file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
0010_auto_20200407_1447.py
# Generated by Django 2.2.9 on 2020-04-07 14:47 from django.db import migrations class Migration(migrations.Migration):
dependencies = [ ('application', '0009_auto_20200407_1208'), ] operations = [ migrations.RemoveField( model_name='collections', name='subtitles_en', ), migrations.RemoveField( model_name='collections', name='subtitles_fi', ), migrations.RemoveField( model_name='collections', name='subtitles_sv', ), ]
urls.py
# -*- coding: utf-8 -*- # @Time : 2021/2/10 下午12:59 # @Author : 司云中 # @File : urls.py # @Software: Pycharm from django.conf import settings from django.urls import path, include from manager_app.apis.auth_api import ManagerLoginApiView, ManagerRegisterApiView
from manager_app.apis.manage_role_api import ManageRoleApiView from manager_app.apis.manage_seller_api import ManagerSellerPermApiView, ManagerSellerRoleApiView app_name = "manager_app" auth_patterns = [ path('login/', ManagerLoginApiView.as_view()), path('register/', ManagerRegisterApiView.as_view()), ] urlpatterns = { path(f'{settings.URL_PREFIX}/auth/', include(auth_patterns)), path(f'{settings.URL_PREFIX}/role/', ManageRoleApiView.as_view()), path(f'{settings.URL_PREFIX}/permission/', ManagePermissionApiView.as_view()), path(f'{settings.URL_PREFIX}/commodity-category/', ManagerCommodityCategoryApiView.as_view()), path(f'{settings.URL_PREFIX}/commodity-group/', ManageCommodityGroupApiView.as_view()), path(f'{settings.URL_PREFIX}/role/seller/', ManagerSellerRoleApiView.as_view()), path(f'{settings.URL_PREFIX}/permission/seller/', ManagerSellerPermApiView.as_view()), path(f'{settings.URL_PREFIX}/carousel/', ManageCarouselApiView.as_view()) }
from manager_app.apis.manage_carousel_api import ManageCarouselApiView from manager_app.apis.manage_commodity_api import ManagerCommodityCategoryApiView, ManageCommodityGroupApiView from manager_app.apis.manage_permission_api import ManagePermissionApiView
tasks_list.go
// Copyright 2012-present Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "fmt" "net/url" "strings" "gopkg.in/olivere/elastic.v3/uritemplates" ) // TasksListService retrieves the list of currently executing tasks // on one ore more nodes in the cluster. It is part of the Task Management API // documented at http://www.elastic.co/guide/en/elasticsearch/reference/master/tasks-list.html. // // It is supported as of Elasticsearch 2.3.0. type TasksListService struct { client *Client pretty bool taskId []int64 actions []string detailed *bool nodeId []string parentNode string parentTask *int64 waitForCompletion *bool } // NewTasksListService creates a new TasksListService. func NewTasksListService(client *Client) *TasksListService { return &TasksListService{ client: client, taskId: make([]int64, 0), actions: make([]string, 0), nodeId: make([]string, 0), } } // TaskId indicates to returns the task(s) with specified id(s). func (s *TasksListService) TaskId(taskId ...int64) *TasksListService { s.taskId = append(s.taskId, taskId...) return s } // Actions is a list of actions that should be returned. Leave empty to return all. func (s *TasksListService) Actions(actions ...string) *TasksListService { s.actions = append(s.actions, actions...) return s } // Detailed indicates whether to return detailed task information (default: false). func (s *TasksListService) Detailed(detailed bool) *TasksListService { s.detailed = &detailed return s } // NodeId is a list of node IDs or names to limit the returned information; // use `_local` to return information from the node you're connecting to, // leave empty to get information from all nodes. func (s *TasksListService) NodeId(nodeId ...string) *TasksListService { s.nodeId = append(s.nodeId, nodeId...) return s } // ParentNode returns tasks with specified parent node. func (s *TasksListService) ParentNode(parentNode string) *TasksListService { s.parentNode = parentNode return s } // ParentTask returns tasks with specified parent task id. Set to -1 to return all. func (s *TasksListService) ParentTask(parentTask int64) *TasksListService { s.parentTask = &parentTask return s } // WaitForCompletion indicates whether to wait for the matching tasks // to complete (default: false). func (s *TasksListService) WaitForCompletion(waitForCompletion bool) *TasksListService { s.waitForCompletion = &waitForCompletion return s } // Pretty indicates that the JSON response be indented and human readable. func (s *TasksListService) Pretty(pretty bool) *TasksListService { s.pretty = pretty return s } // buildURL builds the URL for the operation. func (s *TasksListService) buildURL() (string, url.Values, error) { // Build URL var err error var path string if len(s.taskId) > 0 { var tasks []string for _, taskId := range s.taskId { tasks = append(tasks, fmt.Sprintf("%d", taskId)) } path, err = uritemplates.Expand("/_tasks/{task_id}", map[string]string{ "task_id": strings.Join(tasks, ","), }) } else { path = "/_tasks" } if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} if s.pretty { params.Set("pretty", "1") } if len(s.actions) > 0 { params.Set("actions", strings.Join(s.actions, ",")) } if s.detailed != nil { params.Set("detailed", fmt.Sprintf("%v", *s.detailed)) } if len(s.nodeId) > 0 { params.Set("node_id", strings.Join(s.nodeId, ",")) } if s.parentNode != "" { params.Set("parent_node", s.parentNode) } if s.parentTask != nil { params.Set("parent_task", fmt.Sprintf("%v", *s.parentTask)) } if s.waitForCompletion != nil { params.Set("wait_for_completion", fmt.Sprintf("%v", *s.waitForCompletion)) } return path, params, nil } // Validate checks if the operation is valid. func (s *TasksListService) Validate() error { return nil } // Do executes the operation. func (s *TasksListService) Do() (*TasksListResponse, error) { // Check pre-conditions if err := s.Validate(); err != nil { return nil, err } // Get URL for request path, params, err := s.buildURL() if err != nil { return nil, err } // Get HTTP response res, err := s.client.PerformRequest("GET", path, params, nil) if err != nil {
// Return operation response ret := new(TasksListResponse) if err := s.client.decoder.Decode(res.Body, ret); err != nil { return nil, err } return ret, nil } // TasksListResponse is the response of TasksListService.Do. type TasksListResponse struct { TaskFailures []*TaskOperationFailure `json:"task_failures"` NodeFailures []*FailedNodeException `json:"node_failures"` // Nodes returns the tasks per node. The key is the node id. Nodes map[string]*DiscoveryNode `json:"nodes"` } type TaskOperationFailure struct { TaskId int64 `json:"task_id"` NodeId string `json:"node_id"` Status string `json:"status"` Reason *ErrorDetails `json:"reason"` } type FailedNodeException struct { *ErrorDetails NodeId string `json:"node_id"` } type DiscoveryNode struct { Name string `json:"name"` TransportAddress string `json:"transport_address"` Host string `json:"host"` IP string `json:"ip"` Attributes map[string]interface{} `json:"attributes"` // Tasks returns the tasks by its id (as a string). Tasks map[string]*TaskInfo `json:"tasks"` } type TaskInfo struct { Node string `json:"node"` Id int64 `json:"id"` // the task id Type string `json:"type"` Action string `json:"action"` Status interface{} `json:"status"` Description interface{} `json:"description"` StartTime string `json:"start_time"` StartTimeInMillis int64 `json:"start_time_in_millis"` RunningTime string `json:"running_time"` RunningTimeInNanos int64 `json:"running_time_in_nanos"` ParentTaskId string `json:"parent_task_id"` // like "YxJnVYjwSBm_AUbzddTajQ:12356" }
return nil, err }
ibm_cloud_databases_v5.go
/** * (C) Copyright IBM Corp. 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * IBM OpenAPI SDK Code Generator Version: 3.24.0-fac1d4cc-20210108-162022 */ // Package ibmclouddatabasesv5 : Operations and models for the IbmCloudDatabasesV5 service package ibmclouddatabasesv5 import ( "context" "encoding/json" "fmt" common "github.com/IBM/experimental-go-sdk/common" "github.com/IBM/go-sdk-core/v4/core" "github.com/go-openapi/strfmt" "net/http" "reflect" "time" ) // IbmCloudDatabasesV5 : The IBM Cloud Databases API enables interaction between applications and Cloud Databases // database deployments. // // Access to the API requires an IAM Bearer Token or an IAM API Key to be presented through bearer authentication. // // Deployment IDs are CRNs on the IBM Cloud Databases v5 API platform. No lookup or translation the Compose style UUIDs // is needed. The Deployment ID is a traditional UUID on the Compose v5 API platform. // // When you use CRNs, remember to URL escape the CRN value as they can include the forward-slash (/) character. // // Version: 5.0.0 type IbmCloudDatabasesV5 struct { Service *core.BaseService } // DefaultServiceName is the default key used to find external configuration information. const DefaultServiceName = "ibm_cloud_databases" // IbmCloudDatabasesV5Options : Service options type IbmCloudDatabasesV5Options struct { ServiceName string URL string Authenticator core.Authenticator } // NewIbmCloudDatabasesV5UsingExternalConfig : constructs an instance of IbmCloudDatabasesV5 with passed in options and external configuration. func NewIbmCloudDatabasesV5UsingExternalConfig(options *IbmCloudDatabasesV5Options) (ibmCloudDatabases *IbmCloudDatabasesV5, err error) { if options.ServiceName == "" { options.ServiceName = DefaultServiceName } if options.Authenticator == nil { options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName) if err != nil { return } } ibmCloudDatabases, err = NewIbmCloudDatabasesV5(options) if err != nil { return } err = ibmCloudDatabases.Service.ConfigureService(options.ServiceName) if err != nil { return } if options.URL != "" { err = ibmCloudDatabases.Service.SetServiceURL(options.URL) } return } // NewIbmCloudDatabasesV5 : constructs an instance of IbmCloudDatabasesV5 with passed in options. func NewIbmCloudDatabasesV5(options *IbmCloudDatabasesV5Options) (service *IbmCloudDatabasesV5, err error) { serviceOptions := &core.ServiceOptions{ Authenticator: options.Authenticator, } baseService, err := core.NewBaseService(serviceOptions) if err != nil { return } if options.URL != "" { err = baseService.SetServiceURL(options.URL) if err != nil { return } } service = &IbmCloudDatabasesV5{ Service: baseService, } return } // GetServiceURLForRegion returns the service URL to be used for the specified region func GetServiceURLForRegion(region string) (string, error) { return "", fmt.Errorf("service does not support regional URLs") } // Clone makes a copy of "ibmCloudDatabases" suitable for processing requests. func (ibmCloudDatabases *IbmCloudDatabasesV5) Clone() *IbmCloudDatabasesV5 { if core.IsNil(ibmCloudDatabases) { return nil } clone := *ibmCloudDatabases clone.Service = ibmCloudDatabases.Service.Clone() return &clone } // SetServiceURL sets the service URL func (ibmCloudDatabases *IbmCloudDatabasesV5) SetServiceURL(url string) error { return ibmCloudDatabases.Service.SetServiceURL(url) } // GetServiceURL returns the service URL func (ibmCloudDatabases *IbmCloudDatabasesV5) GetServiceURL() string { return ibmCloudDatabases.Service.GetServiceURL() } // SetDefaultHeaders sets HTTP headers to be sent in every request func (ibmCloudDatabases *IbmCloudDatabasesV5) SetDefaultHeaders(headers http.Header) { ibmCloudDatabases.Service.SetDefaultHeaders(headers) } // SetEnableGzipCompression sets the service's EnableGzipCompression field func (ibmCloudDatabases *IbmCloudDatabasesV5) SetEnableGzipCompression(enableGzip bool) { ibmCloudDatabases.Service.SetEnableGzipCompression(enableGzip) } // GetEnableGzipCompression returns the service's EnableGzipCompression field func (ibmCloudDatabases *IbmCloudDatabasesV5) GetEnableGzipCompression() bool { return ibmCloudDatabases.Service.GetEnableGzipCompression() } // EnableRetries enables automatic retries for requests invoked for this service instance. // If either parameter is specified as 0, then a default value is used instead. func (ibmCloudDatabases *IbmCloudDatabasesV5) EnableRetries(maxRetries int, maxRetryInterval time.Duration) { ibmCloudDatabases.Service.EnableRetries(maxRetries, maxRetryInterval) } // DisableRetries disables automatic retries for requests invoked for this service instance. func (ibmCloudDatabases *IbmCloudDatabasesV5) DisableRetries() { ibmCloudDatabases.Service.DisableRetries() } // GetDeployables : Get all deployable databases // Returns a list of all the types and associated major versions of database deployments that can be provisioned. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeployables(getDeployablesOptions *GetDeployablesOptions) (result *GetDeployablesResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDeployablesWithContext(context.Background(), getDeployablesOptions) } // GetDeployablesWithContext is an alternate form of the GetDeployables method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeployablesWithContext(ctx context.Context, getDeployablesOptions *GetDeployablesOptions) (result *GetDeployablesResponse, response *core.DetailedResponse, err error) { err = core.ValidateStruct(getDeployablesOptions, "getDeployablesOptions") if err != nil { return } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployables`, nil) if err != nil { return } for headerName, headerValue := range getDeployablesOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDeployables") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetDeployablesResponse) if err != nil { return } response.Result = result return } // GetRegions : Get all deployable regions // Returns a list of all the regions that deployments can be provisioned into from the current region. Used to determine // region availability for read-only replicas. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRegions(getRegionsOptions *GetRegionsOptions) (result *GetRegionsResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetRegionsWithContext(context.Background(), getRegionsOptions) } // GetRegionsWithContext is an alternate form of the GetRegions method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRegionsWithContext(ctx context.Context, getRegionsOptions *GetRegionsOptions) (result *GetRegionsResponse, response *core.DetailedResponse, err error) { err = core.ValidateStruct(getRegionsOptions, "getRegionsOptions") if err != nil { return } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/regions`, nil) if err != nil { return } for headerName, headerValue := range getRegionsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetRegions") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetRegionsResponse) if err != nil { return } response.Result = result return } // GetDeploymentInfo : Get deployment information // Gets the full data that is associated with a deployment. This data includes the ID, name, database type, and version. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentInfo(getDeploymentInfoOptions *GetDeploymentInfoOptions) (result *GetDeploymentInfoResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDeploymentInfoWithContext(context.Background(), getDeploymentInfoOptions) } // GetDeploymentInfoWithContext is an alternate form of the GetDeploymentInfo method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentInfoWithContext(ctx context.Context, getDeploymentInfoOptions *GetDeploymentInfoOptions) (result *GetDeploymentInfoResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDeploymentInfoOptions, "getDeploymentInfoOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDeploymentInfoOptions, "getDeploymentInfoOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getDeploymentInfoOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDeploymentInfoOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDeploymentInfo") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetDeploymentInfoResponse) if err != nil { return } response.Result = result return } // CreateDatabaseUser : Creates a user based on user type // Creates a user in the database that can access the database through a connection. func (ibmCloudDatabases *IbmCloudDatabasesV5) CreateDatabaseUser(createDatabaseUserOptions *CreateDatabaseUserOptions) (result *CreateDatabaseUserResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.CreateDatabaseUserWithContext(context.Background(), createDatabaseUserOptions) } // CreateDatabaseUserWithContext is an alternate form of the CreateDatabaseUser method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) CreateDatabaseUserWithContext(ctx context.Context, createDatabaseUserOptions *CreateDatabaseUserOptions) (result *CreateDatabaseUserResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(createDatabaseUserOptions, "createDatabaseUserOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(createDatabaseUserOptions, "createDatabaseUserOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *createDatabaseUserOptions.ID, "user_type": *createDatabaseUserOptions.UserType, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range createDatabaseUserOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "CreateDatabaseUser") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if createDatabaseUserOptions.User != nil { body["user"] = createDatabaseUserOptions.User } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalCreateDatabaseUserResponse) if err != nil { return } response.Result = result return } // ChangeUserPassword : Set specified user's password // Sets the password of a specified user. func (ibmCloudDatabases *IbmCloudDatabasesV5) ChangeUserPassword(changeUserPasswordOptions *ChangeUserPasswordOptions) (result *ChangeUserPasswordResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.ChangeUserPasswordWithContext(context.Background(), changeUserPasswordOptions) } // ChangeUserPasswordWithContext is an alternate form of the ChangeUserPassword method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) ChangeUserPasswordWithContext(ctx context.Context, changeUserPasswordOptions *ChangeUserPasswordOptions) (result *ChangeUserPasswordResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(changeUserPasswordOptions, "changeUserPasswordOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(changeUserPasswordOptions, "changeUserPasswordOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *changeUserPasswordOptions.ID, "user_type": *changeUserPasswordOptions.UserType, "username": *changeUserPasswordOptions.Username, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{username}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range changeUserPasswordOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "ChangeUserPassword") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if changeUserPasswordOptions.User != nil { body["user"] = changeUserPasswordOptions.User } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalChangeUserPasswordResponse) if err != nil { return } response.Result = result return } // DeleteDatabaseUser : Deletes a user based on user type // Removes a user from the deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteDatabaseUser(deleteDatabaseUserOptions *DeleteDatabaseUserOptions) (result *DeleteDatabaseUserResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.DeleteDatabaseUserWithContext(context.Background(), deleteDatabaseUserOptions) } // DeleteDatabaseUserWithContext is an alternate form of the DeleteDatabaseUser method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteDatabaseUserWithContext(ctx context.Context, deleteDatabaseUserOptions *DeleteDatabaseUserOptions) (result *DeleteDatabaseUserResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(deleteDatabaseUserOptions, "deleteDatabaseUserOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(deleteDatabaseUserOptions, "deleteDatabaseUserOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *deleteDatabaseUserOptions.ID, "user_type": *deleteDatabaseUserOptions.UserType, "username": *deleteDatabaseUserOptions.Username, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{username}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range deleteDatabaseUserOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "DeleteDatabaseUser") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteDatabaseUserResponse) if err != nil { return } response.Result = result return } // GetUser : Discover user name and password information for a deployment for a user with an endpoint type // Only for Redis v5 and prior: Discover connection information for a deployment for a user with an endpoint type. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetUser(getUserOptions *GetUserOptions) (result *Task, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetUserWithContext(context.Background(), getUserOptions) } // GetUserWithContext is an alternate form of the GetUser method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetUserWithContext(ctx context.Context, getUserOptions *GetUserOptions) (result *Task, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getUserOptions, "getUserOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getUserOptions, "getUserOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getUserOptions.ID, "user_id": *getUserOptions.UserID, "endpoint_type": *getUserOptions.EndpointType, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_id}/`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getUserOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetUser") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTask) if err != nil { return } response.Result = result return } // SetDatabaseConfiguration : Change your database configuration // Change your database configuration. Available for PostgreSQL, EnterpriseDB, and Redis ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) SetDatabaseConfiguration(setDatabaseConfigurationOptions *SetDatabaseConfigurationOptions) (result *SetDatabaseConfigurationResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.SetDatabaseConfigurationWithContext(context.Background(), setDatabaseConfigurationOptions) } // SetDatabaseConfigurationWithContext is an alternate form of the SetDatabaseConfiguration method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) SetDatabaseConfigurationWithContext(ctx context.Context, setDatabaseConfigurationOptions *SetDatabaseConfigurationOptions) (result *SetDatabaseConfigurationResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(setDatabaseConfigurationOptions, "setDatabaseConfigurationOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(setDatabaseConfigurationOptions, "setDatabaseConfigurationOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *setDatabaseConfigurationOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/configuration`, pathParamsMap) if err != nil { return } for headerName, headerValue := range setDatabaseConfigurationOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "SetDatabaseConfiguration") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if setDatabaseConfigurationOptions.Configuration != nil { body["configuration"] = setDatabaseConfigurationOptions.Configuration } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetDatabaseConfigurationResponse) if err != nil { return } response.Result = result return } // GetDatabaseConfigurationSchema : Get the schema of the database configuration // Get the schema of the database configuration. Available for PostgreSQL and Redis ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDatabaseConfigurationSchema(getDatabaseConfigurationSchemaOptions *GetDatabaseConfigurationSchemaOptions) (result *GetDatabaseConfigurationSchemaResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDatabaseConfigurationSchemaWithContext(context.Background(), getDatabaseConfigurationSchemaOptions) } // GetDatabaseConfigurationSchemaWithContext is an alternate form of the GetDatabaseConfigurationSchema method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDatabaseConfigurationSchemaWithContext(ctx context.Context, getDatabaseConfigurationSchemaOptions *GetDatabaseConfigurationSchemaOptions) (result *GetDatabaseConfigurationSchemaResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDatabaseConfigurationSchemaOptions, "getDatabaseConfigurationSchemaOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDatabaseConfigurationSchemaOptions, "getDatabaseConfigurationSchemaOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getDatabaseConfigurationSchemaOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/configuration/schema`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDatabaseConfigurationSchemaOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDatabaseConfigurationSchema") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetDatabaseConfigurationSchemaResponse) if err != nil { return } response.Result = result return } // GetRemotes : Get read-only replica information // Get the read-only replicas associated with a deployment. Available for PostgreSQL and EnterpriseDB ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRemotes(getRemotesOptions *GetRemotesOptions) (result *GetRemotesResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetRemotesWithContext(context.Background(), getRemotesOptions) } // GetRemotesWithContext is an alternate form of the GetRemotes method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRemotesWithContext(ctx context.Context, getRemotesOptions *GetRemotesOptions) (result *GetRemotesResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getRemotesOptions, "getRemotesOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getRemotesOptions, "getRemotesOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getRemotesOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/remotes`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getRemotesOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetRemotes") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetRemotesResponse) if err != nil { return } response.Result = result return } // SetRemotes : Modify read-only replication on a deployment // Promote a read-only remote replica to leader by calling with leader set to an empty string. Available for PostgreSQL // and EnterpriseDB ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) SetRemotes(setRemotesOptions *SetRemotesOptions) (result *SetRemotesResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.SetRemotesWithContext(context.Background(), setRemotesOptions) } // SetRemotesWithContext is an alternate form of the SetRemotes method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) SetRemotesWithContext(ctx context.Context, setRemotesOptions *SetRemotesOptions) (result *SetRemotesResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(setRemotesOptions, "setRemotesOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(setRemotesOptions, "setRemotesOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *setRemotesOptions.ID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/remotes`, pathParamsMap) if err != nil { return } for headerName, headerValue := range setRemotesOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "SetRemotes") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if setRemotesOptions.Remotes != nil { body["remotes"] = setRemotesOptions.Remotes } if setRemotesOptions.SkipInitialBackup != nil { body["skip_initial_backup"] = setRemotesOptions.SkipInitialBackup } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetRemotesResponse) if err != nil { return } response.Result = result return } // GetRemotesSchema : Resync read-only replica // Reinitialize a read-only replica. Available for PostgreSQL and EnterpriseDB ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRemotesSchema(getRemotesSchemaOptions *GetRemotesSchemaOptions) (result *GetRemotesSchemaResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetRemotesSchemaWithContext(context.Background(), getRemotesSchemaOptions) } // GetRemotesSchemaWithContext is an alternate form of the GetRemotesSchema method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetRemotesSchemaWithContext(ctx context.Context, getRemotesSchemaOptions *GetRemotesSchemaOptions) (result *GetRemotesSchemaResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getRemotesSchemaOptions, "getRemotesSchemaOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getRemotesSchemaOptions, "getRemotesSchemaOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getRemotesSchemaOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/remotes/resync`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getRemotesSchemaOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetRemotesSchema") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetRemotesSchemaResponse) if err != nil { return } response.Result = result return } // SetPromotion : Promote read-only replica to a full deployment // Promote a read-only replica or upgrade and promote a read-only replica. Available for PostgreSQL and EnterpriseDB // ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) SetPromotion(setPromotionOptions *SetPromotionOptions) (result *SetPromotionResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.SetPromotionWithContext(context.Background(), setPromotionOptions) } // SetPromotionWithContext is an alternate form of the SetPromotion method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) SetPromotionWithContext(ctx context.Context, setPromotionOptions *SetPromotionOptions) (result *SetPromotionResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(setPromotionOptions, "setPromotionOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(setPromotionOptions, "setPromotionOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *setPromotionOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/remotes/promotion`, pathParamsMap) if err != nil { return } for headerName, headerValue := range setPromotionOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "SetPromotion") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if setPromotionOptions.Promotion != nil { body["Promotion"] = setPromotionOptions.Promotion } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetPromotionResponse) if err != nil { return } response.Result = result return } // GetDeploymentTasks : Get currently running tasks on a deployment // Obtain a list of tasks currently running or recently run on a deployment. Tasks are ephemeral. Records of successful // tasks are shown for 24-48 hours, and unsuccessful tasks are shown for 7-8 days. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentTasks(getDeploymentTasksOptions *GetDeploymentTasksOptions) (result *Tasks, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDeploymentTasksWithContext(context.Background(), getDeploymentTasksOptions) } // GetDeploymentTasksWithContext is an alternate form of the GetDeploymentTasks method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentTasksWithContext(ctx context.Context, getDeploymentTasksOptions *GetDeploymentTasksOptions) (result *Tasks, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDeploymentTasksOptions, "getDeploymentTasksOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDeploymentTasksOptions, "getDeploymentTasksOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getDeploymentTasksOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/tasks`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDeploymentTasksOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDeploymentTasks") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalTasks) if err != nil { return } response.Result = result return } // GetTasks : Get information about a task // Get information about a task and its status. Tasks themselves are persistent so old tasks can be consulted as well as // running tasks. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetTasks(getTasksOptions *GetTasksOptions) (result *GetTasksResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetTasksWithContext(context.Background(), getTasksOptions) } // GetTasksWithContext is an alternate form of the GetTasks method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetTasksWithContext(ctx context.Context, getTasksOptions *GetTasksOptions) (result *GetTasksResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getTasksOptions, "getTasksOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getTasksOptions, "getTasksOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getTasksOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/tasks/{id}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getTasksOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetTasks") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetTasksResponse) if err != nil { return } response.Result = result return } // GetBackupInfo : Get information about a backup // Get information about a backup, such as creation date. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetBackupInfo(getBackupInfoOptions *GetBackupInfoOptions) (result *GetBackupInfoResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetBackupInfoWithContext(context.Background(), getBackupInfoOptions) } // GetBackupInfoWithContext is an alternate form of the GetBackupInfo method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetBackupInfoWithContext(ctx context.Context, getBackupInfoOptions *GetBackupInfoOptions) (result *GetBackupInfoResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getBackupInfoOptions, "getBackupInfoOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getBackupInfoOptions, "getBackupInfoOptions") if err != nil { return } pathParamsMap := map[string]string{ "backup_id": *getBackupInfoOptions.BackupID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/backups/{backup_id}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getBackupInfoOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetBackupInfo") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetBackupInfoResponse) if err != nil { return } response.Result = result return } // GetDeploymentBackups : Get currently available backups from a deployment // Get details of all currently available backups from a deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentBackups(getDeploymentBackupsOptions *GetDeploymentBackupsOptions) (result *Backups, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDeploymentBackupsWithContext(context.Background(), getDeploymentBackupsOptions) } // GetDeploymentBackupsWithContext is an alternate form of the GetDeploymentBackups method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentBackupsWithContext(ctx context.Context, getDeploymentBackupsOptions *GetDeploymentBackupsOptions) (result *Backups, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDeploymentBackupsOptions, "getDeploymentBackupsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDeploymentBackupsOptions, "getDeploymentBackupsOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getDeploymentBackupsOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/backups`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDeploymentBackupsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDeploymentBackups") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalBackups) if err != nil { return } response.Result = result return } // StartOndemandBackup : Initiate an on-demand backup // Signal the platform to create an on-demand backup for the specified deployment. The returned task can be polled to // track progress of the backup as it takes place. func (ibmCloudDatabases *IbmCloudDatabasesV5) StartOndemandBackup(startOndemandBackupOptions *StartOndemandBackupOptions) (result *StartOndemandBackupResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.StartOndemandBackupWithContext(context.Background(), startOndemandBackupOptions) } // StartOndemandBackupWithContext is an alternate form of the StartOndemandBackup method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) StartOndemandBackupWithContext(ctx context.Context, startOndemandBackupOptions *StartOndemandBackupOptions) (result *StartOndemandBackupResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(startOndemandBackupOptions, "startOndemandBackupOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(startOndemandBackupOptions, "startOndemandBackupOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *startOndemandBackupOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/backups`, pathParamsMap) if err != nil { return } for headerName, headerValue := range startOndemandBackupOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "StartOndemandBackup") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalStartOndemandBackupResponse) if err != nil { return } response.Result = result return } // GetPITRdata : Get earliest point-in-time-recovery timestamp // Returns the earliest available time for point-in-time-recovery in ISO8601 UTC format. PostgreSQL and EnterpriseDB // only. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetPITRdata(getPITRdataOptions *GetPITRdataOptions) (result *PointInTimeRecoveryData, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetPITRdataWithContext(context.Background(), getPITRdataOptions) } // GetPITRdataWithContext is an alternate form of the GetPITRdata method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetPITRdataWithContext(ctx context.Context, getPITRdataOptions *GetPITRdataOptions) (result *PointInTimeRecoveryData, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getPITRdataOptions, "getPITRdataOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getPITRdataOptions, "getPITRdataOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getPITRdataOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/point_in_time_recovery_data`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getPITRdataOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetPITRdata") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalPointInTimeRecoveryData) if err != nil { return } response.Result = result return } // GetConnection : Discover connection information for a deployment for a user with an endpoint type // Discover connection information for a deployment for a user with an endpoint type. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetConnection(getConnectionOptions *GetConnectionOptions) (result *Connection, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetConnectionWithContext(context.Background(), getConnectionOptions) } // GetConnectionWithContext is an alternate form of the GetConnection method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetConnectionWithContext(ctx context.Context, getConnectionOptions *GetConnectionOptions) (result *Connection, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getConnectionOptions, "getConnectionOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getConnectionOptions, "getConnectionOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getConnectionOptions.ID, "user_type": *getConnectionOptions.UserType, "user_id": *getConnectionOptions.UserID, "endpoint_type": *getConnectionOptions.EndpointType, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{user_id}/connections/{endpoint_type}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetConnection") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") if getConnectionOptions.CertificateRoot != nil { builder.AddQuery("certificate_root", fmt.Sprint(*getConnectionOptions.CertificateRoot)) } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalConnection) if err != nil { return } response.Result = result return } // CompleteConnection : Discover connection information for a deployment for a user with substitutions and an endpoint type // Discover connection information for a deployment for a user. Behaves the same as the GET method but substitutes the // provided password parameter into the returned connection information. func (ibmCloudDatabases *IbmCloudDatabasesV5) CompleteConnection(completeConnectionOptions *CompleteConnectionOptions) (result *Connection, response *core.DetailedResponse, err error) { return ibmCloudDatabases.CompleteConnectionWithContext(context.Background(), completeConnectionOptions) } // CompleteConnectionWithContext is an alternate form of the CompleteConnection method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) CompleteConnectionWithContext(ctx context.Context, completeConnectionOptions *CompleteConnectionOptions) (result *Connection, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(completeConnectionOptions, "completeConnectionOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(completeConnectionOptions, "completeConnectionOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *completeConnectionOptions.ID, "user_type": *completeConnectionOptions.UserType, "user_id": *completeConnectionOptions.UserID, "endpoint_type": *completeConnectionOptions.EndpointType, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{user_id}/connections/{endpoint_type}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range completeConnectionOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "CompleteConnection") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if completeConnectionOptions.Password != nil { body["password"] = completeConnectionOptions.Password } if completeConnectionOptions.CertificateRoot != nil { body["certificate_root"] = completeConnectionOptions.CertificateRoot } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalConnection) if err != nil { return } response.Result = result return } // GetConnectionDeprecated : Discover connection information for a deployment for a user // Discover connection information for a deployment for a user. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetConnectionDeprecated(getConnectionDeprecatedOptions *GetConnectionDeprecatedOptions) (result *Connection, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetConnectionDeprecatedWithContext(context.Background(), getConnectionDeprecatedOptions) } // GetConnectionDeprecatedWithContext is an alternate form of the GetConnectionDeprecated method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetConnectionDeprecatedWithContext(ctx context.Context, getConnectionDeprecatedOptions *GetConnectionDeprecatedOptions) (result *Connection, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getConnectionDeprecatedOptions, "getConnectionDeprecatedOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getConnectionDeprecatedOptions, "getConnectionDeprecatedOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getConnectionDeprecatedOptions.ID, "user_type": *getConnectionDeprecatedOptions.UserType, "user_id": *getConnectionDeprecatedOptions.UserID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{user_id}/connections`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getConnectionDeprecatedOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetConnectionDeprecated") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") if getConnectionDeprecatedOptions.CertificateRoot != nil { builder.AddQuery("certificate_root", fmt.Sprint(*getConnectionDeprecatedOptions.CertificateRoot)) } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalConnection) if err != nil { return } response.Result = result return } // CompleteConnectionDeprecated : Discover connection information for a deployment for a user with substitutions // Discover connection information for a deployment for a user. Behaves the same as the GET method but substitutes the // given password parameter into the returned connection information. func (ibmCloudDatabases *IbmCloudDatabasesV5) CompleteConnectionDeprecated(completeConnectionDeprecatedOptions *CompleteConnectionDeprecatedOptions) (result *Connection, response *core.DetailedResponse, err error) { return ibmCloudDatabases.CompleteConnectionDeprecatedWithContext(context.Background(), completeConnectionDeprecatedOptions) } // CompleteConnectionDeprecatedWithContext is an alternate form of the CompleteConnectionDeprecated method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) CompleteConnectionDeprecatedWithContext(ctx context.Context, completeConnectionDeprecatedOptions *CompleteConnectionDeprecatedOptions) (result *Connection, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(completeConnectionDeprecatedOptions, "completeConnectionDeprecatedOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(completeConnectionDeprecatedOptions, "completeConnectionDeprecatedOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *completeConnectionDeprecatedOptions.ID, "user_type": *completeConnectionDeprecatedOptions.UserType, "user_id": *completeConnectionDeprecatedOptions.UserID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/users/{user_type}/{user_id}/connections`, pathParamsMap) if err != nil { return } for headerName, headerValue := range completeConnectionDeprecatedOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "CompleteConnectionDeprecated") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if completeConnectionDeprecatedOptions.Password != nil { body["password"] = completeConnectionDeprecatedOptions.Password } if completeConnectionDeprecatedOptions.CertificateRoot != nil { body["certificate_root"] = completeConnectionDeprecatedOptions.CertificateRoot } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalConnection) if err != nil { return } response.Result = result return } // GetDeploymentScalingGroups : Get currently available scaling groups from a deployment // Scaling groups represent the various resources that are allocated to a deployment. This command allows for the // retrieval of all of the groups for a particular deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentScalingGroups(getDeploymentScalingGroupsOptions *GetDeploymentScalingGroupsOptions) (result *Groups, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDeploymentScalingGroupsWithContext(context.Background(), getDeploymentScalingGroupsOptions) } // GetDeploymentScalingGroupsWithContext is an alternate form of the GetDeploymentScalingGroups method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDeploymentScalingGroupsWithContext(ctx context.Context, getDeploymentScalingGroupsOptions *GetDeploymentScalingGroupsOptions) (result *Groups, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDeploymentScalingGroupsOptions, "getDeploymentScalingGroupsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDeploymentScalingGroupsOptions, "getDeploymentScalingGroupsOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getDeploymentScalingGroupsOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/groups`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDeploymentScalingGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDeploymentScalingGroups") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGroups) if err != nil { return } response.Result = result return } // GetDefaultScalingGroups : Get default scaling groups for a new deployment // Scaling groups represent the various resources allocated to a deployment. When a new deployment is created, there are // a set of defaults for each database type. This endpoint returns them for a particular database. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDefaultScalingGroups(getDefaultScalingGroupsOptions *GetDefaultScalingGroupsOptions) (result *Groups, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetDefaultScalingGroupsWithContext(context.Background(), getDefaultScalingGroupsOptions) } // GetDefaultScalingGroupsWithContext is an alternate form of the GetDefaultScalingGroups method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetDefaultScalingGroupsWithContext(ctx context.Context, getDefaultScalingGroupsOptions *GetDefaultScalingGroupsOptions) (result *Groups, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getDefaultScalingGroupsOptions, "getDefaultScalingGroupsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getDefaultScalingGroupsOptions, "getDefaultScalingGroupsOptions") if err != nil { return } pathParamsMap := map[string]string{ "type": *getDefaultScalingGroupsOptions.Type, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployables/{type}/groups`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getDefaultScalingGroupsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetDefaultScalingGroups") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGroups) if err != nil { return } response.Result = result return } // SetDeploymentScalingGroup : Set scaling values on a specified group // Set scaling value on a specified group. Can only be performed on is_adjustable=true groups. Values set are for the // group as a whole and resources are distributed amongst the group. Values must be greater than or equal to the minimum // size and must be a multiple of the step size. func (ibmCloudDatabases *IbmCloudDatabasesV5) SetDeploymentScalingGroup(setDeploymentScalingGroupOptions *SetDeploymentScalingGroupOptions) (result *SetDeploymentScalingGroupResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.SetDeploymentScalingGroupWithContext(context.Background(), setDeploymentScalingGroupOptions) } // SetDeploymentScalingGroupWithContext is an alternate form of the SetDeploymentScalingGroup method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) SetDeploymentScalingGroupWithContext(ctx context.Context, setDeploymentScalingGroupOptions *SetDeploymentScalingGroupOptions) (result *SetDeploymentScalingGroupResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(setDeploymentScalingGroupOptions, "setDeploymentScalingGroupOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(setDeploymentScalingGroupOptions, "setDeploymentScalingGroupOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *setDeploymentScalingGroupOptions.ID, "group_id": *setDeploymentScalingGroupOptions.GroupID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/groups/{group_id}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range setDeploymentScalingGroupOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "SetDeploymentScalingGroup") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") _, err = builder.SetBodyContentJSON(setDeploymentScalingGroupOptions.SetDeploymentScalingGroupRequest) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetDeploymentScalingGroupResponse) if err != nil { return } response.Result = result return } // GetAutoscalingConditions : Get the autoscaling configuration from a deployment // The Autoscaling configuration represents the various conditions that control autoscaling for a deployment. This // command allows for the retrieval of all autoscaling conditions for a particular deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetAutoscalingConditions(getAutoscalingConditionsOptions *GetAutoscalingConditionsOptions) (result *GetAutoscalingConditionsResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetAutoscalingConditionsWithContext(context.Background(), getAutoscalingConditionsOptions) } // GetAutoscalingConditionsWithContext is an alternate form of the GetAutoscalingConditions method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetAutoscalingConditionsWithContext(ctx context.Context, getAutoscalingConditionsOptions *GetAutoscalingConditionsOptions) (result *GetAutoscalingConditionsResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getAutoscalingConditionsOptions, "getAutoscalingConditionsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getAutoscalingConditionsOptions, "getAutoscalingConditionsOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getAutoscalingConditionsOptions.ID, "group_id": *getAutoscalingConditionsOptions.GroupID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/groups/{group_id}/autoscaling`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getAutoscalingConditionsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetAutoscalingConditions") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalGetAutoscalingConditionsResponse) if err != nil {
response.Result = result return } // SetAutoscalingConditions : Set the autoscaling configuration from a deployment // Enable, disable, or set the conditions for autoscaling on your deployment. Memory, disk, and CPU (if available) can // be set separately and are not all required. func (ibmCloudDatabases *IbmCloudDatabasesV5) SetAutoscalingConditions(setAutoscalingConditionsOptions *SetAutoscalingConditionsOptions) (result *SetAutoscalingConditionsResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.SetAutoscalingConditionsWithContext(context.Background(), setAutoscalingConditionsOptions) } // SetAutoscalingConditionsWithContext is an alternate form of the SetAutoscalingConditions method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) SetAutoscalingConditionsWithContext(ctx context.Context, setAutoscalingConditionsOptions *SetAutoscalingConditionsOptions) (result *SetAutoscalingConditionsResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(setAutoscalingConditionsOptions, "setAutoscalingConditionsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(setAutoscalingConditionsOptions, "setAutoscalingConditionsOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *setAutoscalingConditionsOptions.ID, "group_id": *setAutoscalingConditionsOptions.GroupID, } builder := core.NewRequestBuilder(core.PATCH) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/groups/{group_id}/autoscaling`, pathParamsMap) if err != nil { return } for headerName, headerValue := range setAutoscalingConditionsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "SetAutoscalingConditions") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if setAutoscalingConditionsOptions.Autoscaling != nil { body["autoscaling"] = setAutoscalingConditionsOptions.Autoscaling } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalSetAutoscalingConditionsResponse) if err != nil { return } response.Result = result return } // KillConnections : Kill connections to a PostgreSQL or EnterpriseDB deployment // Closes all the connections on a deployment. Available for PostgreSQL and EnterpriseDB ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) KillConnections(killConnectionsOptions *KillConnectionsOptions) (result *KillConnectionsResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.KillConnectionsWithContext(context.Background(), killConnectionsOptions) } // KillConnectionsWithContext is an alternate form of the KillConnections method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) KillConnectionsWithContext(ctx context.Context, killConnectionsOptions *KillConnectionsOptions) (result *KillConnectionsResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(killConnectionsOptions, "killConnectionsOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(killConnectionsOptions, "killConnectionsOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *killConnectionsOptions.ID, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/management/database_connections`, pathParamsMap) if err != nil { return } for headerName, headerValue := range killConnectionsOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "KillConnections") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalKillConnectionsResponse) if err != nil { return } response.Result = result return } // FileSync : Sync files uploaded to Elasticsearch deployment // Starts a task that writes files to disk. Available for Elasticsearch ONLY. func (ibmCloudDatabases *IbmCloudDatabasesV5) FileSync(fileSyncOptions *FileSyncOptions) (result *FileSyncResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.FileSyncWithContext(context.Background(), fileSyncOptions) } // FileSyncWithContext is an alternate form of the FileSync method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) FileSyncWithContext(ctx context.Context, fileSyncOptions *FileSyncOptions) (result *FileSyncResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(fileSyncOptions, "fileSyncOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(fileSyncOptions, "fileSyncOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *fileSyncOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/elasticsearch/file_syncs`, pathParamsMap) if err != nil { return } for headerName, headerValue := range fileSyncOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "FileSync") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalFileSyncResponse) if err != nil { return } response.Result = result return } // CreateLogicalReplicationSlot : Create a new logical replication slot // Creates a new logical replication slot on the specified database. For use with PostgreSQL, EnterpriseDB, and wal2json // only. func (ibmCloudDatabases *IbmCloudDatabasesV5) CreateLogicalReplicationSlot(createLogicalReplicationSlotOptions *CreateLogicalReplicationSlotOptions) (result *CreateLogicalReplicationSlotResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.CreateLogicalReplicationSlotWithContext(context.Background(), createLogicalReplicationSlotOptions) } // CreateLogicalReplicationSlotWithContext is an alternate form of the CreateLogicalReplicationSlot method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) CreateLogicalReplicationSlotWithContext(ctx context.Context, createLogicalReplicationSlotOptions *CreateLogicalReplicationSlotOptions) (result *CreateLogicalReplicationSlotResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(createLogicalReplicationSlotOptions, "createLogicalReplicationSlotOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(createLogicalReplicationSlotOptions, "createLogicalReplicationSlotOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *createLogicalReplicationSlotOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/postgresql/logical_replication_slots`, pathParamsMap) if err != nil { return } for headerName, headerValue := range createLogicalReplicationSlotOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "CreateLogicalReplicationSlot") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if createLogicalReplicationSlotOptions.LogicalReplicationSlot != nil { body["logical_replication_slot"] = createLogicalReplicationSlotOptions.LogicalReplicationSlot } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalCreateLogicalReplicationSlotResponse) if err != nil { return } response.Result = result return } // DeleteLogicalReplicationSlot : Delete a logical replication slot // Deletes a logical replication slot from a database. For use with PostgreSQL, EnterpriseDB, and wal2json only. func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteLogicalReplicationSlot(deleteLogicalReplicationSlotOptions *DeleteLogicalReplicationSlotOptions) (result *DeleteLogicalReplicationSlotResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.DeleteLogicalReplicationSlotWithContext(context.Background(), deleteLogicalReplicationSlotOptions) } // DeleteLogicalReplicationSlotWithContext is an alternate form of the DeleteLogicalReplicationSlot method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteLogicalReplicationSlotWithContext(ctx context.Context, deleteLogicalReplicationSlotOptions *DeleteLogicalReplicationSlotOptions) (result *DeleteLogicalReplicationSlotResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(deleteLogicalReplicationSlotOptions, "deleteLogicalReplicationSlotOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(deleteLogicalReplicationSlotOptions, "deleteLogicalReplicationSlotOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *deleteLogicalReplicationSlotOptions.ID, "name": *deleteLogicalReplicationSlotOptions.Name, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/postgresql/logical_replication_slots/{name}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range deleteLogicalReplicationSlotOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "DeleteLogicalReplicationSlot") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteLogicalReplicationSlotResponse) if err != nil { return } response.Result = result return } // GetWhitelist : Retrieve the allowlisted addresses and ranges for a deployment // Retrieve the allowlisted addresses and ranges for a deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) GetWhitelist(getWhitelistOptions *GetWhitelistOptions) (result *Whitelist, response *core.DetailedResponse, err error) { return ibmCloudDatabases.GetWhitelistWithContext(context.Background(), getWhitelistOptions) } // GetWhitelistWithContext is an alternate form of the GetWhitelist method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) GetWhitelistWithContext(ctx context.Context, getWhitelistOptions *GetWhitelistOptions) (result *Whitelist, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(getWhitelistOptions, "getWhitelistOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(getWhitelistOptions, "getWhitelistOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *getWhitelistOptions.ID, } builder := core.NewRequestBuilder(core.GET) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/whitelists/ip_addresses`, pathParamsMap) if err != nil { return } for headerName, headerValue := range getWhitelistOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "GetWhitelist") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalWhitelist) if err != nil { return } response.Result = result return } // ReplaceWhitelist : Replace the allowlist for a deployment // Replace the allowlist for a deployment. This action overwrites all existing entries, so when you modify the allowlist // via a GET/update/PUT, provide the GET response's ETag header value in this endpoint's If-Match header to ensure that // changes that are made by other clients are not accidentally overwritten. func (ibmCloudDatabases *IbmCloudDatabasesV5) ReplaceWhitelist(replaceWhitelistOptions *ReplaceWhitelistOptions) (result *ReplaceWhitelistResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.ReplaceWhitelistWithContext(context.Background(), replaceWhitelistOptions) } // ReplaceWhitelistWithContext is an alternate form of the ReplaceWhitelist method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) ReplaceWhitelistWithContext(ctx context.Context, replaceWhitelistOptions *ReplaceWhitelistOptions) (result *ReplaceWhitelistResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(replaceWhitelistOptions, "replaceWhitelistOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(replaceWhitelistOptions, "replaceWhitelistOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *replaceWhitelistOptions.ID, } builder := core.NewRequestBuilder(core.PUT) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/whitelists/ip_addresses`, pathParamsMap) if err != nil { return } for headerName, headerValue := range replaceWhitelistOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "ReplaceWhitelist") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") if replaceWhitelistOptions.IfMatch != nil { builder.AddHeader("If-Match", fmt.Sprint(*replaceWhitelistOptions.IfMatch)) } body := make(map[string]interface{}) if replaceWhitelistOptions.IpAddresses != nil { body["ip_addresses"] = replaceWhitelistOptions.IpAddresses } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalReplaceWhitelistResponse) if err != nil { return } response.Result = result return } // AddWhitelistEntry : Add an address or range to the allowlist for a deployment // Add an address or range to the allowlist for a deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) AddWhitelistEntry(addWhitelistEntryOptions *AddWhitelistEntryOptions) (result *AddWhitelistEntryResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.AddWhitelistEntryWithContext(context.Background(), addWhitelistEntryOptions) } // AddWhitelistEntryWithContext is an alternate form of the AddWhitelistEntry method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) AddWhitelistEntryWithContext(ctx context.Context, addWhitelistEntryOptions *AddWhitelistEntryOptions) (result *AddWhitelistEntryResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(addWhitelistEntryOptions, "addWhitelistEntryOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(addWhitelistEntryOptions, "addWhitelistEntryOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *addWhitelistEntryOptions.ID, } builder := core.NewRequestBuilder(core.POST) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/whitelists/ip_addresses`, pathParamsMap) if err != nil { return } for headerName, headerValue := range addWhitelistEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "AddWhitelistEntry") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") builder.AddHeader("Content-Type", "application/json") body := make(map[string]interface{}) if addWhitelistEntryOptions.IpAddress != nil { body["ip_address"] = addWhitelistEntryOptions.IpAddress } _, err = builder.SetBodyContentJSON(body) if err != nil { return } request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalAddWhitelistEntryResponse) if err != nil { return } response.Result = result return } // DeleteWhitelistEntry : Delete an address or range from the allowlist of a deployment // Delete an address or range from the allowlist of a deployment. func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteWhitelistEntry(deleteWhitelistEntryOptions *DeleteWhitelistEntryOptions) (result *DeleteWhitelistEntryResponse, response *core.DetailedResponse, err error) { return ibmCloudDatabases.DeleteWhitelistEntryWithContext(context.Background(), deleteWhitelistEntryOptions) } // DeleteWhitelistEntryWithContext is an alternate form of the DeleteWhitelistEntry method which supports a Context parameter func (ibmCloudDatabases *IbmCloudDatabasesV5) DeleteWhitelistEntryWithContext(ctx context.Context, deleteWhitelistEntryOptions *DeleteWhitelistEntryOptions) (result *DeleteWhitelistEntryResponse, response *core.DetailedResponse, err error) { err = core.ValidateNotNil(deleteWhitelistEntryOptions, "deleteWhitelistEntryOptions cannot be nil") if err != nil { return } err = core.ValidateStruct(deleteWhitelistEntryOptions, "deleteWhitelistEntryOptions") if err != nil { return } pathParamsMap := map[string]string{ "id": *deleteWhitelistEntryOptions.ID, "ipaddress": *deleteWhitelistEntryOptions.Ipaddress, } builder := core.NewRequestBuilder(core.DELETE) builder = builder.WithContext(ctx) builder.EnableGzipCompression = ibmCloudDatabases.GetEnableGzipCompression() _, err = builder.ResolveRequestURL(ibmCloudDatabases.Service.Options.URL, `/deployments/{id}/whitelists/ip_addresses/{ipaddress}`, pathParamsMap) if err != nil { return } for headerName, headerValue := range deleteWhitelistEntryOptions.Headers { builder.AddHeader(headerName, headerValue) } sdkHeaders := common.GetSdkHeaders("ibm_cloud_databases", "V5", "DeleteWhitelistEntry") for headerName, headerValue := range sdkHeaders { builder.AddHeader(headerName, headerValue) } builder.AddHeader("Accept", "application/json") request, err := builder.Build() if err != nil { return } var rawResponse map[string]json.RawMessage response, err = ibmCloudDatabases.Service.Request(request, &rawResponse) if err != nil { return } err = core.UnmarshalModel(rawResponse, "", &result, UnmarshalDeleteWhitelistEntryResponse) if err != nil { return } response.Result = result return } // APasswordSettingUser : APasswordSettingUser struct type APasswordSettingUser struct { Password *string `json:"password,omitempty"` } // UnmarshalAPasswordSettingUser unmarshals an instance of APasswordSettingUser from the specified map of raw messages. func UnmarshalAPasswordSettingUser(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(APasswordSettingUser) err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AddWhitelistEntryOptions : The AddWhitelistEntry options. type AddWhitelistEntryOptions struct { // Deployment ID. ID *string `validate:"required,ne="` IpAddress *WhitelistEntry // Allows users to set headers on API requests Headers map[string]string } // NewAddWhitelistEntryOptions : Instantiate AddWhitelistEntryOptions func (*IbmCloudDatabasesV5) NewAddWhitelistEntryOptions(id string) *AddWhitelistEntryOptions { return &AddWhitelistEntryOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *AddWhitelistEntryOptions) SetID(id string) *AddWhitelistEntryOptions { options.ID = core.StringPtr(id) return options } // SetIpAddress : Allow user to set IpAddress func (options *AddWhitelistEntryOptions) SetIpAddress(ipAddress *WhitelistEntry) *AddWhitelistEntryOptions { options.IpAddress = ipAddress return options } // SetHeaders : Allow user to set Headers func (options *AddWhitelistEntryOptions) SetHeaders(param map[string]string) *AddWhitelistEntryOptions { options.Headers = param return options } // AddWhitelistEntryResponse : AddWhitelistEntryResponse struct type AddWhitelistEntryResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalAddWhitelistEntryResponse unmarshals an instance of AddWhitelistEntryResponse from the specified map of raw messages. func UnmarshalAddWhitelistEntryResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AddWhitelistEntryResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingCPUGroupCPU : AutoscalingCPUGroupCPU struct type AutoscalingCPUGroupCPU struct { Scalers interface{} `json:"scalers,omitempty"` Rate *AutoscalingCPUGroupCPURate `json:"rate,omitempty"` } // UnmarshalAutoscalingCPUGroupCPU unmarshals an instance of AutoscalingCPUGroupCPU from the specified map of raw messages. func UnmarshalAutoscalingCPUGroupCPU(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingCPUGroupCPU) err = core.UnmarshalPrimitive(m, "scalers", &obj.Scalers) if err != nil { return } err = core.UnmarshalModel(m, "rate", &obj.Rate, UnmarshalAutoscalingCPUGroupCPURate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingCPUGroupCPURate : AutoscalingCPUGroupCPURate struct type AutoscalingCPUGroupCPURate struct { IncreasePercent *float64 `json:"increase_percent,omitempty"` PeriodSeconds *int64 `json:"period_seconds,omitempty"` LimitCountPerMember *int64 `json:"limit_count_per_member,omitempty"` Units *string `json:"units,omitempty"` } // UnmarshalAutoscalingCPUGroupCPURate unmarshals an instance of AutoscalingCPUGroupCPURate from the specified map of raw messages. func UnmarshalAutoscalingCPUGroupCPURate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingCPUGroupCPURate) err = core.UnmarshalPrimitive(m, "increase_percent", &obj.IncreasePercent) if err != nil { return } err = core.UnmarshalPrimitive(m, "period_seconds", &obj.PeriodSeconds) if err != nil { return } err = core.UnmarshalPrimitive(m, "limit_count_per_member", &obj.LimitCountPerMember) if err != nil { return } err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingDiskGroupDisk : AutoscalingDiskGroupDisk struct type AutoscalingDiskGroupDisk struct { Scalers *AutoscalingDiskGroupDiskScalers `json:"scalers,omitempty"` Rate *AutoscalingDiskGroupDiskRate `json:"rate,omitempty"` } // UnmarshalAutoscalingDiskGroupDisk unmarshals an instance of AutoscalingDiskGroupDisk from the specified map of raw messages. func UnmarshalAutoscalingDiskGroupDisk(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingDiskGroupDisk) err = core.UnmarshalModel(m, "scalers", &obj.Scalers, UnmarshalAutoscalingDiskGroupDiskScalers) if err != nil { return } err = core.UnmarshalModel(m, "rate", &obj.Rate, UnmarshalAutoscalingDiskGroupDiskRate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingDiskGroupDiskRate : AutoscalingDiskGroupDiskRate struct type AutoscalingDiskGroupDiskRate struct { IncreasePercent *float64 `json:"increase_percent,omitempty"` PeriodSeconds *int64 `json:"period_seconds,omitempty"` LimitMbPerMember *float64 `json:"limit_mb_per_member,omitempty"` Units *string `json:"units,omitempty"` } // UnmarshalAutoscalingDiskGroupDiskRate unmarshals an instance of AutoscalingDiskGroupDiskRate from the specified map of raw messages. func UnmarshalAutoscalingDiskGroupDiskRate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingDiskGroupDiskRate) err = core.UnmarshalPrimitive(m, "increase_percent", &obj.IncreasePercent) if err != nil { return } err = core.UnmarshalPrimitive(m, "period_seconds", &obj.PeriodSeconds) if err != nil { return } err = core.UnmarshalPrimitive(m, "limit_mb_per_member", &obj.LimitMbPerMember) if err != nil { return } err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingDiskGroupDiskScalers : AutoscalingDiskGroupDiskScalers struct type AutoscalingDiskGroupDiskScalers struct { Capacity *AutoscalingDiskGroupDiskScalersCapacity `json:"capacity,omitempty"` IoUtilization *AutoscalingDiskGroupDiskScalersIoUtilization `json:"io_utilization,omitempty"` } // UnmarshalAutoscalingDiskGroupDiskScalers unmarshals an instance of AutoscalingDiskGroupDiskScalers from the specified map of raw messages. func UnmarshalAutoscalingDiskGroupDiskScalers(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingDiskGroupDiskScalers) err = core.UnmarshalModel(m, "capacity", &obj.Capacity, UnmarshalAutoscalingDiskGroupDiskScalersCapacity) if err != nil { return } err = core.UnmarshalModel(m, "io_utilization", &obj.IoUtilization, UnmarshalAutoscalingDiskGroupDiskScalersIoUtilization) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingDiskGroupDiskScalersCapacity : AutoscalingDiskGroupDiskScalersCapacity struct type AutoscalingDiskGroupDiskScalersCapacity struct { Enabled *bool `json:"enabled,omitempty"` FreeSpaceLessThanPercent *int64 `json:"free_space_less_than_percent,omitempty"` } // UnmarshalAutoscalingDiskGroupDiskScalersCapacity unmarshals an instance of AutoscalingDiskGroupDiskScalersCapacity from the specified map of raw messages. func UnmarshalAutoscalingDiskGroupDiskScalersCapacity(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingDiskGroupDiskScalersCapacity) err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) if err != nil { return } err = core.UnmarshalPrimitive(m, "free_space_less_than_percent", &obj.FreeSpaceLessThanPercent) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingDiskGroupDiskScalersIoUtilization : AutoscalingDiskGroupDiskScalersIoUtilization struct type AutoscalingDiskGroupDiskScalersIoUtilization struct { Enabled *bool `json:"enabled,omitempty"` OverPeriod *string `json:"over_period,omitempty"` AbovePercent *int64 `json:"above_percent,omitempty"` } // UnmarshalAutoscalingDiskGroupDiskScalersIoUtilization unmarshals an instance of AutoscalingDiskGroupDiskScalersIoUtilization from the specified map of raw messages. func UnmarshalAutoscalingDiskGroupDiskScalersIoUtilization(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingDiskGroupDiskScalersIoUtilization) err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) if err != nil { return } err = core.UnmarshalPrimitive(m, "over_period", &obj.OverPeriod) if err != nil { return } err = core.UnmarshalPrimitive(m, "above_percent", &obj.AbovePercent) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingGroup : AutoscalingGroup struct type AutoscalingGroup struct { Disk *AutoscalingDiskGroupDisk `json:"disk,omitempty"` Memory *AutoscalingMemoryGroupMemory `json:"memory,omitempty"` Cpu *AutoscalingCPUGroupCPU `json:"cpu,omitempty"` } // UnmarshalAutoscalingGroup unmarshals an instance of AutoscalingGroup from the specified map of raw messages. func UnmarshalAutoscalingGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingGroup) err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalAutoscalingDiskGroupDisk) if err != nil { return } err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalAutoscalingMemoryGroupMemory) if err != nil { return } err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalAutoscalingCPUGroupCPU) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingMemoryGroupMemory : AutoscalingMemoryGroupMemory struct type AutoscalingMemoryGroupMemory struct { Scalers *AutoscalingMemoryGroupMemoryScalers `json:"scalers,omitempty"` Rate *AutoscalingMemoryGroupMemoryRate `json:"rate,omitempty"` } // UnmarshalAutoscalingMemoryGroupMemory unmarshals an instance of AutoscalingMemoryGroupMemory from the specified map of raw messages. func UnmarshalAutoscalingMemoryGroupMemory(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingMemoryGroupMemory) err = core.UnmarshalModel(m, "scalers", &obj.Scalers, UnmarshalAutoscalingMemoryGroupMemoryScalers) if err != nil { return } err = core.UnmarshalModel(m, "rate", &obj.Rate, UnmarshalAutoscalingMemoryGroupMemoryRate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingMemoryGroupMemoryRate : AutoscalingMemoryGroupMemoryRate struct type AutoscalingMemoryGroupMemoryRate struct { IncreasePercent *float64 `json:"increase_percent,omitempty"` PeriodSeconds *int64 `json:"period_seconds,omitempty"` LimitMbPerMember *float64 `json:"limit_mb_per_member,omitempty"` Units *string `json:"units,omitempty"` } // UnmarshalAutoscalingMemoryGroupMemoryRate unmarshals an instance of AutoscalingMemoryGroupMemoryRate from the specified map of raw messages. func UnmarshalAutoscalingMemoryGroupMemoryRate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingMemoryGroupMemoryRate) err = core.UnmarshalPrimitive(m, "increase_percent", &obj.IncreasePercent) if err != nil { return } err = core.UnmarshalPrimitive(m, "period_seconds", &obj.PeriodSeconds) if err != nil { return } err = core.UnmarshalPrimitive(m, "limit_mb_per_member", &obj.LimitMbPerMember) if err != nil { return } err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingMemoryGroupMemoryScalers : AutoscalingMemoryGroupMemoryScalers struct type AutoscalingMemoryGroupMemoryScalers struct { IoUtilization *AutoscalingMemoryGroupMemoryScalersIoUtilization `json:"io_utilization,omitempty"` } // UnmarshalAutoscalingMemoryGroupMemoryScalers unmarshals an instance of AutoscalingMemoryGroupMemoryScalers from the specified map of raw messages. func UnmarshalAutoscalingMemoryGroupMemoryScalers(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingMemoryGroupMemoryScalers) err = core.UnmarshalModel(m, "io_utilization", &obj.IoUtilization, UnmarshalAutoscalingMemoryGroupMemoryScalersIoUtilization) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingMemoryGroupMemoryScalersIoUtilization : AutoscalingMemoryGroupMemoryScalersIoUtilization struct type AutoscalingMemoryGroupMemoryScalersIoUtilization struct { Enabled *bool `json:"enabled,omitempty"` OverPeriod *string `json:"over_period,omitempty"` AbovePercent *int64 `json:"above_percent,omitempty"` } // UnmarshalAutoscalingMemoryGroupMemoryScalersIoUtilization unmarshals an instance of AutoscalingMemoryGroupMemoryScalersIoUtilization from the specified map of raw messages. func UnmarshalAutoscalingMemoryGroupMemoryScalersIoUtilization(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingMemoryGroupMemoryScalersIoUtilization) err = core.UnmarshalPrimitive(m, "enabled", &obj.Enabled) if err != nil { return } err = core.UnmarshalPrimitive(m, "over_period", &obj.OverPeriod) if err != nil { return } err = core.UnmarshalPrimitive(m, "above_percent", &obj.AbovePercent) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingSetGroup : AutoscalingSetGroup struct // Models which "extend" this model: // - AutoscalingSetGroupAutoscalingDiskGroup // - AutoscalingSetGroupAutoscalingMemoryGroup // - AutoscalingSetGroupAutoscalingCPUGroup type AutoscalingSetGroup struct { Disk *AutoscalingDiskGroupDisk `json:"disk,omitempty"` Memory *AutoscalingMemoryGroupMemory `json:"memory,omitempty"` Cpu *AutoscalingCPUGroupCPU `json:"cpu,omitempty"` } func (*AutoscalingSetGroup) isaAutoscalingSetGroup() bool { return true } type AutoscalingSetGroupIntf interface { isaAutoscalingSetGroup() bool } // UnmarshalAutoscalingSetGroup unmarshals an instance of AutoscalingSetGroup from the specified map of raw messages. func UnmarshalAutoscalingSetGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingSetGroup) err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalAutoscalingDiskGroupDisk) if err != nil { return } err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalAutoscalingMemoryGroupMemory) if err != nil { return } err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalAutoscalingCPUGroupCPU) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Backup : Backup struct type Backup struct { // ID of this backup. ID *string `json:"id,omitempty"` // ID of the deployment this backup relates to. DeploymentID *string `json:"deployment_id,omitempty"` // The type of backup. Type *string `json:"type,omitempty"` // The status of this backup. Status *string `json:"status,omitempty"` // Is this backup available to download?. IsDownloadable *bool `json:"is_downloadable,omitempty"` // Can this backup be used to restore an instance?. IsRestorable *bool `json:"is_restorable,omitempty"` // Date and time when this backup was created. CreatedAt *strfmt.DateTime `json:"created_at,omitempty"` } // Constants associated with the Backup.Type property. // The type of backup. const ( Backup_Type_OnDemand = "on_demand" Backup_Type_Scheduled = "scheduled" ) // Constants associated with the Backup.Status property. // The status of this backup. const ( Backup_Status_Completed = "completed" Backup_Status_Failed = "failed" Backup_Status_Running = "running" ) // UnmarshalBackup unmarshals an instance of Backup from the specified map of raw messages. func UnmarshalBackup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Backup) err = core.UnmarshalPrimitive(m, "id", &obj.ID) if err != nil { return } err = core.UnmarshalPrimitive(m, "deployment_id", &obj.DeploymentID) if err != nil { return } err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "status", &obj.Status) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_downloadable", &obj.IsDownloadable) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_restorable", &obj.IsRestorable) if err != nil { return } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Backups : Backups struct type Backups struct { Backups []Backup `json:"backups,omitempty"` } // UnmarshalBackups unmarshals an instance of Backups from the specified map of raw messages. func UnmarshalBackups(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Backups) err = core.UnmarshalModel(m, "backups", &obj.Backups, UnmarshalBackup) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ChangeUserPasswordOptions : The ChangeUserPassword options. type ChangeUserPasswordOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` // User ID. Username *string `validate:"required,ne="` User *APasswordSettingUser // Allows users to set headers on API requests Headers map[string]string } // NewChangeUserPasswordOptions : Instantiate ChangeUserPasswordOptions func (*IbmCloudDatabasesV5) NewChangeUserPasswordOptions(id string, userType string, username string) *ChangeUserPasswordOptions { return &ChangeUserPasswordOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), Username: core.StringPtr(username), } } // SetID : Allow user to set ID func (options *ChangeUserPasswordOptions) SetID(id string) *ChangeUserPasswordOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *ChangeUserPasswordOptions) SetUserType(userType string) *ChangeUserPasswordOptions { options.UserType = core.StringPtr(userType) return options } // SetUsername : Allow user to set Username func (options *ChangeUserPasswordOptions) SetUsername(username string) *ChangeUserPasswordOptions { options.Username = core.StringPtr(username) return options } // SetUser : Allow user to set User func (options *ChangeUserPasswordOptions) SetUser(user *APasswordSettingUser) *ChangeUserPasswordOptions { options.User = user return options } // SetHeaders : Allow user to set Headers func (options *ChangeUserPasswordOptions) SetHeaders(param map[string]string) *ChangeUserPasswordOptions { options.Headers = param return options } // ChangeUserPasswordResponse : ChangeUserPasswordResponse struct type ChangeUserPasswordResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalChangeUserPasswordResponse unmarshals an instance of ChangeUserPasswordResponse from the specified map of raw messages. func UnmarshalChangeUserPasswordResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ChangeUserPasswordResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ChoicePropertySchema : Choice Property Schema. type ChoicePropertySchema struct { // Whether the setting is customer-configurable. CustomerConfigurable *bool `json:"customer_configurable,omitempty"` // The default value of the setting. Default *int64 `json:"default,omitempty"` // The description of the default value. DefaultDescription *string `json:"default_description,omitempty"` // The description of the setting. Description *string `json:"description,omitempty"` // The type of this setting (e.g., string, integer). Kind *string `json:"kind,omitempty"` // Whether or not changing this setting will restart the database. RequiresRestart *bool `json:"requires_restart,omitempty"` // The valid choices for this setting. Choices []string `json:"choices,omitempty"` } // UnmarshalChoicePropertySchema unmarshals an instance of ChoicePropertySchema from the specified map of raw messages. func UnmarshalChoicePropertySchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ChoicePropertySchema) err = core.UnmarshalPrimitive(m, "customer_configurable", &obj.CustomerConfigurable) if err != nil { return } err = core.UnmarshalPrimitive(m, "default", &obj.Default) if err != nil { return } err = core.UnmarshalPrimitive(m, "default_description", &obj.DefaultDescription) if err != nil { return } err = core.UnmarshalPrimitive(m, "description", &obj.Description) if err != nil { return } err = core.UnmarshalPrimitive(m, "kind", &obj.Kind) if err != nil { return } err = core.UnmarshalPrimitive(m, "requires_restart", &obj.RequiresRestart) if err != nil { return } err = core.UnmarshalPrimitive(m, "choices", &obj.Choices) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // CompleteConnectionDeprecatedOptions : The CompleteConnectionDeprecated options. type CompleteConnectionDeprecatedOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` // User ID. UserID *string `validate:"required,ne="` // Password to be substituted into the response. Password *string // Optional certificate root path to prepend certificate names. Certificates would be stored in this directory for use // by other commands. CertificateRoot *string // Allows users to set headers on API requests Headers map[string]string } // NewCompleteConnectionDeprecatedOptions : Instantiate CompleteConnectionDeprecatedOptions func (*IbmCloudDatabasesV5) NewCompleteConnectionDeprecatedOptions(id string, userType string, userID string) *CompleteConnectionDeprecatedOptions { return &CompleteConnectionDeprecatedOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), UserID: core.StringPtr(userID), } } // SetID : Allow user to set ID func (options *CompleteConnectionDeprecatedOptions) SetID(id string) *CompleteConnectionDeprecatedOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *CompleteConnectionDeprecatedOptions) SetUserType(userType string) *CompleteConnectionDeprecatedOptions { options.UserType = core.StringPtr(userType) return options } // SetUserID : Allow user to set UserID func (options *CompleteConnectionDeprecatedOptions) SetUserID(userID string) *CompleteConnectionDeprecatedOptions { options.UserID = core.StringPtr(userID) return options } // SetPassword : Allow user to set Password func (options *CompleteConnectionDeprecatedOptions) SetPassword(password string) *CompleteConnectionDeprecatedOptions { options.Password = core.StringPtr(password) return options } // SetCertificateRoot : Allow user to set CertificateRoot func (options *CompleteConnectionDeprecatedOptions) SetCertificateRoot(certificateRoot string) *CompleteConnectionDeprecatedOptions { options.CertificateRoot = core.StringPtr(certificateRoot) return options } // SetHeaders : Allow user to set Headers func (options *CompleteConnectionDeprecatedOptions) SetHeaders(param map[string]string) *CompleteConnectionDeprecatedOptions { options.Headers = param return options } // CompleteConnectionOptions : The CompleteConnection options. type CompleteConnectionOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type of `database` is the only currently supported value. UserType *string `validate:"required,ne="` // User ID. UserID *string `validate:"required,ne="` // Endpoint Type. The select endpoint must be enabled on the deployment before its connection information can be // fetched. EndpointType *string `validate:"required,ne="` // Password to be substituted into the response. Password *string // Optional certificate root path to prepend certificate names. Certificates would be stored in this directory for use // by other commands. CertificateRoot *string // Allows users to set headers on API requests Headers map[string]string } // Constants associated with the CompleteConnectionOptions.EndpointType property. // Endpoint Type. The select endpoint must be enabled on the deployment before its connection information can be // fetched. const ( CompleteConnectionOptions_EndpointType_Private = "private" CompleteConnectionOptions_EndpointType_Public = "public" ) // NewCompleteConnectionOptions : Instantiate CompleteConnectionOptions func (*IbmCloudDatabasesV5) NewCompleteConnectionOptions(id string, userType string, userID string, endpointType string) *CompleteConnectionOptions { return &CompleteConnectionOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), UserID: core.StringPtr(userID), EndpointType: core.StringPtr(endpointType), } } // SetID : Allow user to set ID func (options *CompleteConnectionOptions) SetID(id string) *CompleteConnectionOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *CompleteConnectionOptions) SetUserType(userType string) *CompleteConnectionOptions { options.UserType = core.StringPtr(userType) return options } // SetUserID : Allow user to set UserID func (options *CompleteConnectionOptions) SetUserID(userID string) *CompleteConnectionOptions { options.UserID = core.StringPtr(userID) return options } // SetEndpointType : Allow user to set EndpointType func (options *CompleteConnectionOptions) SetEndpointType(endpointType string) *CompleteConnectionOptions { options.EndpointType = core.StringPtr(endpointType) return options } // SetPassword : Allow user to set Password func (options *CompleteConnectionOptions) SetPassword(password string) *CompleteConnectionOptions { options.Password = core.StringPtr(password) return options } // SetCertificateRoot : Allow user to set CertificateRoot func (options *CompleteConnectionOptions) SetCertificateRoot(certificateRoot string) *CompleteConnectionOptions { options.CertificateRoot = core.StringPtr(certificateRoot) return options } // SetHeaders : Allow user to set Headers func (options *CompleteConnectionOptions) SetHeaders(param map[string]string) *CompleteConnectionOptions { options.Headers = param return options } // ConfigurationSchema : Database Configuration Schema. type ConfigurationSchema struct { Schema ConfigurationSchemaSchemaIntf `json:"schema" validate:"required"` } // UnmarshalConfigurationSchema unmarshals an instance of ConfigurationSchema from the specified map of raw messages. func UnmarshalConfigurationSchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConfigurationSchema) err = core.UnmarshalModel(m, "schema", &obj.Schema, UnmarshalConfigurationSchemaSchema) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConfigurationSchemaSchema : ConfigurationSchemaSchema struct // Models which "extend" this model: // - ConfigurationSchemaSchemaPGConfigurationSchema // - ConfigurationSchemaSchemaRedisConfigurationSchema type ConfigurationSchemaSchema struct { // Integer Property Schema. MaxConnections *IntegerPropertySchema `json:"max_connections,omitempty"` // Integer Property Schema. MaxPreparedConnections *IntegerPropertySchema `json:"max_prepared_connections,omitempty"` // Integer Property Schema. BackupRetentionPeriod *IntegerPropertySchema `json:"backup_retention_period,omitempty"` // Integer Property Schema. DeadlockTimeout *IntegerPropertySchema `json:"deadlock_timeout,omitempty"` // Integer Property Schema. EffectiveIoConcurrency *IntegerPropertySchema `json:"effective_io_concurrency,omitempty"` // Integer Property Schema. MaxReplicationSlots *IntegerPropertySchema `json:"max_replication_slots,omitempty"` // Integer Property Schema. MaxWalSenders *IntegerPropertySchema `json:"max_wal_senders,omitempty"` // Integer Property Schema. SharedBuffers *IntegerPropertySchema `json:"shared_buffers,omitempty"` // Choice Property Schema. SynchronousCommit *ChoicePropertySchema `json:"synchronous_commit,omitempty"` // Choice Property Schema. WalLevel *ChoicePropertySchema `json:"wal_level,omitempty"` // Integer Property Schema. ArchiveTimeout *IntegerPropertySchema `json:"archive_timeout,omitempty"` // Integer Property Schema. LogMinDurationStatement *IntegerPropertySchema `json:"log_min_duration_statement,omitempty"` // Integer Property Schema. MaxmemoryRedis *IntegerPropertySchema `json:"maxmemory-redis,omitempty"` // Choice Property Schema. MaxmemoryPolicy *ChoicePropertySchema `json:"maxmemory-policy,omitempty"` // Choice Property Schema. Appendonly *ChoicePropertySchema `json:"appendonly,omitempty"` // Integer Property Schema. MaxmemorySamples *IntegerPropertySchema `json:"maxmemory-samples,omitempty"` // Choice Property Schema. StopWritesOnBgsaveError *ChoicePropertySchema `json:"stop-writes-on-bgsave-error,omitempty"` } func (*ConfigurationSchemaSchema) isaConfigurationSchemaSchema() bool { return true } type ConfigurationSchemaSchemaIntf interface { isaConfigurationSchemaSchema() bool } // UnmarshalConfigurationSchemaSchema unmarshals an instance of ConfigurationSchemaSchema from the specified map of raw messages. func UnmarshalConfigurationSchemaSchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConfigurationSchemaSchema) err = core.UnmarshalModel(m, "max_connections", &obj.MaxConnections, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_prepared_connections", &obj.MaxPreparedConnections, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "backup_retention_period", &obj.BackupRetentionPeriod, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "deadlock_timeout", &obj.DeadlockTimeout, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "effective_io_concurrency", &obj.EffectiveIoConcurrency, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_replication_slots", &obj.MaxReplicationSlots, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_wal_senders", &obj.MaxWalSenders, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "shared_buffers", &obj.SharedBuffers, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "synchronous_commit", &obj.SynchronousCommit, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "wal_level", &obj.WalLevel, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "archive_timeout", &obj.ArchiveTimeout, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "log_min_duration_statement", &obj.LogMinDurationStatement, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "maxmemory-redis", &obj.MaxmemoryRedis, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "maxmemory-policy", &obj.MaxmemoryPolicy, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "appendonly", &obj.Appendonly, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "maxmemory-samples", &obj.MaxmemorySamples, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "stop-writes-on-bgsave-error", &obj.StopWritesOnBgsaveError, UnmarshalChoicePropertySchema) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Connection : Connection struct type Connection struct { Connection ConnectionConnectionIntf `json:"connection" validate:"required"` } // UnmarshalConnection unmarshals an instance of Connection from the specified map of raw messages. func UnmarshalConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Connection) err = core.UnmarshalModel(m, "connection", &obj.Connection, UnmarshalConnectionConnection) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionCLI : CLI Connection. type ConnectionCLI struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // A map of environment variables for a CLI connection. Environment map[string]string `json:"environment,omitempty"` // The name of the executable the CLI should run. Bin *string `json:"bin,omitempty"` // Sets of arguments to call the executable with. The outer array corresponds to a possible way to call the CLI; the // inner array is the set of arguments to use with that call. Arguments [][]string `json:"arguments,omitempty"` Certificate *ConnectionCLICertificate `json:"certificate,omitempty"` } // UnmarshalConnectionCLI unmarshals an instance of ConnectionCLI from the specified map of raw messages. func UnmarshalConnectionCLI(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionCLI) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "environment", &obj.Environment) if err != nil { return } err = core.UnmarshalPrimitive(m, "bin", &obj.Bin) if err != nil { return } err = core.UnmarshalPrimitive(m, "arguments", &obj.Arguments) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalConnectionCLICertificate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionCLICertificate : ConnectionCLICertificate struct type ConnectionCLICertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalConnectionCLICertificate unmarshals an instance of ConnectionCLICertificate from the specified map of raw messages. func UnmarshalConnectionCLICertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionCLICertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnection : ConnectionConnection struct // Models which "extend" this model: // - ConnectionConnectionPostgreSQLConnection // - ConnectionConnectionRedisConnection // - ConnectionConnectionElasticsearchConnection // - ConnectionConnectionRabbitMQConnection // - ConnectionConnectionEtcdConnection // - ConnectionConnectionMongoDBConnection type ConnectionConnection struct { // Connection information for drivers and libraries. Postgres *PostgreSQLConnectionURI `json:"postgres,omitempty"` // Connection information for psql. Cli *ConnectionCLI `json:"cli,omitempty"` // Connection information for drivers and libraries. Rediss *RedisConnectionURI `json:"rediss,omitempty"` // Elasticsearch Connection information for drivers and libraries. Https *ElasticsearchConnectionHTTPS `json:"https,omitempty"` // RabbitMQ Connection information for AMQPS drivers and libraries. Amqps *RabbitMQConnectionAMQPS `json:"amqps,omitempty"` // RabbitMQ Connection information for MQTTS drivers and libraries. Mqtts *RabbitMQConnectionMQTTS `json:"mqtts,omitempty"` // RabbitMQ Connection information for STOMP drivers and libraries. StompSsl *RabbitMQConnectionStompSSL `json:"stomp_ssl,omitempty"` // GRPC(etcd3) Connection information for drivers and libraries. Grpc *GRPCConnectionURI `json:"grpc,omitempty"` // MongoDB Connection information for drivers and libraries. Mongodb *MongoDBConnectionURI `json:"mongodb,omitempty"` } func (*ConnectionConnection) isaConnectionConnection() bool { return true } type ConnectionConnectionIntf interface { isaConnectionConnection() bool } // UnmarshalConnectionConnection unmarshals an instance of ConnectionConnection from the specified map of raw messages. func UnmarshalConnectionConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnection) err = core.UnmarshalModel(m, "postgres", &obj.Postgres, UnmarshalPostgreSQLConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } err = core.UnmarshalModel(m, "rediss", &obj.Rediss, UnmarshalRedisConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "https", &obj.Https, UnmarshalElasticsearchConnectionHTTPS) if err != nil { return } err = core.UnmarshalModel(m, "amqps", &obj.Amqps, UnmarshalRabbitMQConnectionAMQPS) if err != nil { return } err = core.UnmarshalModel(m, "mqtts", &obj.Mqtts, UnmarshalRabbitMQConnectionMQTTS) if err != nil { return } err = core.UnmarshalModel(m, "stomp_ssl", &obj.StompSsl, UnmarshalRabbitMQConnectionStompSSL) if err != nil { return } err = core.UnmarshalModel(m, "grpc", &obj.Grpc, UnmarshalGRPCConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "mongodb", &obj.Mongodb, UnmarshalMongoDBConnectionURI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // CreateDatabaseUserOptions : The CreateDatabaseUser options. type CreateDatabaseUserOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` User *CreateDatabaseUserRequestUser // Allows users to set headers on API requests Headers map[string]string } // NewCreateDatabaseUserOptions : Instantiate CreateDatabaseUserOptions func (*IbmCloudDatabasesV5) NewCreateDatabaseUserOptions(id string, userType string) *CreateDatabaseUserOptions { return &CreateDatabaseUserOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), } } // SetID : Allow user to set ID func (options *CreateDatabaseUserOptions) SetID(id string) *CreateDatabaseUserOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *CreateDatabaseUserOptions) SetUserType(userType string) *CreateDatabaseUserOptions { options.UserType = core.StringPtr(userType) return options } // SetUser : Allow user to set User func (options *CreateDatabaseUserOptions) SetUser(user *CreateDatabaseUserRequestUser) *CreateDatabaseUserOptions { options.User = user return options } // SetHeaders : Allow user to set Headers func (options *CreateDatabaseUserOptions) SetHeaders(param map[string]string) *CreateDatabaseUserOptions { options.Headers = param return options } // CreateDatabaseUserRequestUser : CreateDatabaseUserRequestUser struct type CreateDatabaseUserRequestUser struct { // User type for new user. UserType *string `json:"user_type,omitempty"` // Username for new user. Username *string `json:"username,omitempty"` // Password for new user. Password *string `json:"password,omitempty"` } // UnmarshalCreateDatabaseUserRequestUser unmarshals an instance of CreateDatabaseUserRequestUser from the specified map of raw messages. func UnmarshalCreateDatabaseUserRequestUser(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(CreateDatabaseUserRequestUser) err = core.UnmarshalPrimitive(m, "user_type", &obj.UserType) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // CreateDatabaseUserResponse : CreateDatabaseUserResponse struct type CreateDatabaseUserResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalCreateDatabaseUserResponse unmarshals an instance of CreateDatabaseUserResponse from the specified map of raw messages. func UnmarshalCreateDatabaseUserResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(CreateDatabaseUserResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // CreateLogicalReplicationSlotOptions : The CreateLogicalReplicationSlot options. type CreateLogicalReplicationSlotOptions struct { // Deployment ID. ID *string `validate:"required,ne="` LogicalReplicationSlot *LogicalReplicationSlotLogicalReplicationSlot // Allows users to set headers on API requests Headers map[string]string } // NewCreateLogicalReplicationSlotOptions : Instantiate CreateLogicalReplicationSlotOptions func (*IbmCloudDatabasesV5) NewCreateLogicalReplicationSlotOptions(id string) *CreateLogicalReplicationSlotOptions { return &CreateLogicalReplicationSlotOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *CreateLogicalReplicationSlotOptions) SetID(id string) *CreateLogicalReplicationSlotOptions { options.ID = core.StringPtr(id) return options } // SetLogicalReplicationSlot : Allow user to set LogicalReplicationSlot func (options *CreateLogicalReplicationSlotOptions) SetLogicalReplicationSlot(logicalReplicationSlot *LogicalReplicationSlotLogicalReplicationSlot) *CreateLogicalReplicationSlotOptions { options.LogicalReplicationSlot = logicalReplicationSlot return options } // SetHeaders : Allow user to set Headers func (options *CreateLogicalReplicationSlotOptions) SetHeaders(param map[string]string) *CreateLogicalReplicationSlotOptions { options.Headers = param return options } // CreateLogicalReplicationSlotResponse : CreateLogicalReplicationSlotResponse struct type CreateLogicalReplicationSlotResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalCreateLogicalReplicationSlotResponse unmarshals an instance of CreateLogicalReplicationSlotResponse from the specified map of raw messages. func UnmarshalCreateLogicalReplicationSlotResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(CreateLogicalReplicationSlotResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // DeleteDatabaseUserOptions : The DeleteDatabaseUser options. type DeleteDatabaseUserOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` // Username. Username *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewDeleteDatabaseUserOptions : Instantiate DeleteDatabaseUserOptions func (*IbmCloudDatabasesV5) NewDeleteDatabaseUserOptions(id string, userType string, username string) *DeleteDatabaseUserOptions { return &DeleteDatabaseUserOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), Username: core.StringPtr(username), } } // SetID : Allow user to set ID func (options *DeleteDatabaseUserOptions) SetID(id string) *DeleteDatabaseUserOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *DeleteDatabaseUserOptions) SetUserType(userType string) *DeleteDatabaseUserOptions { options.UserType = core.StringPtr(userType) return options } // SetUsername : Allow user to set Username func (options *DeleteDatabaseUserOptions) SetUsername(username string) *DeleteDatabaseUserOptions { options.Username = core.StringPtr(username) return options } // SetHeaders : Allow user to set Headers func (options *DeleteDatabaseUserOptions) SetHeaders(param map[string]string) *DeleteDatabaseUserOptions { options.Headers = param return options } // DeleteDatabaseUserResponse : DeleteDatabaseUserResponse struct type DeleteDatabaseUserResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalDeleteDatabaseUserResponse unmarshals an instance of DeleteDatabaseUserResponse from the specified map of raw messages. func UnmarshalDeleteDatabaseUserResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(DeleteDatabaseUserResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // DeleteLogicalReplicationSlotOptions : The DeleteLogicalReplicationSlot options. type DeleteLogicalReplicationSlotOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Name of the logical replication slot. Name *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewDeleteLogicalReplicationSlotOptions : Instantiate DeleteLogicalReplicationSlotOptions func (*IbmCloudDatabasesV5) NewDeleteLogicalReplicationSlotOptions(id string, name string) *DeleteLogicalReplicationSlotOptions { return &DeleteLogicalReplicationSlotOptions{ ID: core.StringPtr(id), Name: core.StringPtr(name), } } // SetID : Allow user to set ID func (options *DeleteLogicalReplicationSlotOptions) SetID(id string) *DeleteLogicalReplicationSlotOptions { options.ID = core.StringPtr(id) return options } // SetName : Allow user to set Name func (options *DeleteLogicalReplicationSlotOptions) SetName(name string) *DeleteLogicalReplicationSlotOptions { options.Name = core.StringPtr(name) return options } // SetHeaders : Allow user to set Headers func (options *DeleteLogicalReplicationSlotOptions) SetHeaders(param map[string]string) *DeleteLogicalReplicationSlotOptions { options.Headers = param return options } // DeleteLogicalReplicationSlotResponse : DeleteLogicalReplicationSlotResponse struct type DeleteLogicalReplicationSlotResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalDeleteLogicalReplicationSlotResponse unmarshals an instance of DeleteLogicalReplicationSlotResponse from the specified map of raw messages. func UnmarshalDeleteLogicalReplicationSlotResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(DeleteLogicalReplicationSlotResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // DeleteWhitelistEntryOptions : The DeleteWhitelistEntry options. type DeleteWhitelistEntryOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // An IPv4 address or a CIDR range (netmasked IPv4 address). Ipaddress *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewDeleteWhitelistEntryOptions : Instantiate DeleteWhitelistEntryOptions func (*IbmCloudDatabasesV5) NewDeleteWhitelistEntryOptions(id string, ipaddress string) *DeleteWhitelistEntryOptions { return &DeleteWhitelistEntryOptions{ ID: core.StringPtr(id), Ipaddress: core.StringPtr(ipaddress), } } // SetID : Allow user to set ID func (options *DeleteWhitelistEntryOptions) SetID(id string) *DeleteWhitelistEntryOptions { options.ID = core.StringPtr(id) return options } // SetIpaddress : Allow user to set Ipaddress func (options *DeleteWhitelistEntryOptions) SetIpaddress(ipaddress string) *DeleteWhitelistEntryOptions { options.Ipaddress = core.StringPtr(ipaddress) return options } // SetHeaders : Allow user to set Headers func (options *DeleteWhitelistEntryOptions) SetHeaders(param map[string]string) *DeleteWhitelistEntryOptions { options.Headers = param return options } // DeleteWhitelistEntryResponse : DeleteWhitelistEntryResponse struct type DeleteWhitelistEntryResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalDeleteWhitelistEntryResponse unmarshals an instance of DeleteWhitelistEntryResponse from the specified map of raw messages. func UnmarshalDeleteWhitelistEntryResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(DeleteWhitelistEntryResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Deployables : Deployable databases with their version information. type Deployables struct { // Deployment type - typically the name of the database. Type *string `json:"type,omitempty"` // An array of versions of the database, their status, preferedness, and transitions. Versions []DeployablesVersionsItem `json:"versions,omitempty"` } // UnmarshalDeployables unmarshals an instance of Deployables from the specified map of raw messages. func UnmarshalDeployables(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Deployables) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalModel(m, "versions", &obj.Versions, UnmarshalDeployablesVersionsItem) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // DeployablesVersionsItem : DeployablesVersionsItem struct type DeployablesVersionsItem struct { // The version number. Version *string `json:"version,omitempty"` // The status of this version: To be finalized. Status *string `json:"status,omitempty"` // Should this version be preferred over others?. IsPreferred *bool `json:"is_preferred,omitempty"` // versions that this version can be upgraded to. Transitions []DeployablesVersionsItemTransitionsItem `json:"transitions,omitempty"` } // Constants associated with the DeployablesVersionsItem.Status property. // The status of this version: To be finalized. const ( DeployablesVersionsItem_Status_Beta = "beta" DeployablesVersionsItem_Status_Deprecated = "deprecated" DeployablesVersionsItem_Status_Stable = "stable" ) // UnmarshalDeployablesVersionsItem unmarshals an instance of DeployablesVersionsItem from the specified map of raw messages. func UnmarshalDeployablesVersionsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(DeployablesVersionsItem) err = core.UnmarshalPrimitive(m, "version", &obj.Version) if err != nil { return } err = core.UnmarshalPrimitive(m, "status", &obj.Status) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_preferred", &obj.IsPreferred) if err != nil { return } err = core.UnmarshalModel(m, "transitions", &obj.Transitions, UnmarshalDeployablesVersionsItemTransitionsItem) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // DeployablesVersionsItemTransitionsItem : DeployablesVersionsItemTransitionsItem struct type DeployablesVersionsItemTransitionsItem struct { // The database type. Application *string `json:"application,omitempty"` // method of going from from_version to to_version. Method *string `json:"method,omitempty"` // The version the transition in from. FromVersion *string `json:"from_version,omitempty"` // The version the transition is to. ToVersion *string `json:"to_version,omitempty"` } // UnmarshalDeployablesVersionsItemTransitionsItem unmarshals an instance of DeployablesVersionsItemTransitionsItem from the specified map of raw messages. func UnmarshalDeployablesVersionsItemTransitionsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(DeployablesVersionsItemTransitionsItem) err = core.UnmarshalPrimitive(m, "application", &obj.Application) if err != nil { return } err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "from_version", &obj.FromVersion) if err != nil { return } err = core.UnmarshalPrimitive(m, "to_version", &obj.ToVersion) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Deployment : Deployment struct type Deployment struct { // ID of this deployment. ID *string `json:"id,omitempty"` // Readable name of this deployment. Name *string `json:"name,omitempty"` // Database type within this deployment. Type *string `json:"type,omitempty"` // Platform-specific options for this deployment. PlatformOptions interface{} `json:"platform_options,omitempty"` // Version number of the database. Version *string `json:"version,omitempty"` // Login name of administration level user. AdminUsernames *string `json:"admin_usernames,omitempty"` // Whether access to this deployment is enabled from the public internet. This property can be modified by updating // this service instance through the Resource Controller API. EnablePublicEndpoints *bool `json:"enable_public_endpoints,omitempty"` // Whether access to this deployment is enabled from IBM Cloud via the IBM Cloud backbone network. This property can be // modified by updating this service instance through the Resource Controller API. EnablePrivateEndpoints *bool `json:"enable_private_endpoints,omitempty"` } // UnmarshalDeployment unmarshals an instance of Deployment from the specified map of raw messages. func UnmarshalDeployment(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Deployment) err = core.UnmarshalPrimitive(m, "id", &obj.ID) if err != nil { return } err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "platform_options", &obj.PlatformOptions) if err != nil { return } err = core.UnmarshalPrimitive(m, "version", &obj.Version) if err != nil { return } err = core.UnmarshalPrimitive(m, "admin_usernames", &obj.AdminUsernames) if err != nil { return } err = core.UnmarshalPrimitive(m, "enable_public_endpoints", &obj.EnablePublicEndpoints) if err != nil { return } err = core.UnmarshalPrimitive(m, "enable_private_endpoints", &obj.EnablePrivateEndpoints) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ElasticsearchConnectionHTTPS : ElasticsearchConnectionHTTPS struct type ElasticsearchConnectionHTTPS struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []ElasticsearchConnectionHTTPSHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *ElasticsearchConnectionHTTPSAuthentication `json:"authentication,omitempty"` Certificate *ElasticsearchConnectionHTTPSCertificate `json:"certificate,omitempty"` } // UnmarshalElasticsearchConnectionHTTPS unmarshals an instance of ElasticsearchConnectionHTTPS from the specified map of raw messages. func UnmarshalElasticsearchConnectionHTTPS(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ElasticsearchConnectionHTTPS) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalElasticsearchConnectionHTTPSHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalElasticsearchConnectionHTTPSAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalElasticsearchConnectionHTTPSCertificate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ElasticsearchConnectionHTTPSAuthentication : ElasticsearchConnectionHTTPSAuthentication struct type ElasticsearchConnectionHTTPSAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalElasticsearchConnectionHTTPSAuthentication unmarshals an instance of ElasticsearchConnectionHTTPSAuthentication from the specified map of raw messages. func UnmarshalElasticsearchConnectionHTTPSAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ElasticsearchConnectionHTTPSAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ElasticsearchConnectionHTTPSCertificate : ElasticsearchConnectionHTTPSCertificate struct type ElasticsearchConnectionHTTPSCertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalElasticsearchConnectionHTTPSCertificate unmarshals an instance of ElasticsearchConnectionHTTPSCertificate from the specified map of raw messages. func UnmarshalElasticsearchConnectionHTTPSCertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ElasticsearchConnectionHTTPSCertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ElasticsearchConnectionHTTPSHostsItem : ElasticsearchConnectionHTTPSHostsItem struct type ElasticsearchConnectionHTTPSHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalElasticsearchConnectionHTTPSHostsItem unmarshals an instance of ElasticsearchConnectionHTTPSHostsItem from the specified map of raw messages. func UnmarshalElasticsearchConnectionHTTPSHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ElasticsearchConnectionHTTPSHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // FileSyncOptions : The FileSync options. type FileSyncOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewFileSyncOptions : Instantiate FileSyncOptions func (*IbmCloudDatabasesV5) NewFileSyncOptions(id string) *FileSyncOptions { return &FileSyncOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *FileSyncOptions) SetID(id string) *FileSyncOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *FileSyncOptions) SetHeaders(param map[string]string) *FileSyncOptions { options.Headers = param return options } // FileSyncResponse : FileSyncResponse struct type FileSyncResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalFileSyncResponse unmarshals an instance of FileSyncResponse from the specified map of raw messages. func UnmarshalFileSyncResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(FileSyncResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GRPCConnectionURI : GRPCConnectionURI struct type GRPCConnectionURI struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []GRPCConnectionURIHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *GRPCConnectionURIAuthentication `json:"authentication,omitempty"` Certificate *GRPCConnectionURICertificate `json:"certificate,omitempty"` } // UnmarshalGRPCConnectionURI unmarshals an instance of GRPCConnectionURI from the specified map of raw messages. func UnmarshalGRPCConnectionURI(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GRPCConnectionURI) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalGRPCConnectionURIHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalGRPCConnectionURIAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalGRPCConnectionURICertificate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GRPCConnectionURIAuthentication : GRPCConnectionURIAuthentication struct type GRPCConnectionURIAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalGRPCConnectionURIAuthentication unmarshals an instance of GRPCConnectionURIAuthentication from the specified map of raw messages. func UnmarshalGRPCConnectionURIAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GRPCConnectionURIAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GRPCConnectionURICertificate : GRPCConnectionURICertificate struct type GRPCConnectionURICertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalGRPCConnectionURICertificate unmarshals an instance of GRPCConnectionURICertificate from the specified map of raw messages. func UnmarshalGRPCConnectionURICertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GRPCConnectionURICertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GRPCConnectionURIHostsItem : GRPCConnectionURIHostsItem struct type GRPCConnectionURIHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalGRPCConnectionURIHostsItem unmarshals an instance of GRPCConnectionURIHostsItem from the specified map of raw messages. func UnmarshalGRPCConnectionURIHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GRPCConnectionURIHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetAutoscalingConditionsOptions : The GetAutoscalingConditions options. type GetAutoscalingConditionsOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Group ID. GroupID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetAutoscalingConditionsOptions : Instantiate GetAutoscalingConditionsOptions func (*IbmCloudDatabasesV5) NewGetAutoscalingConditionsOptions(id string, groupID string) *GetAutoscalingConditionsOptions { return &GetAutoscalingConditionsOptions{ ID: core.StringPtr(id), GroupID: core.StringPtr(groupID), } } // SetID : Allow user to set ID func (options *GetAutoscalingConditionsOptions) SetID(id string) *GetAutoscalingConditionsOptions { options.ID = core.StringPtr(id) return options } // SetGroupID : Allow user to set GroupID func (options *GetAutoscalingConditionsOptions) SetGroupID(groupID string) *GetAutoscalingConditionsOptions { options.GroupID = core.StringPtr(groupID) return options } // SetHeaders : Allow user to set Headers func (options *GetAutoscalingConditionsOptions) SetHeaders(param map[string]string) *GetAutoscalingConditionsOptions { options.Headers = param return options } // GetAutoscalingConditionsResponse : GetAutoscalingConditionsResponse struct type GetAutoscalingConditionsResponse struct { Autoscaling *AutoscalingGroup `json:"autoscaling,omitempty"` } // UnmarshalGetAutoscalingConditionsResponse unmarshals an instance of GetAutoscalingConditionsResponse from the specified map of raw messages. func UnmarshalGetAutoscalingConditionsResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetAutoscalingConditionsResponse) err = core.UnmarshalModel(m, "autoscaling", &obj.Autoscaling, UnmarshalAutoscalingGroup) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetBackupInfoOptions : The GetBackupInfo options. type GetBackupInfoOptions struct { // Backup ID. BackupID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetBackupInfoOptions : Instantiate GetBackupInfoOptions func (*IbmCloudDatabasesV5) NewGetBackupInfoOptions(backupID string) *GetBackupInfoOptions { return &GetBackupInfoOptions{ BackupID: core.StringPtr(backupID), } } // SetBackupID : Allow user to set BackupID func (options *GetBackupInfoOptions) SetBackupID(backupID string) *GetBackupInfoOptions { options.BackupID = core.StringPtr(backupID) return options } // SetHeaders : Allow user to set Headers func (options *GetBackupInfoOptions) SetHeaders(param map[string]string) *GetBackupInfoOptions { options.Headers = param return options } // GetBackupInfoResponse : GetBackupInfoResponse struct type GetBackupInfoResponse struct { Backup *Backup `json:"backup,omitempty"` } // UnmarshalGetBackupInfoResponse unmarshals an instance of GetBackupInfoResponse from the specified map of raw messages. func UnmarshalGetBackupInfoResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetBackupInfoResponse) err = core.UnmarshalModel(m, "backup", &obj.Backup, UnmarshalBackup) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetConnectionDeprecatedOptions : The GetConnectionDeprecated options. type GetConnectionDeprecatedOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` // User ID. UserID *string `validate:"required,ne="` // Optional certificate root path to prepend certificate names. Certificates would be stored in this directory for use // by other commands. CertificateRoot *string // Allows users to set headers on API requests Headers map[string]string } // NewGetConnectionDeprecatedOptions : Instantiate GetConnectionDeprecatedOptions func (*IbmCloudDatabasesV5) NewGetConnectionDeprecatedOptions(id string, userType string, userID string) *GetConnectionDeprecatedOptions { return &GetConnectionDeprecatedOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), UserID: core.StringPtr(userID), } } // SetID : Allow user to set ID func (options *GetConnectionDeprecatedOptions) SetID(id string) *GetConnectionDeprecatedOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *GetConnectionDeprecatedOptions) SetUserType(userType string) *GetConnectionDeprecatedOptions { options.UserType = core.StringPtr(userType) return options } // SetUserID : Allow user to set UserID func (options *GetConnectionDeprecatedOptions) SetUserID(userID string) *GetConnectionDeprecatedOptions { options.UserID = core.StringPtr(userID) return options } // SetCertificateRoot : Allow user to set CertificateRoot func (options *GetConnectionDeprecatedOptions) SetCertificateRoot(certificateRoot string) *GetConnectionDeprecatedOptions { options.CertificateRoot = core.StringPtr(certificateRoot) return options } // SetHeaders : Allow user to set Headers func (options *GetConnectionDeprecatedOptions) SetHeaders(param map[string]string) *GetConnectionDeprecatedOptions { options.Headers = param return options } // GetConnectionOptions : The GetConnection options. type GetConnectionOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User type. UserType *string `validate:"required,ne="` // User ID. UserID *string `validate:"required,ne="` // Endpoint Type. The endpoint must be enabled on the deployment before its connection information can be fetched. EndpointType *string `validate:"required,ne="` // Optional certificate root path to prepend certificate names. Certificates would be stored in this directory for use // by other commands. CertificateRoot *string // Allows users to set headers on API requests Headers map[string]string } // Constants associated with the GetConnectionOptions.EndpointType property. // Endpoint Type. The endpoint must be enabled on the deployment before its connection information can be fetched. const ( GetConnectionOptions_EndpointType_Private = "private" GetConnectionOptions_EndpointType_Public = "public" ) // NewGetConnectionOptions : Instantiate GetConnectionOptions func (*IbmCloudDatabasesV5) NewGetConnectionOptions(id string, userType string, userID string, endpointType string) *GetConnectionOptions { return &GetConnectionOptions{ ID: core.StringPtr(id), UserType: core.StringPtr(userType), UserID: core.StringPtr(userID), EndpointType: core.StringPtr(endpointType), } } // SetID : Allow user to set ID func (options *GetConnectionOptions) SetID(id string) *GetConnectionOptions { options.ID = core.StringPtr(id) return options } // SetUserType : Allow user to set UserType func (options *GetConnectionOptions) SetUserType(userType string) *GetConnectionOptions { options.UserType = core.StringPtr(userType) return options } // SetUserID : Allow user to set UserID func (options *GetConnectionOptions) SetUserID(userID string) *GetConnectionOptions { options.UserID = core.StringPtr(userID) return options } // SetEndpointType : Allow user to set EndpointType func (options *GetConnectionOptions) SetEndpointType(endpointType string) *GetConnectionOptions { options.EndpointType = core.StringPtr(endpointType) return options } // SetCertificateRoot : Allow user to set CertificateRoot func (options *GetConnectionOptions) SetCertificateRoot(certificateRoot string) *GetConnectionOptions { options.CertificateRoot = core.StringPtr(certificateRoot) return options } // SetHeaders : Allow user to set Headers func (options *GetConnectionOptions) SetHeaders(param map[string]string) *GetConnectionOptions { options.Headers = param return options } // GetDatabaseConfigurationSchemaOptions : The GetDatabaseConfigurationSchema options. type GetDatabaseConfigurationSchemaOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetDatabaseConfigurationSchemaOptions : Instantiate GetDatabaseConfigurationSchemaOptions func (*IbmCloudDatabasesV5) NewGetDatabaseConfigurationSchemaOptions(id string) *GetDatabaseConfigurationSchemaOptions { return &GetDatabaseConfigurationSchemaOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetDatabaseConfigurationSchemaOptions) SetID(id string) *GetDatabaseConfigurationSchemaOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetDatabaseConfigurationSchemaOptions) SetHeaders(param map[string]string) *GetDatabaseConfigurationSchemaOptions { options.Headers = param return options } // GetDatabaseConfigurationSchemaResponse : GetDatabaseConfigurationSchemaResponse struct type GetDatabaseConfigurationSchemaResponse struct { // Database Configuration Schema. Schema *ConfigurationSchema `json:"schema,omitempty"` } // UnmarshalGetDatabaseConfigurationSchemaResponse unmarshals an instance of GetDatabaseConfigurationSchemaResponse from the specified map of raw messages. func UnmarshalGetDatabaseConfigurationSchemaResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetDatabaseConfigurationSchemaResponse) err = core.UnmarshalModel(m, "schema", &obj.Schema, UnmarshalConfigurationSchema) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetDefaultScalingGroupsOptions : The GetDefaultScalingGroups options. type GetDefaultScalingGroupsOptions struct { // Database type name. Type *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // Constants associated with the GetDefaultScalingGroupsOptions.Type property. // Database type name. const ( GetDefaultScalingGroupsOptions_Type_Etcd = "etcd" GetDefaultScalingGroupsOptions_Type_Postgresql = "postgresql" ) // NewGetDefaultScalingGroupsOptions : Instantiate GetDefaultScalingGroupsOptions func (*IbmCloudDatabasesV5) NewGetDefaultScalingGroupsOptions(typeVar string) *GetDefaultScalingGroupsOptions { return &GetDefaultScalingGroupsOptions{ Type: core.StringPtr(typeVar), } } // SetType : Allow user to set Type func (options *GetDefaultScalingGroupsOptions) SetType(typeVar string) *GetDefaultScalingGroupsOptions { options.Type = core.StringPtr(typeVar) return options } // SetHeaders : Allow user to set Headers func (options *GetDefaultScalingGroupsOptions) SetHeaders(param map[string]string) *GetDefaultScalingGroupsOptions { options.Headers = param return options } // GetDeployablesOptions : The GetDeployables options. type GetDeployablesOptions struct { // Allows users to set headers on API requests Headers map[string]string } // NewGetDeployablesOptions : Instantiate GetDeployablesOptions func (*IbmCloudDatabasesV5) NewGetDeployablesOptions() *GetDeployablesOptions { return &GetDeployablesOptions{} } // SetHeaders : Allow user to set Headers func (options *GetDeployablesOptions) SetHeaders(param map[string]string) *GetDeployablesOptions { options.Headers = param return options } // GetDeployablesResponse : GetDeployablesResponse struct type GetDeployablesResponse struct { Deployables []Deployables `json:"deployables,omitempty"` } // UnmarshalGetDeployablesResponse unmarshals an instance of GetDeployablesResponse from the specified map of raw messages. func UnmarshalGetDeployablesResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetDeployablesResponse) err = core.UnmarshalModel(m, "deployables", &obj.Deployables, UnmarshalDeployables) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetDeploymentBackupsOptions : The GetDeploymentBackups options. type GetDeploymentBackupsOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetDeploymentBackupsOptions : Instantiate GetDeploymentBackupsOptions func (*IbmCloudDatabasesV5) NewGetDeploymentBackupsOptions(id string) *GetDeploymentBackupsOptions { return &GetDeploymentBackupsOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetDeploymentBackupsOptions) SetID(id string) *GetDeploymentBackupsOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetDeploymentBackupsOptions) SetHeaders(param map[string]string) *GetDeploymentBackupsOptions { options.Headers = param return options } // GetDeploymentInfoOptions : The GetDeploymentInfo options. type GetDeploymentInfoOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetDeploymentInfoOptions : Instantiate GetDeploymentInfoOptions func (*IbmCloudDatabasesV5) NewGetDeploymentInfoOptions(id string) *GetDeploymentInfoOptions { return &GetDeploymentInfoOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetDeploymentInfoOptions) SetID(id string) *GetDeploymentInfoOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetDeploymentInfoOptions) SetHeaders(param map[string]string) *GetDeploymentInfoOptions { options.Headers = param return options } // GetDeploymentInfoResponse : GetDeploymentInfoResponse struct type GetDeploymentInfoResponse struct { Deployment *Deployment `json:"deployment,omitempty"` } // UnmarshalGetDeploymentInfoResponse unmarshals an instance of GetDeploymentInfoResponse from the specified map of raw messages. func UnmarshalGetDeploymentInfoResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetDeploymentInfoResponse) err = core.UnmarshalModel(m, "deployment", &obj.Deployment, UnmarshalDeployment) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetDeploymentScalingGroupsOptions : The GetDeploymentScalingGroups options. type GetDeploymentScalingGroupsOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetDeploymentScalingGroupsOptions : Instantiate GetDeploymentScalingGroupsOptions func (*IbmCloudDatabasesV5) NewGetDeploymentScalingGroupsOptions(id string) *GetDeploymentScalingGroupsOptions { return &GetDeploymentScalingGroupsOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetDeploymentScalingGroupsOptions) SetID(id string) *GetDeploymentScalingGroupsOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetDeploymentScalingGroupsOptions) SetHeaders(param map[string]string) *GetDeploymentScalingGroupsOptions { options.Headers = param return options } // GetDeploymentTasksOptions : The GetDeploymentTasks options. type GetDeploymentTasksOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetDeploymentTasksOptions : Instantiate GetDeploymentTasksOptions func (*IbmCloudDatabasesV5) NewGetDeploymentTasksOptions(id string) *GetDeploymentTasksOptions { return &GetDeploymentTasksOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetDeploymentTasksOptions) SetID(id string) *GetDeploymentTasksOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetDeploymentTasksOptions) SetHeaders(param map[string]string) *GetDeploymentTasksOptions { options.Headers = param return options } // GetPITRdataOptions : The GetPITRdata options. type GetPITRdataOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetPITRdataOptions : Instantiate GetPITRdataOptions func (*IbmCloudDatabasesV5) NewGetPITRdataOptions(id string) *GetPITRdataOptions { return &GetPITRdataOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetPITRdataOptions) SetID(id string) *GetPITRdataOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetPITRdataOptions) SetHeaders(param map[string]string) *GetPITRdataOptions { options.Headers = param return options } // GetRegionsOptions : The GetRegions options. type GetRegionsOptions struct { // Allows users to set headers on API requests Headers map[string]string } // NewGetRegionsOptions : Instantiate GetRegionsOptions func (*IbmCloudDatabasesV5) NewGetRegionsOptions() *GetRegionsOptions { return &GetRegionsOptions{} } // SetHeaders : Allow user to set Headers func (options *GetRegionsOptions) SetHeaders(param map[string]string) *GetRegionsOptions { options.Headers = param return options } // GetRegionsResponse : GetRegionsResponse struct type GetRegionsResponse struct { // An array of region ids. Regions []string `json:"regions,omitempty"` } // UnmarshalGetRegionsResponse unmarshals an instance of GetRegionsResponse from the specified map of raw messages. func UnmarshalGetRegionsResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetRegionsResponse) err = core.UnmarshalPrimitive(m, "regions", &obj.Regions) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetRemotesOptions : The GetRemotes options. type GetRemotesOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetRemotesOptions : Instantiate GetRemotesOptions func (*IbmCloudDatabasesV5) NewGetRemotesOptions(id string) *GetRemotesOptions { return &GetRemotesOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetRemotesOptions) SetID(id string) *GetRemotesOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetRemotesOptions) SetHeaders(param map[string]string) *GetRemotesOptions { options.Headers = param return options } // GetRemotesResponse : GetRemotesResponse struct type GetRemotesResponse struct { // Remotes. Remotes *Remotes `json:"remotes,omitempty"` } // UnmarshalGetRemotesResponse unmarshals an instance of GetRemotesResponse from the specified map of raw messages. func UnmarshalGetRemotesResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetRemotesResponse) err = core.UnmarshalModel(m, "remotes", &obj.Remotes, UnmarshalRemotes) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetRemotesSchemaOptions : The GetRemotesSchema options. type GetRemotesSchemaOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetRemotesSchemaOptions : Instantiate GetRemotesSchemaOptions func (*IbmCloudDatabasesV5) NewGetRemotesSchemaOptions(id string) *GetRemotesSchemaOptions { return &GetRemotesSchemaOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetRemotesSchemaOptions) SetID(id string) *GetRemotesSchemaOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetRemotesSchemaOptions) SetHeaders(param map[string]string) *GetRemotesSchemaOptions { options.Headers = param return options } // GetRemotesSchemaResponse : GetRemotesSchemaResponse struct type GetRemotesSchemaResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalGetRemotesSchemaResponse unmarshals an instance of GetRemotesSchemaResponse from the specified map of raw messages. func UnmarshalGetRemotesSchemaResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetRemotesSchemaResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetTasksOptions : The GetTasks options. type GetTasksOptions struct { // Task ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetTasksOptions : Instantiate GetTasksOptions func (*IbmCloudDatabasesV5) NewGetTasksOptions(id string) *GetTasksOptions { return &GetTasksOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetTasksOptions) SetID(id string) *GetTasksOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetTasksOptions) SetHeaders(param map[string]string) *GetTasksOptions { options.Headers = param return options } // GetTasksResponse : GetTasksResponse struct type GetTasksResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalGetTasksResponse unmarshals an instance of GetTasksResponse from the specified map of raw messages. func UnmarshalGetTasksResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GetTasksResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GetUserOptions : The GetUser options. type GetUserOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // User ID. UserID *string `validate:"required,ne="` // Endpoint Type. The endpoint must be enabled on the deployment before its connection information can be fetched. EndpointType *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // Constants associated with the GetUserOptions.EndpointType property. // Endpoint Type. The endpoint must be enabled on the deployment before its connection information can be fetched. const ( GetUserOptions_EndpointType_Private = "private" GetUserOptions_EndpointType_Public = "public" ) // NewGetUserOptions : Instantiate GetUserOptions func (*IbmCloudDatabasesV5) NewGetUserOptions(id string, userID string, endpointType string) *GetUserOptions { return &GetUserOptions{ ID: core.StringPtr(id), UserID: core.StringPtr(userID), EndpointType: core.StringPtr(endpointType), } } // SetID : Allow user to set ID func (options *GetUserOptions) SetID(id string) *GetUserOptions { options.ID = core.StringPtr(id) return options } // SetUserID : Allow user to set UserID func (options *GetUserOptions) SetUserID(userID string) *GetUserOptions { options.UserID = core.StringPtr(userID) return options } // SetEndpointType : Allow user to set EndpointType func (options *GetUserOptions) SetEndpointType(endpointType string) *GetUserOptions { options.EndpointType = core.StringPtr(endpointType) return options } // SetHeaders : Allow user to set Headers func (options *GetUserOptions) SetHeaders(param map[string]string) *GetUserOptions { options.Headers = param return options } // GetWhitelistOptions : The GetWhitelist options. type GetWhitelistOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewGetWhitelistOptions : Instantiate GetWhitelistOptions func (*IbmCloudDatabasesV5) NewGetWhitelistOptions(id string) *GetWhitelistOptions { return &GetWhitelistOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *GetWhitelistOptions) SetID(id string) *GetWhitelistOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *GetWhitelistOptions) SetHeaders(param map[string]string) *GetWhitelistOptions { options.Headers = param return options } // Group : Group struct type Group struct { // Id/name for group. ID *string `json:"id,omitempty"` // Number of entities in the group. Count *int64 `json:"count,omitempty"` Members *GroupMembers `json:"members,omitempty"` Memory *GroupMemory `json:"memory,omitempty"` Cpu *GroupCpu `json:"cpu,omitempty"` Disk *GroupDisk `json:"disk,omitempty"` } // UnmarshalGroup unmarshals an instance of Group from the specified map of raw messages. func UnmarshalGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Group) err = core.UnmarshalPrimitive(m, "id", &obj.ID) if err != nil { return } err = core.UnmarshalPrimitive(m, "count", &obj.Count) if err != nil { return } err = core.UnmarshalModel(m, "members", &obj.Members, UnmarshalGroupMembers) if err != nil { return } err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalGroupMemory) if err != nil { return } err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalGroupCpu) if err != nil { return } err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalGroupDisk) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GroupCpu : GroupCpu struct type GroupCpu struct { // Units used for scaling cpu - count means the value is the number of the unit(s) available. Units *string `json:"units,omitempty"` // Number of allocated CPUs. AllocationCount *int64 `json:"allocation_count,omitempty"` // Minimum number of CPUs. MinimumCount *int64 `json:"minimum_count,omitempty"` // Maximum number of CPUs. MaximumCount *int64 `json:"maximum_count,omitempty"` // Step size CPUs can be adjusted. StepSizeCount *int64 `json:"step_size_count,omitempty"` // Is this group's CPU count adjustable. IsAdjustable *bool `json:"is_adjustable,omitempty"` // Is this group's CPU optional?. IsOptional *bool `json:"is_optional,omitempty"` // Can this group's CPU scale down?. CanScaleDown *bool `json:"can_scale_down,omitempty"` } // UnmarshalGroupCpu unmarshals an instance of GroupCpu from the specified map of raw messages. func UnmarshalGroupCpu(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GroupCpu) err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } err = core.UnmarshalPrimitive(m, "allocation_count", &obj.AllocationCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "minimum_count", &obj.MinimumCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "maximum_count", &obj.MaximumCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "step_size_count", &obj.StepSizeCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_adjustable", &obj.IsAdjustable) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_optional", &obj.IsOptional) if err != nil { return } err = core.UnmarshalPrimitive(m, "can_scale_down", &obj.CanScaleDown) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GroupDisk : GroupDisk struct type GroupDisk struct { // Units used for scaling storage. Units *string `json:"units,omitempty"` // Allocated storage in MB. AllocationMb *int64 `json:"allocation_mb,omitempty"` // Minimum allocated storage. MinimumMb *int64 `json:"minimum_mb,omitempty"` // Maximum allocated storage. MaximumMb *int64 `json:"maximum_mb,omitempty"` // Step size storage can be adjusted. StepSizeMb *int64 `json:"step_size_mb,omitempty"` // Is this group's storage adjustable?. IsAdjustable *bool `json:"is_adjustable,omitempty"` // Is this group's storage optional?. IsOptional *bool `json:"is_optional,omitempty"` // Can this group's storage scale down?. CanScaleDown *bool `json:"can_scale_down,omitempty"` } // UnmarshalGroupDisk unmarshals an instance of GroupDisk from the specified map of raw messages. func UnmarshalGroupDisk(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GroupDisk) err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } err = core.UnmarshalPrimitive(m, "allocation_mb", &obj.AllocationMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "minimum_mb", &obj.MinimumMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "maximum_mb", &obj.MaximumMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "step_size_mb", &obj.StepSizeMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_adjustable", &obj.IsAdjustable) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_optional", &obj.IsOptional) if err != nil { return } err = core.UnmarshalPrimitive(m, "can_scale_down", &obj.CanScaleDown) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GroupMembers : GroupMembers struct type GroupMembers struct { // Units used for scaling number of members. Units *string `json:"units,omitempty"` // Allocated number of members. AllocationCount *int64 `json:"allocation_count,omitempty"` // Minimum number of members. MinimumCount *int64 `json:"minimum_count,omitempty"` // Maximum number of members. MaximumCount *int64 `json:"maximum_count,omitempty"` // Step size for number of members. StepSizeCount *int64 `json:"step_size_count,omitempty"` // Is this deployment's number of members adjustable?. IsAdjustable *bool `json:"is_adjustable,omitempty"` // Is this deployments's number of members optional?. IsOptional *bool `json:"is_optional,omitempty"` // Can this deployment's number of members scale down?. CanScaleDown *bool `json:"can_scale_down,omitempty"` } // UnmarshalGroupMembers unmarshals an instance of GroupMembers from the specified map of raw messages. func UnmarshalGroupMembers(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GroupMembers) err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } err = core.UnmarshalPrimitive(m, "allocation_count", &obj.AllocationCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "minimum_count", &obj.MinimumCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "maximum_count", &obj.MaximumCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "step_size_count", &obj.StepSizeCount) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_adjustable", &obj.IsAdjustable) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_optional", &obj.IsOptional) if err != nil { return } err = core.UnmarshalPrimitive(m, "can_scale_down", &obj.CanScaleDown) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // GroupMemory : GroupMemory struct type GroupMemory struct { // Units used for scaling memory. Units *string `json:"units,omitempty"` // Allocated memory in MB. AllocationMb *int64 `json:"allocation_mb,omitempty"` // Minimum memory in MB. MinimumMb *int64 `json:"minimum_mb,omitempty"` // Maximum memory in MB. MaximumMb *int64 `json:"maximum_mb,omitempty"` // Step size memory can be adjusted by in MB. StepSizeMb *int64 `json:"step_size_mb,omitempty"` // Is this group's memory adjustable?. IsAdjustable *bool `json:"is_adjustable,omitempty"` // Is this group's memory optional?. IsOptional *bool `json:"is_optional,omitempty"` // Can this group's memory scale down?. CanScaleDown *bool `json:"can_scale_down,omitempty"` } // UnmarshalGroupMemory unmarshals an instance of GroupMemory from the specified map of raw messages. func UnmarshalGroupMemory(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(GroupMemory) err = core.UnmarshalPrimitive(m, "units", &obj.Units) if err != nil { return } err = core.UnmarshalPrimitive(m, "allocation_mb", &obj.AllocationMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "minimum_mb", &obj.MinimumMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "maximum_mb", &obj.MaximumMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "step_size_mb", &obj.StepSizeMb) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_adjustable", &obj.IsAdjustable) if err != nil { return } err = core.UnmarshalPrimitive(m, "is_optional", &obj.IsOptional) if err != nil { return } err = core.UnmarshalPrimitive(m, "can_scale_down", &obj.CanScaleDown) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Groups : Groups struct type Groups struct { Groups []Group `json:"groups,omitempty"` } // UnmarshalGroups unmarshals an instance of Groups from the specified map of raw messages. func UnmarshalGroups(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Groups) err = core.UnmarshalModel(m, "groups", &obj.Groups, UnmarshalGroup) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // IntegerPropertySchema : Integer Property Schema. type IntegerPropertySchema struct { // Whether the setting is customer-configurable. CustomerConfigurable *bool `json:"customer_configurable,omitempty"` // The default value of the setting. Default *int64 `json:"default,omitempty"` // The description of the default value. DefaultDescription *string `json:"default_description,omitempty"` // The description of the setting. Description *string `json:"description,omitempty"` // The type of this setting (e.g., string, integer). Kind *string `json:"kind,omitempty"` // Whether or not changing this setting will restart the database. RequiresRestart *bool `json:"requires_restart,omitempty"` // The minimum value that this setting accepts. Min *int64 `json:"min,omitempty"` // The maximum value that this setting accepts. Max *int64 `json:"max,omitempty"` // The number that should be skipped between each step of a slider rendered for this setting. Step *int64 `json:"step,omitempty"` } // UnmarshalIntegerPropertySchema unmarshals an instance of IntegerPropertySchema from the specified map of raw messages. func UnmarshalIntegerPropertySchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(IntegerPropertySchema) err = core.UnmarshalPrimitive(m, "customer_configurable", &obj.CustomerConfigurable) if err != nil { return } err = core.UnmarshalPrimitive(m, "default", &obj.Default) if err != nil { return } err = core.UnmarshalPrimitive(m, "default_description", &obj.DefaultDescription) if err != nil { return } err = core.UnmarshalPrimitive(m, "description", &obj.Description) if err != nil { return } err = core.UnmarshalPrimitive(m, "kind", &obj.Kind) if err != nil { return } err = core.UnmarshalPrimitive(m, "requires_restart", &obj.RequiresRestart) if err != nil { return } err = core.UnmarshalPrimitive(m, "min", &obj.Min) if err != nil { return } err = core.UnmarshalPrimitive(m, "max", &obj.Max) if err != nil { return } err = core.UnmarshalPrimitive(m, "step", &obj.Step) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // KillConnectionsOptions : The KillConnections options. type KillConnectionsOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewKillConnectionsOptions : Instantiate KillConnectionsOptions func (*IbmCloudDatabasesV5) NewKillConnectionsOptions(id string) *KillConnectionsOptions { return &KillConnectionsOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *KillConnectionsOptions) SetID(id string) *KillConnectionsOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *KillConnectionsOptions) SetHeaders(param map[string]string) *KillConnectionsOptions { options.Headers = param return options } // KillConnectionsResponse : KillConnectionsResponse struct type KillConnectionsResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalKillConnectionsResponse unmarshals an instance of KillConnectionsResponse from the specified map of raw messages. func UnmarshalKillConnectionsResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(KillConnectionsResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // LogicalReplicationSlotLogicalReplicationSlot : LogicalReplicationSlotLogicalReplicationSlot struct type LogicalReplicationSlotLogicalReplicationSlot struct { // name of the replication slot. Name *string `json:"name,omitempty"` // name of the database the replication slot is created on. DatabaseName *string `json:"database_name,omitempty"` // creating a replication slot is only supported for use with wal2json. PluginType *string `json:"plugin_type,omitempty"` } // UnmarshalLogicalReplicationSlotLogicalReplicationSlot unmarshals an instance of LogicalReplicationSlotLogicalReplicationSlot from the specified map of raw messages. func UnmarshalLogicalReplicationSlotLogicalReplicationSlot(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(LogicalReplicationSlotLogicalReplicationSlot) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "database_name", &obj.DatabaseName) if err != nil { return } err = core.UnmarshalPrimitive(m, "plugin_type", &obj.PluginType) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // MongoDBConnectionURI : MongoDBConnectionURI struct type MongoDBConnectionURI struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []MongoDBConnectionURIHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *MongoDBConnectionURIAuthentication `json:"authentication,omitempty"` Certificate *MongoDBConnectionURICertificate `json:"certificate,omitempty"` // Name of the database to use in the URI connection. Database *string `json:"database,omitempty"` // Name of the replica set to use in the URI connection. ReplicaSet *string `json:"replica_set,omitempty"` } // UnmarshalMongoDBConnectionURI unmarshals an instance of MongoDBConnectionURI from the specified map of raw messages. func UnmarshalMongoDBConnectionURI(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(MongoDBConnectionURI) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalMongoDBConnectionURIHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalMongoDBConnectionURIAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalMongoDBConnectionURICertificate) if err != nil { return } err = core.UnmarshalPrimitive(m, "database", &obj.Database) if err != nil { return } err = core.UnmarshalPrimitive(m, "replica_set", &obj.ReplicaSet) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // MongoDBConnectionURIAuthentication : MongoDBConnectionURIAuthentication struct type MongoDBConnectionURIAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalMongoDBConnectionURIAuthentication unmarshals an instance of MongoDBConnectionURIAuthentication from the specified map of raw messages. func UnmarshalMongoDBConnectionURIAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(MongoDBConnectionURIAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // MongoDBConnectionURICertificate : MongoDBConnectionURICertificate struct type MongoDBConnectionURICertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalMongoDBConnectionURICertificate unmarshals an instance of MongoDBConnectionURICertificate from the specified map of raw messages. func UnmarshalMongoDBConnectionURICertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(MongoDBConnectionURICertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // MongoDBConnectionURIHostsItem : MongoDBConnectionURIHostsItem struct type MongoDBConnectionURIHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalMongoDBConnectionURIHostsItem unmarshals an instance of MongoDBConnectionURIHostsItem from the specified map of raw messages. func UnmarshalMongoDBConnectionURIHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(MongoDBConnectionURIHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // PointInTimeRecoveryData : PointInTimeRecoveryData struct type PointInTimeRecoveryData struct { EarliestPointInTimeRecoveryTime *string `json:"earliest_point_in_time_recovery_time,omitempty"` } // UnmarshalPointInTimeRecoveryData unmarshals an instance of PointInTimeRecoveryData from the specified map of raw messages. func UnmarshalPointInTimeRecoveryData(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(PointInTimeRecoveryData) err = core.UnmarshalPrimitive(m, "earliest_point_in_time_recovery_time", &obj.EarliestPointInTimeRecoveryTime) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // PostgreSQLConnectionURI : PostgreSQLConnectionURI struct type PostgreSQLConnectionURI struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []PostgreSQLConnectionURIHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *PostgreSQLConnectionURIAuthentication `json:"authentication,omitempty"` Certificate *PostgreSQLConnectionURICertificate `json:"certificate,omitempty"` // Name of the database to use in the URI connection. Database *string `json:"database,omitempty"` } // UnmarshalPostgreSQLConnectionURI unmarshals an instance of PostgreSQLConnectionURI from the specified map of raw messages. func UnmarshalPostgreSQLConnectionURI(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(PostgreSQLConnectionURI) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalPostgreSQLConnectionURIHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalPostgreSQLConnectionURIAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalPostgreSQLConnectionURICertificate) if err != nil { return } err = core.UnmarshalPrimitive(m, "database", &obj.Database) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // PostgreSQLConnectionURIAuthentication : PostgreSQLConnectionURIAuthentication struct type PostgreSQLConnectionURIAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalPostgreSQLConnectionURIAuthentication unmarshals an instance of PostgreSQLConnectionURIAuthentication from the specified map of raw messages. func UnmarshalPostgreSQLConnectionURIAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(PostgreSQLConnectionURIAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // PostgreSQLConnectionURICertificate : PostgreSQLConnectionURICertificate struct type PostgreSQLConnectionURICertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalPostgreSQLConnectionURICertificate unmarshals an instance of PostgreSQLConnectionURICertificate from the specified map of raw messages. func UnmarshalPostgreSQLConnectionURICertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(PostgreSQLConnectionURICertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // PostgreSQLConnectionURIHostsItem : PostgreSQLConnectionURIHostsItem struct type PostgreSQLConnectionURIHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalPostgreSQLConnectionURIHostsItem unmarshals an instance of PostgreSQLConnectionURIHostsItem from the specified map of raw messages. func UnmarshalPostgreSQLConnectionURIHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(PostgreSQLConnectionURIHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionAMQPS : RabbitMQConnectionAMQPS struct type RabbitMQConnectionAMQPS struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []RabbitMQConnectionAMQPSHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *RabbitMQConnectionAMQPSAuthentication `json:"authentication,omitempty"` Certificate *RabbitMQConnectionAMQPSCertificate `json:"certificate,omitempty"` } // UnmarshalRabbitMQConnectionAMQPS unmarshals an instance of RabbitMQConnectionAMQPS from the specified map of raw messages. func UnmarshalRabbitMQConnectionAMQPS(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionAMQPS) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalRabbitMQConnectionAMQPSHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalRabbitMQConnectionAMQPSAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalRabbitMQConnectionAMQPSCertificate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionAMQPSAuthentication : RabbitMQConnectionAMQPSAuthentication struct type RabbitMQConnectionAMQPSAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalRabbitMQConnectionAMQPSAuthentication unmarshals an instance of RabbitMQConnectionAMQPSAuthentication from the specified map of raw messages. func UnmarshalRabbitMQConnectionAMQPSAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionAMQPSAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionAMQPSCertificate : RabbitMQConnectionAMQPSCertificate struct type RabbitMQConnectionAMQPSCertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalRabbitMQConnectionAMQPSCertificate unmarshals an instance of RabbitMQConnectionAMQPSCertificate from the specified map of raw messages. func UnmarshalRabbitMQConnectionAMQPSCertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionAMQPSCertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionAMQPSHostsItem : RabbitMQConnectionAMQPSHostsItem struct type RabbitMQConnectionAMQPSHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalRabbitMQConnectionAMQPSHostsItem unmarshals an instance of RabbitMQConnectionAMQPSHostsItem from the specified map of raw messages. func UnmarshalRabbitMQConnectionAMQPSHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionAMQPSHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionHTTPS : RabbitMQConnectionHTTPS struct type RabbitMQConnectionHTTPS struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []RabbitMQConnectionHTTPSHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *RabbitMQConnectionHTTPSAuthentication `json:"authentication,omitempty"` Certificate *RabbitMQConnectionHTTPSCertificate `json:"certificate,omitempty"` // Indicates the address is accessible by browser, for the RabbitMQ Management UI. BrowserAccessible *bool `json:"browser_accessible,omitempty"` } // UnmarshalRabbitMQConnectionHTTPS unmarshals an instance of RabbitMQConnectionHTTPS from the specified map of raw messages. func UnmarshalRabbitMQConnectionHTTPS(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionHTTPS) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalRabbitMQConnectionHTTPSHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalRabbitMQConnectionHTTPSAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalRabbitMQConnectionHTTPSCertificate) if err != nil { return } err = core.UnmarshalPrimitive(m, "browser_accessible", &obj.BrowserAccessible) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionHTTPSAuthentication : RabbitMQConnectionHTTPSAuthentication struct type RabbitMQConnectionHTTPSAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalRabbitMQConnectionHTTPSAuthentication unmarshals an instance of RabbitMQConnectionHTTPSAuthentication from the specified map of raw messages. func UnmarshalRabbitMQConnectionHTTPSAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionHTTPSAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionHTTPSCertificate : RabbitMQConnectionHTTPSCertificate struct type RabbitMQConnectionHTTPSCertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalRabbitMQConnectionHTTPSCertificate unmarshals an instance of RabbitMQConnectionHTTPSCertificate from the specified map of raw messages. func UnmarshalRabbitMQConnectionHTTPSCertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionHTTPSCertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionHTTPSHostsItem : RabbitMQConnectionHTTPSHostsItem struct type RabbitMQConnectionHTTPSHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalRabbitMQConnectionHTTPSHostsItem unmarshals an instance of RabbitMQConnectionHTTPSHostsItem from the specified map of raw messages. func UnmarshalRabbitMQConnectionHTTPSHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionHTTPSHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionMQTTS : RabbitMQConnectionMQTTS struct type RabbitMQConnectionMQTTS struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []RabbitMQConnectionMQTTSHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *RabbitMQConnectionMQTTSAuthentication `json:"authentication,omitempty"` Certificate *RabbitMQConnectionMQTTSCertificate `json:"certificate,omitempty"` } // UnmarshalRabbitMQConnectionMQTTS unmarshals an instance of RabbitMQConnectionMQTTS from the specified map of raw messages. func UnmarshalRabbitMQConnectionMQTTS(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionMQTTS) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalRabbitMQConnectionMQTTSHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalRabbitMQConnectionMQTTSAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalRabbitMQConnectionMQTTSCertificate) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionMQTTSAuthentication : RabbitMQConnectionMQTTSAuthentication struct type RabbitMQConnectionMQTTSAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalRabbitMQConnectionMQTTSAuthentication unmarshals an instance of RabbitMQConnectionMQTTSAuthentication from the specified map of raw messages. func UnmarshalRabbitMQConnectionMQTTSAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionMQTTSAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionMQTTSCertificate : RabbitMQConnectionMQTTSCertificate struct type RabbitMQConnectionMQTTSCertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalRabbitMQConnectionMQTTSCertificate unmarshals an instance of RabbitMQConnectionMQTTSCertificate from the specified map of raw messages. func UnmarshalRabbitMQConnectionMQTTSCertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionMQTTSCertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionMQTTSHostsItem : RabbitMQConnectionMQTTSHostsItem struct type RabbitMQConnectionMQTTSHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalRabbitMQConnectionMQTTSHostsItem unmarshals an instance of RabbitMQConnectionMQTTSHostsItem from the specified map of raw messages. func UnmarshalRabbitMQConnectionMQTTSHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionMQTTSHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionStompSSL : RabbitMQConnectionStompSSL struct type RabbitMQConnectionStompSSL struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` Hosts []RabbitMQConnectionStompSSLHostsItem `json:"hosts,omitempty"` Authentication *RabbitMQConnectionStompSSLAuthentication `json:"authentication,omitempty"` Certificate *RabbitMQConnectionStompSSLCertificate `json:"certificate,omitempty"` // Indicates ssl is required for the connection. Ssl *bool `json:"ssl,omitempty"` } // UnmarshalRabbitMQConnectionStompSSL unmarshals an instance of RabbitMQConnectionStompSSL from the specified map of raw messages. func UnmarshalRabbitMQConnectionStompSSL(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionStompSSL) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalRabbitMQConnectionStompSSLHostsItem) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalRabbitMQConnectionStompSSLAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalRabbitMQConnectionStompSSLCertificate) if err != nil { return } err = core.UnmarshalPrimitive(m, "ssl", &obj.Ssl) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionStompSSLAuthentication : RabbitMQConnectionStompSSLAuthentication struct type RabbitMQConnectionStompSSLAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalRabbitMQConnectionStompSSLAuthentication unmarshals an instance of RabbitMQConnectionStompSSLAuthentication from the specified map of raw messages. func UnmarshalRabbitMQConnectionStompSSLAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionStompSSLAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionStompSSLCertificate : RabbitMQConnectionStompSSLCertificate struct type RabbitMQConnectionStompSSLCertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalRabbitMQConnectionStompSSLCertificate unmarshals an instance of RabbitMQConnectionStompSSLCertificate from the specified map of raw messages. func UnmarshalRabbitMQConnectionStompSSLCertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionStompSSLCertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RabbitMQConnectionStompSSLHostsItem : RabbitMQConnectionStompSSLHostsItem struct type RabbitMQConnectionStompSSLHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalRabbitMQConnectionStompSSLHostsItem unmarshals an instance of RabbitMQConnectionStompSSLHostsItem from the specified map of raw messages. func UnmarshalRabbitMQConnectionStompSSLHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RabbitMQConnectionStompSSLHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RedisConnectionURI : RedisConnectionURI struct type RedisConnectionURI struct { // Type of connection being described. Type *string `json:"type,omitempty"` Composed []string `json:"composed,omitempty"` // Scheme/protocol for URI connection. Scheme *string `json:"scheme,omitempty"` Hosts []RedisConnectionURIHostsItem `json:"hosts,omitempty"` // Path for URI connection. Path *string `json:"path,omitempty"` // Query options to add to the URI connection. QueryOptions interface{} `json:"query_options,omitempty"` Authentication *RedisConnectionURIAuthentication `json:"authentication,omitempty"` Certificate *RedisConnectionURICertificate `json:"certificate,omitempty"` // Number of the database to use in the URI connection. Database *int64 `json:"database,omitempty"` } // UnmarshalRedisConnectionURI unmarshals an instance of RedisConnectionURI from the specified map of raw messages. func UnmarshalRedisConnectionURI(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RedisConnectionURI) err = core.UnmarshalPrimitive(m, "type", &obj.Type) if err != nil { return } err = core.UnmarshalPrimitive(m, "composed", &obj.Composed) if err != nil { return } err = core.UnmarshalPrimitive(m, "scheme", &obj.Scheme) if err != nil { return } err = core.UnmarshalModel(m, "hosts", &obj.Hosts, UnmarshalRedisConnectionURIHostsItem) if err != nil { return } err = core.UnmarshalPrimitive(m, "path", &obj.Path) if err != nil { return } err = core.UnmarshalPrimitive(m, "query_options", &obj.QueryOptions) if err != nil { return } err = core.UnmarshalModel(m, "authentication", &obj.Authentication, UnmarshalRedisConnectionURIAuthentication) if err != nil { return } err = core.UnmarshalModel(m, "certificate", &obj.Certificate, UnmarshalRedisConnectionURICertificate) if err != nil { return } err = core.UnmarshalPrimitive(m, "database", &obj.Database) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RedisConnectionURIAuthentication : RedisConnectionURIAuthentication struct type RedisConnectionURIAuthentication struct { // Authentication method for this credential. Method *string `json:"method,omitempty"` // Username part of credential. Username *string `json:"username,omitempty"` // Password part of credential. Password *string `json:"password,omitempty"` } // UnmarshalRedisConnectionURIAuthentication unmarshals an instance of RedisConnectionURIAuthentication from the specified map of raw messages. func UnmarshalRedisConnectionURIAuthentication(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RedisConnectionURIAuthentication) err = core.UnmarshalPrimitive(m, "method", &obj.Method) if err != nil { return } err = core.UnmarshalPrimitive(m, "username", &obj.Username) if err != nil { return } err = core.UnmarshalPrimitive(m, "password", &obj.Password) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RedisConnectionURICertificate : RedisConnectionURICertificate struct type RedisConnectionURICertificate struct { // Name associated with the certificate. Name *string `json:"name,omitempty"` // Base64 encoded version of the certificate. CertificateBase64 *string `json:"certificate_base64,omitempty"` } // UnmarshalRedisConnectionURICertificate unmarshals an instance of RedisConnectionURICertificate from the specified map of raw messages. func UnmarshalRedisConnectionURICertificate(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RedisConnectionURICertificate) err = core.UnmarshalPrimitive(m, "name", &obj.Name) if err != nil { return } err = core.UnmarshalPrimitive(m, "certificate_base64", &obj.CertificateBase64) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // RedisConnectionURIHostsItem : RedisConnectionURIHostsItem struct type RedisConnectionURIHostsItem struct { // Hostname for connection. Hostname *string `json:"hostname,omitempty"` // Port number for connection. Port *int64 `json:"port,omitempty"` } // UnmarshalRedisConnectionURIHostsItem unmarshals an instance of RedisConnectionURIHostsItem from the specified map of raw messages. func UnmarshalRedisConnectionURIHostsItem(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(RedisConnectionURIHostsItem) err = core.UnmarshalPrimitive(m, "hostname", &obj.Hostname) if err != nil { return } err = core.UnmarshalPrimitive(m, "port", &obj.Port) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Remotes : Remotes. type Remotes struct { // Leader ID, if applicable. Leader *string `json:"leader,omitempty"` // Replica IDs, if applicable. Replicas []string `json:"replicas,omitempty"` } // UnmarshalRemotes unmarshals an instance of Remotes from the specified map of raw messages. func UnmarshalRemotes(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Remotes) err = core.UnmarshalPrimitive(m, "leader", &obj.Leader) if err != nil { return } err = core.UnmarshalPrimitive(m, "replicas", &obj.Replicas) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ReplaceWhitelistOptions : The ReplaceWhitelist options. type ReplaceWhitelistOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // An array of allowlist entries. IpAddresses []WhitelistEntry // Verify that the current allowlist matches a provided ETag value. Use in conjunction with the GET operation's ETag // header to ensure synchronicity between clients. IfMatch *string // Allows users to set headers on API requests Headers map[string]string } // NewReplaceWhitelistOptions : Instantiate ReplaceWhitelistOptions func (*IbmCloudDatabasesV5) NewReplaceWhitelistOptions(id string) *ReplaceWhitelistOptions { return &ReplaceWhitelistOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *ReplaceWhitelistOptions) SetID(id string) *ReplaceWhitelistOptions { options.ID = core.StringPtr(id) return options } // SetIpAddresses : Allow user to set IpAddresses func (options *ReplaceWhitelistOptions) SetIpAddresses(ipAddresses []WhitelistEntry) *ReplaceWhitelistOptions { options.IpAddresses = ipAddresses return options } // SetIfMatch : Allow user to set IfMatch func (options *ReplaceWhitelistOptions) SetIfMatch(ifMatch string) *ReplaceWhitelistOptions { options.IfMatch = core.StringPtr(ifMatch) return options } // SetHeaders : Allow user to set Headers func (options *ReplaceWhitelistOptions) SetHeaders(param map[string]string) *ReplaceWhitelistOptions { options.Headers = param return options } // ReplaceWhitelistResponse : ReplaceWhitelistResponse struct type ReplaceWhitelistResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalReplaceWhitelistResponse unmarshals an instance of ReplaceWhitelistResponse from the specified map of raw messages. func UnmarshalReplaceWhitelistResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ReplaceWhitelistResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetAutoscalingConditionsOptions : The SetAutoscalingConditions options. type SetAutoscalingConditionsOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Group ID. GroupID *string `validate:"required,ne="` Autoscaling AutoscalingSetGroupIntf // Allows users to set headers on API requests Headers map[string]string } // NewSetAutoscalingConditionsOptions : Instantiate SetAutoscalingConditionsOptions func (*IbmCloudDatabasesV5) NewSetAutoscalingConditionsOptions(id string, groupID string) *SetAutoscalingConditionsOptions { return &SetAutoscalingConditionsOptions{ ID: core.StringPtr(id), GroupID: core.StringPtr(groupID), } } // SetID : Allow user to set ID func (options *SetAutoscalingConditionsOptions) SetID(id string) *SetAutoscalingConditionsOptions { options.ID = core.StringPtr(id) return options } // SetGroupID : Allow user to set GroupID func (options *SetAutoscalingConditionsOptions) SetGroupID(groupID string) *SetAutoscalingConditionsOptions { options.GroupID = core.StringPtr(groupID) return options } // SetAutoscaling : Allow user to set Autoscaling func (options *SetAutoscalingConditionsOptions) SetAutoscaling(autoscaling AutoscalingSetGroupIntf) *SetAutoscalingConditionsOptions { options.Autoscaling = autoscaling return options } // SetHeaders : Allow user to set Headers func (options *SetAutoscalingConditionsOptions) SetHeaders(param map[string]string) *SetAutoscalingConditionsOptions { options.Headers = param return options } // SetAutoscalingConditionsResponse : SetAutoscalingConditionsResponse struct type SetAutoscalingConditionsResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalSetAutoscalingConditionsResponse unmarshals an instance of SetAutoscalingConditionsResponse from the specified map of raw messages. func UnmarshalSetAutoscalingConditionsResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetAutoscalingConditionsResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetCPUGroupCPU : SetCPUGroupCPU struct type SetCPUGroupCPU struct { // Number of allocated CPUs. AllocationCount *int64 `json:"allocation_count,omitempty"` } // UnmarshalSetCPUGroupCPU unmarshals an instance of SetCPUGroupCPU from the specified map of raw messages. func UnmarshalSetCPUGroupCPU(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetCPUGroupCPU) err = core.UnmarshalPrimitive(m, "allocation_count", &obj.AllocationCount) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetConfigurationConfiguration : SetConfigurationConfiguration struct // Models which "extend" this model: // - SetConfigurationConfigurationPGConfiguration // - SetConfigurationConfigurationRedisConfiguration type SetConfigurationConfiguration struct { // Maximum connections allowed. MaxConnections *int64 `json:"max_connections,omitempty"` // Max number of transactions that can be in the "prepared" state simultaneously. MaxPreparedTransactions *int64 `json:"max_prepared_transactions,omitempty"` // Deadlock timeout in ms. The time to wait on a lock before checking for deadlock. Also the duration where lock waits // will be logged. DeadlockTimeout *int64 `json:"deadlock_timeout,omitempty"` // Number of simultaneous requests that can be handled efficiently by the disk subsystem. EffectiveIoConcurrency *int64 `json:"effective_io_concurrency,omitempty"` // Maximum number of simultaneously defined replication slots. MaxReplicationSlots *int64 `json:"max_replication_slots,omitempty"` // Maximum number of simultaneously running WAL sender processes. MaxWalSenders *int64 `json:"max_wal_senders,omitempty"` // The number of 8kB shared memory buffers used by the server. Set to 1/4 of memory. Setting too high will cause // crashes or prevent the database from starting. SharedBuffers *int64 `json:"shared_buffers,omitempty"` // Sets the current transaction's synchronization level. Off can result in data loss. remote_write with enable // synchronous replication which will impact performance and availabilty. SynchronousCommit *string `json:"synchronous_commit,omitempty"` // WAL level. Set to logical to use logical decoding or logical replication. WalLevel *string `json:"wal_level,omitempty"` // The number of seconds to wait before forces a switch to the next WAL file if a new file has not been started. ArchiveTimeout *int64 `json:"archive_timeout,omitempty"` // The minimum number of milliseconds for execution time above which statements will be logged. LogMinDurationStatement *int64 `json:"log_min_duration_statement,omitempty"` // The maximum memory Redis should use, as bytes. MaxmemoryRedis *int64 `json:"maxmemory-redis,omitempty"` // The policy with which Redis evicts keys when maximum memory is reached. MaxmemoryPolicy *string `json:"maxmemory-policy,omitempty"` // If set to yes this will enable AOF persistence. Appendonly *string `json:"appendonly,omitempty"` // The maximum memory Redis should use, as bytes. MaxmemorySamples *int64 `json:"maxmemory-samples,omitempty"` // Whether or not to stop accepting writes when background persistence actions fail. StopWritesOnBgsaveError *string `json:"stop-writes-on-bgsave-error,omitempty"` } // Constants associated with the SetConfigurationConfiguration.SynchronousCommit property. // Sets the current transaction's synchronization level. Off can result in data loss. remote_write with enable // synchronous replication which will impact performance and availabilty. const ( SetConfigurationConfiguration_SynchronousCommit_Local = "local" SetConfigurationConfiguration_SynchronousCommit_Off = "off" ) // Constants associated with the SetConfigurationConfiguration.WalLevel property. // WAL level. Set to logical to use logical decoding or logical replication. const ( SetConfigurationConfiguration_WalLevel_HotStandby = "hot_standby" SetConfigurationConfiguration_WalLevel_Logical = "logical" ) // Constants associated with the SetConfigurationConfiguration.MaxmemoryPolicy property. // The policy with which Redis evicts keys when maximum memory is reached. const ( SetConfigurationConfiguration_MaxmemoryPolicy_AllkeysLru = "allkeys-lru" SetConfigurationConfiguration_MaxmemoryPolicy_AllkeysRandom = "allkeys-random" SetConfigurationConfiguration_MaxmemoryPolicy_Noeviction = "noeviction" SetConfigurationConfiguration_MaxmemoryPolicy_VolatileLru = "volatile-lru" SetConfigurationConfiguration_MaxmemoryPolicy_VolatileRandom = "volatile-random" SetConfigurationConfiguration_MaxmemoryPolicy_VolatileTTL = "volatile-ttl" ) // Constants associated with the SetConfigurationConfiguration.Appendonly property. // If set to yes this will enable AOF persistence. const ( SetConfigurationConfiguration_Appendonly_No = "no" SetConfigurationConfiguration_Appendonly_Yes = "yes" ) // Constants associated with the SetConfigurationConfiguration.StopWritesOnBgsaveError property. // Whether or not to stop accepting writes when background persistence actions fail. const ( SetConfigurationConfiguration_StopWritesOnBgsaveError_No = "no" SetConfigurationConfiguration_StopWritesOnBgsaveError_Yes = "yes" ) func (*SetConfigurationConfiguration) isaSetConfigurationConfiguration() bool { return true } type SetConfigurationConfigurationIntf interface { isaSetConfigurationConfiguration() bool } // UnmarshalSetConfigurationConfiguration unmarshals an instance of SetConfigurationConfiguration from the specified map of raw messages. func UnmarshalSetConfigurationConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetConfigurationConfiguration) err = core.UnmarshalPrimitive(m, "max_connections", &obj.MaxConnections) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_prepared_transactions", &obj.MaxPreparedTransactions) if err != nil { return } err = core.UnmarshalPrimitive(m, "deadlock_timeout", &obj.DeadlockTimeout) if err != nil { return } err = core.UnmarshalPrimitive(m, "effective_io_concurrency", &obj.EffectiveIoConcurrency) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_replication_slots", &obj.MaxReplicationSlots) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_wal_senders", &obj.MaxWalSenders) if err != nil { return } err = core.UnmarshalPrimitive(m, "shared_buffers", &obj.SharedBuffers) if err != nil { return } err = core.UnmarshalPrimitive(m, "synchronous_commit", &obj.SynchronousCommit) if err != nil { return } err = core.UnmarshalPrimitive(m, "wal_level", &obj.WalLevel) if err != nil { return } err = core.UnmarshalPrimitive(m, "archive_timeout", &obj.ArchiveTimeout) if err != nil { return } err = core.UnmarshalPrimitive(m, "log_min_duration_statement", &obj.LogMinDurationStatement) if err != nil { return } err = core.UnmarshalPrimitive(m, "maxmemory-redis", &obj.MaxmemoryRedis) if err != nil { return } err = core.UnmarshalPrimitive(m, "maxmemory-policy", &obj.MaxmemoryPolicy) if err != nil { return } err = core.UnmarshalPrimitive(m, "appendonly", &obj.Appendonly) if err != nil { return } err = core.UnmarshalPrimitive(m, "maxmemory-samples", &obj.MaxmemorySamples) if err != nil { return } err = core.UnmarshalPrimitive(m, "stop-writes-on-bgsave-error", &obj.StopWritesOnBgsaveError) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDatabaseConfigurationOptions : The SetDatabaseConfiguration options. type SetDatabaseConfigurationOptions struct { // Deployment ID. ID *string `validate:"required,ne="` Configuration SetConfigurationConfigurationIntf `validate:"required"` // Allows users to set headers on API requests Headers map[string]string } // NewSetDatabaseConfigurationOptions : Instantiate SetDatabaseConfigurationOptions func (*IbmCloudDatabasesV5) NewSetDatabaseConfigurationOptions(id string, configuration SetConfigurationConfigurationIntf) *SetDatabaseConfigurationOptions { return &SetDatabaseConfigurationOptions{ ID: core.StringPtr(id), Configuration: configuration, } } // SetID : Allow user to set ID func (options *SetDatabaseConfigurationOptions) SetID(id string) *SetDatabaseConfigurationOptions { options.ID = core.StringPtr(id) return options } // SetConfiguration : Allow user to set Configuration func (options *SetDatabaseConfigurationOptions) SetConfiguration(configuration SetConfigurationConfigurationIntf) *SetDatabaseConfigurationOptions { options.Configuration = configuration return options } // SetHeaders : Allow user to set Headers func (options *SetDatabaseConfigurationOptions) SetHeaders(param map[string]string) *SetDatabaseConfigurationOptions { options.Headers = param return options } // SetDatabaseConfigurationResponse : SetDatabaseConfigurationResponse struct type SetDatabaseConfigurationResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalSetDatabaseConfigurationResponse unmarshals an instance of SetDatabaseConfigurationResponse from the specified map of raw messages. func UnmarshalSetDatabaseConfigurationResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDatabaseConfigurationResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupOptions : The SetDeploymentScalingGroup options. type SetDeploymentScalingGroupOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Group Id. GroupID *string `validate:"required,ne="` // Scaling group settings. SetDeploymentScalingGroupRequest SetDeploymentScalingGroupRequestIntf `validate:"required"` // Allows users to set headers on API requests Headers map[string]string } // NewSetDeploymentScalingGroupOptions : Instantiate SetDeploymentScalingGroupOptions func (*IbmCloudDatabasesV5) NewSetDeploymentScalingGroupOptions(id string, groupID string, setDeploymentScalingGroupRequest SetDeploymentScalingGroupRequestIntf) *SetDeploymentScalingGroupOptions { return &SetDeploymentScalingGroupOptions{ ID: core.StringPtr(id), GroupID: core.StringPtr(groupID), SetDeploymentScalingGroupRequest: setDeploymentScalingGroupRequest, } } // SetID : Allow user to set ID func (options *SetDeploymentScalingGroupOptions) SetID(id string) *SetDeploymentScalingGroupOptions { options.ID = core.StringPtr(id) return options } // SetGroupID : Allow user to set GroupID func (options *SetDeploymentScalingGroupOptions) SetGroupID(groupID string) *SetDeploymentScalingGroupOptions { options.GroupID = core.StringPtr(groupID) return options } // SetSetDeploymentScalingGroupRequest : Allow user to set SetDeploymentScalingGroupRequest func (options *SetDeploymentScalingGroupOptions) SetSetDeploymentScalingGroupRequest(setDeploymentScalingGroupRequest SetDeploymentScalingGroupRequestIntf) *SetDeploymentScalingGroupOptions { options.SetDeploymentScalingGroupRequest = setDeploymentScalingGroupRequest return options } // SetHeaders : Allow user to set Headers func (options *SetDeploymentScalingGroupOptions) SetHeaders(param map[string]string) *SetDeploymentScalingGroupOptions { options.Headers = param return options } // SetDeploymentScalingGroupRequest : SetDeploymentScalingGroupRequest struct // Models which "extend" this model: // - SetDeploymentScalingGroupRequestSetMembersGroup // - SetDeploymentScalingGroupRequestSetMemoryGroup // - SetDeploymentScalingGroupRequestSetCPUGroup // - SetDeploymentScalingGroupRequestSetDiskGroup type SetDeploymentScalingGroupRequest struct { Members *SetMembersGroupMembers `json:"members,omitempty"` Memory *SetMemoryGroupMemory `json:"memory,omitempty"` Cpu *SetCPUGroupCPU `json:"cpu,omitempty"` Disk *SetDiskGroupDisk `json:"disk,omitempty"` } func (*SetDeploymentScalingGroupRequest) isaSetDeploymentScalingGroupRequest() bool { return true } type SetDeploymentScalingGroupRequestIntf interface { isaSetDeploymentScalingGroupRequest() bool } // UnmarshalSetDeploymentScalingGroupRequest unmarshals an instance of SetDeploymentScalingGroupRequest from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupRequest(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupRequest) err = core.UnmarshalModel(m, "members", &obj.Members, UnmarshalSetMembersGroupMembers) if err != nil { return } err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalSetMemoryGroupMemory) if err != nil { return } err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalSetCPUGroupCPU) if err != nil { return } err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalSetDiskGroupDisk) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupResponse : SetDeploymentScalingGroupResponse struct type SetDeploymentScalingGroupResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalSetDeploymentScalingGroupResponse unmarshals an instance of SetDeploymentScalingGroupResponse from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDiskGroupDisk : SetDiskGroupDisk struct type SetDiskGroupDisk struct { // Allocated storage in MB. AllocationMb *int64 `json:"allocation_mb,omitempty"` } // UnmarshalSetDiskGroupDisk unmarshals an instance of SetDiskGroupDisk from the specified map of raw messages. func UnmarshalSetDiskGroupDisk(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDiskGroupDisk) err = core.UnmarshalPrimitive(m, "allocation_mb", &obj.AllocationMb) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetMembersGroupMembers : SetMembersGroupMembers struct type SetMembersGroupMembers struct { // Allocated number of members. AllocationCount *int64 `json:"allocation_count,omitempty"` } // UnmarshalSetMembersGroupMembers unmarshals an instance of SetMembersGroupMembers from the specified map of raw messages. func UnmarshalSetMembersGroupMembers(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetMembersGroupMembers) err = core.UnmarshalPrimitive(m, "allocation_count", &obj.AllocationCount) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetMemoryGroupMemory : SetMemoryGroupMemory struct type SetMemoryGroupMemory struct { // Allocated memory in MB. AllocationMb *int64 `json:"allocation_mb,omitempty"` } // UnmarshalSetMemoryGroupMemory unmarshals an instance of SetMemoryGroupMemory from the specified map of raw messages. func UnmarshalSetMemoryGroupMemory(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetMemoryGroupMemory) err = core.UnmarshalPrimitive(m, "allocation_mb", &obj.AllocationMb) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetPromotionOptions : The SetPromotion options. type SetPromotionOptions struct { // Deployment ID. ID *string `validate:"required,ne="` Promotion SetPromotionPromotionIntf `validate:"required"` // Allows users to set headers on API requests Headers map[string]string } // NewSetPromotionOptions : Instantiate SetPromotionOptions func (*IbmCloudDatabasesV5) NewSetPromotionOptions(id string, promotion SetPromotionPromotionIntf) *SetPromotionOptions { return &SetPromotionOptions{ ID: core.StringPtr(id), Promotion: promotion, } } // SetID : Allow user to set ID func (options *SetPromotionOptions) SetID(id string) *SetPromotionOptions { options.ID = core.StringPtr(id) return options } // SetPromotion : Allow user to set Promotion func (options *SetPromotionOptions) SetPromotion(promotion SetPromotionPromotionIntf) *SetPromotionOptions { options.Promotion = promotion return options } // SetHeaders : Allow user to set Headers func (options *SetPromotionOptions) SetHeaders(param map[string]string) *SetPromotionOptions { options.Headers = param return options } // SetPromotionPromotion : SetPromotionPromotion struct // Models which "extend" this model: // - SetPromotionPromotionPromote // - SetPromotionPromotionUpgradePromote type SetPromotionPromotion struct { // Promotion options. Promotion map[string]interface{} `json:"promotion,omitempty"` } func (*SetPromotionPromotion) isaSetPromotionPromotion() bool { return true } type SetPromotionPromotionIntf interface { isaSetPromotionPromotion() bool } // UnmarshalSetPromotionPromotion unmarshals an instance of SetPromotionPromotion from the specified map of raw messages. func UnmarshalSetPromotionPromotion(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetPromotionPromotion) err = core.UnmarshalPrimitive(m, "promotion", &obj.Promotion) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetPromotionResponse : SetPromotionResponse struct type SetPromotionResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalSetPromotionResponse unmarshals an instance of SetPromotionResponse from the specified map of raw messages. func UnmarshalSetPromotionResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetPromotionResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetRemotesOptions : The SetRemotes options. type SetRemotesOptions struct { // Deployment ID. ID *string `validate:"required,ne="` Remotes *SetRemotesRequestRemotes // Option to restore instance without taking a backup once data is restored. Allows restored deployment to be available // sooner. SkipInitialBackup *bool // Allows users to set headers on API requests Headers map[string]string } // NewSetRemotesOptions : Instantiate SetRemotesOptions func (*IbmCloudDatabasesV5) NewSetRemotesOptions(id string) *SetRemotesOptions { return &SetRemotesOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *SetRemotesOptions) SetID(id string) *SetRemotesOptions { options.ID = core.StringPtr(id) return options } // SetRemotes : Allow user to set Remotes func (options *SetRemotesOptions) SetRemotes(remotes *SetRemotesRequestRemotes) *SetRemotesOptions { options.Remotes = remotes return options } // SetSkipInitialBackup : Allow user to set SkipInitialBackup func (options *SetRemotesOptions) SetSkipInitialBackup(skipInitialBackup bool) *SetRemotesOptions { options.SkipInitialBackup = core.BoolPtr(skipInitialBackup) return options } // SetHeaders : Allow user to set Headers func (options *SetRemotesOptions) SetHeaders(param map[string]string) *SetRemotesOptions { options.Headers = param return options } // SetRemotesRequestRemotes : SetRemotesRequestRemotes struct type SetRemotesRequestRemotes struct { // Leader should be an empty string. Leader *string `json:"leader,omitempty"` } // UnmarshalSetRemotesRequestRemotes unmarshals an instance of SetRemotesRequestRemotes from the specified map of raw messages. func UnmarshalSetRemotesRequestRemotes(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetRemotesRequestRemotes) err = core.UnmarshalPrimitive(m, "leader", &obj.Leader) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetRemotesResponse : SetRemotesResponse struct type SetRemotesResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalSetRemotesResponse unmarshals an instance of SetRemotesResponse from the specified map of raw messages. func UnmarshalSetRemotesResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetRemotesResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // StartOndemandBackupOptions : The StartOndemandBackup options. type StartOndemandBackupOptions struct { // Deployment ID. ID *string `validate:"required,ne="` // Allows users to set headers on API requests Headers map[string]string } // NewStartOndemandBackupOptions : Instantiate StartOndemandBackupOptions func (*IbmCloudDatabasesV5) NewStartOndemandBackupOptions(id string) *StartOndemandBackupOptions { return &StartOndemandBackupOptions{ ID: core.StringPtr(id), } } // SetID : Allow user to set ID func (options *StartOndemandBackupOptions) SetID(id string) *StartOndemandBackupOptions { options.ID = core.StringPtr(id) return options } // SetHeaders : Allow user to set Headers func (options *StartOndemandBackupOptions) SetHeaders(param map[string]string) *StartOndemandBackupOptions { options.Headers = param return options } // StartOndemandBackupResponse : StartOndemandBackupResponse struct type StartOndemandBackupResponse struct { Task *Task `json:"task,omitempty"` } // UnmarshalStartOndemandBackupResponse unmarshals an instance of StartOndemandBackupResponse from the specified map of raw messages. func UnmarshalStartOndemandBackupResponse(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(StartOndemandBackupResponse) err = core.UnmarshalModel(m, "task", &obj.Task, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Task : Task struct type Task struct { // ID of the task. ID *string `json:"id,omitempty"` // Human-readable description of the task. Description *string `json:"description,omitempty"` // The status of the task. Status *string `json:"status,omitempty"` // ID of the deployment the task is being performed on. DeploymentID *string `json:"deployment_id,omitempty"` // Indicator as percentage of progress of the task. ProgressPercent *int64 `json:"progress_percent,omitempty"` // Date and time when the task was created. CreatedAt *strfmt.DateTime `json:"created_at,omitempty"` } // Constants associated with the Task.Status property. // The status of the task. const ( Task_Status_Completed = "completed" Task_Status_Failed = "failed" Task_Status_Running = "running" ) // UnmarshalTask unmarshals an instance of Task from the specified map of raw messages. func UnmarshalTask(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Task) err = core.UnmarshalPrimitive(m, "id", &obj.ID) if err != nil { return } err = core.UnmarshalPrimitive(m, "description", &obj.Description) if err != nil { return } err = core.UnmarshalPrimitive(m, "status", &obj.Status) if err != nil { return } err = core.UnmarshalPrimitive(m, "deployment_id", &obj.DeploymentID) if err != nil { return } err = core.UnmarshalPrimitive(m, "progress_percent", &obj.ProgressPercent) if err != nil { return } err = core.UnmarshalPrimitive(m, "created_at", &obj.CreatedAt) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Tasks : Tasks struct type Tasks struct { Tasks []Task `json:"tasks,omitempty"` } // UnmarshalTasks unmarshals an instance of Tasks from the specified map of raw messages. func UnmarshalTasks(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Tasks) err = core.UnmarshalModel(m, "tasks", &obj.Tasks, UnmarshalTask) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // Whitelist : Whitelist struct type Whitelist struct { // An array of allowlist entries. IpAddresses []WhitelistEntry `json:"ip_addresses,omitempty"` } // UnmarshalWhitelist unmarshals an instance of Whitelist from the specified map of raw messages. func UnmarshalWhitelist(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(Whitelist) err = core.UnmarshalModel(m, "ip_addresses", &obj.IpAddresses, UnmarshalWhitelistEntry) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // WhitelistEntry : WhitelistEntry struct type WhitelistEntry struct { // An IPv4 address or a CIDR range (netmasked IPv4 address). Address *string `json:"address,omitempty"` // A human readable description of the address or range for identification purposes. Description *string `json:"description,omitempty"` } // UnmarshalWhitelistEntry unmarshals an instance of WhitelistEntry from the specified map of raw messages. func UnmarshalWhitelistEntry(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(WhitelistEntry) err = core.UnmarshalPrimitive(m, "address", &obj.Address) if err != nil { return } err = core.UnmarshalPrimitive(m, "description", &obj.Description) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingSetGroupAutoscalingCPUGroup : AutoscalingSetGroupAutoscalingCPUGroup struct // This model "extends" AutoscalingSetGroup type AutoscalingSetGroupAutoscalingCPUGroup struct { Cpu *AutoscalingCPUGroupCPU `json:"cpu,omitempty"` } func (*AutoscalingSetGroupAutoscalingCPUGroup) isaAutoscalingSetGroup() bool { return true } // UnmarshalAutoscalingSetGroupAutoscalingCPUGroup unmarshals an instance of AutoscalingSetGroupAutoscalingCPUGroup from the specified map of raw messages. func UnmarshalAutoscalingSetGroupAutoscalingCPUGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingSetGroupAutoscalingCPUGroup) err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalAutoscalingCPUGroupCPU) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingSetGroupAutoscalingDiskGroup : AutoscalingSetGroupAutoscalingDiskGroup struct // This model "extends" AutoscalingSetGroup type AutoscalingSetGroupAutoscalingDiskGroup struct { Disk *AutoscalingDiskGroupDisk `json:"disk,omitempty"` } func (*AutoscalingSetGroupAutoscalingDiskGroup) isaAutoscalingSetGroup() bool { return true } // UnmarshalAutoscalingSetGroupAutoscalingDiskGroup unmarshals an instance of AutoscalingSetGroupAutoscalingDiskGroup from the specified map of raw messages. func UnmarshalAutoscalingSetGroupAutoscalingDiskGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingSetGroupAutoscalingDiskGroup) err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalAutoscalingDiskGroupDisk) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // AutoscalingSetGroupAutoscalingMemoryGroup : AutoscalingSetGroupAutoscalingMemoryGroup struct // This model "extends" AutoscalingSetGroup type AutoscalingSetGroupAutoscalingMemoryGroup struct { Memory *AutoscalingMemoryGroupMemory `json:"memory,omitempty"` } func (*AutoscalingSetGroupAutoscalingMemoryGroup) isaAutoscalingSetGroup() bool { return true } // UnmarshalAutoscalingSetGroupAutoscalingMemoryGroup unmarshals an instance of AutoscalingSetGroupAutoscalingMemoryGroup from the specified map of raw messages. func UnmarshalAutoscalingSetGroupAutoscalingMemoryGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(AutoscalingSetGroupAutoscalingMemoryGroup) err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalAutoscalingMemoryGroupMemory) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConfigurationSchemaSchemaPGConfigurationSchema : PostgreSQL and EnterpriseDB Configuration Schema. // This model "extends" ConfigurationSchemaSchema type ConfigurationSchemaSchemaPGConfigurationSchema struct { // Integer Property Schema. MaxConnections *IntegerPropertySchema `json:"max_connections" validate:"required"` // Integer Property Schema. MaxPreparedConnections *IntegerPropertySchema `json:"max_prepared_connections" validate:"required"` // Integer Property Schema. BackupRetentionPeriod *IntegerPropertySchema `json:"backup_retention_period" validate:"required"` // Integer Property Schema. DeadlockTimeout *IntegerPropertySchema `json:"deadlock_timeout" validate:"required"` // Integer Property Schema. EffectiveIoConcurrency *IntegerPropertySchema `json:"effective_io_concurrency" validate:"required"` // Integer Property Schema. MaxReplicationSlots *IntegerPropertySchema `json:"max_replication_slots" validate:"required"` // Integer Property Schema. MaxWalSenders *IntegerPropertySchema `json:"max_wal_senders" validate:"required"` // Integer Property Schema. SharedBuffers *IntegerPropertySchema `json:"shared_buffers" validate:"required"` // Choice Property Schema. SynchronousCommit *ChoicePropertySchema `json:"synchronous_commit" validate:"required"` // Choice Property Schema. WalLevel *ChoicePropertySchema `json:"wal_level" validate:"required"` // Integer Property Schema. ArchiveTimeout *IntegerPropertySchema `json:"archive_timeout" validate:"required"` // Integer Property Schema. LogMinDurationStatement *IntegerPropertySchema `json:"log_min_duration_statement" validate:"required"` } func (*ConfigurationSchemaSchemaPGConfigurationSchema) isaConfigurationSchemaSchema() bool { return true } // UnmarshalConfigurationSchemaSchemaPGConfigurationSchema unmarshals an instance of ConfigurationSchemaSchemaPGConfigurationSchema from the specified map of raw messages. func UnmarshalConfigurationSchemaSchemaPGConfigurationSchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConfigurationSchemaSchemaPGConfigurationSchema) err = core.UnmarshalModel(m, "max_connections", &obj.MaxConnections, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_prepared_connections", &obj.MaxPreparedConnections, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "backup_retention_period", &obj.BackupRetentionPeriod, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "deadlock_timeout", &obj.DeadlockTimeout, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "effective_io_concurrency", &obj.EffectiveIoConcurrency, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_replication_slots", &obj.MaxReplicationSlots, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "max_wal_senders", &obj.MaxWalSenders, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "shared_buffers", &obj.SharedBuffers, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "synchronous_commit", &obj.SynchronousCommit, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "wal_level", &obj.WalLevel, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "archive_timeout", &obj.ArchiveTimeout, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "log_min_duration_statement", &obj.LogMinDurationStatement, UnmarshalIntegerPropertySchema) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConfigurationSchemaSchemaRedisConfigurationSchema : Redis Configuration Schema. // This model "extends" ConfigurationSchemaSchema type ConfigurationSchemaSchemaRedisConfigurationSchema struct { // Integer Property Schema. MaxmemoryRedis *IntegerPropertySchema `json:"maxmemory-redis" validate:"required"` // Choice Property Schema. MaxmemoryPolicy *ChoicePropertySchema `json:"maxmemory-policy" validate:"required"` // Choice Property Schema. Appendonly *ChoicePropertySchema `json:"appendonly" validate:"required"` // Integer Property Schema. MaxmemorySamples *IntegerPropertySchema `json:"maxmemory-samples" validate:"required"` // Choice Property Schema. StopWritesOnBgsaveError *ChoicePropertySchema `json:"stop-writes-on-bgsave-error" validate:"required"` } func (*ConfigurationSchemaSchemaRedisConfigurationSchema) isaConfigurationSchemaSchema() bool { return true } // UnmarshalConfigurationSchemaSchemaRedisConfigurationSchema unmarshals an instance of ConfigurationSchemaSchemaRedisConfigurationSchema from the specified map of raw messages. func UnmarshalConfigurationSchemaSchemaRedisConfigurationSchema(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConfigurationSchemaSchemaRedisConfigurationSchema) err = core.UnmarshalModel(m, "maxmemory-redis", &obj.MaxmemoryRedis, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "maxmemory-policy", &obj.MaxmemoryPolicy, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "appendonly", &obj.Appendonly, UnmarshalChoicePropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "maxmemory-samples", &obj.MaxmemorySamples, UnmarshalIntegerPropertySchema) if err != nil { return } err = core.UnmarshalModel(m, "stop-writes-on-bgsave-error", &obj.StopWritesOnBgsaveError, UnmarshalChoicePropertySchema) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionElasticsearchConnection : Elasticsearch Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionElasticsearchConnection struct { // Elasticsearch Connection information for drivers and libraries. Https *ElasticsearchConnectionHTTPS `json:"https" validate:"required"` // Connection information for cURL. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionElasticsearchConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionElasticsearchConnection unmarshals an instance of ConnectionConnectionElasticsearchConnection from the specified map of raw messages. func UnmarshalConnectionConnectionElasticsearchConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionElasticsearchConnection) err = core.UnmarshalModel(m, "https", &obj.Https, UnmarshalElasticsearchConnectionHTTPS) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionEtcdConnection : etcd3 Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionEtcdConnection struct { // GRPC(etcd3) Connection information for drivers and libraries. Grpc *GRPCConnectionURI `json:"grpc" validate:"required"` // Connection information for etcdctl. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionEtcdConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionEtcdConnection unmarshals an instance of ConnectionConnectionEtcdConnection from the specified map of raw messages. func UnmarshalConnectionConnectionEtcdConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionEtcdConnection) err = core.UnmarshalModel(m, "grpc", &obj.Grpc, UnmarshalGRPCConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionMongoDBConnection : MongoDB Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionMongoDBConnection struct { // MongoDB Connection information for drivers and libraries. Mongodb *MongoDBConnectionURI `json:"mongodb" validate:"required"` // Connection information for mongo shell. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionMongoDBConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionMongoDBConnection unmarshals an instance of ConnectionConnectionMongoDBConnection from the specified map of raw messages. func UnmarshalConnectionConnectionMongoDBConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionMongoDBConnection) err = core.UnmarshalModel(m, "mongodb", &obj.Mongodb, UnmarshalMongoDBConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionPostgreSQLConnection : PostgreSQL and EnterpriseDB Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionPostgreSQLConnection struct { // Connection information for drivers and libraries. Postgres *PostgreSQLConnectionURI `json:"postgres" validate:"required"` // Connection information for psql. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionPostgreSQLConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionPostgreSQLConnection unmarshals an instance of ConnectionConnectionPostgreSQLConnection from the specified map of raw messages. func UnmarshalConnectionConnectionPostgreSQLConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionPostgreSQLConnection) err = core.UnmarshalModel(m, "postgres", &obj.Postgres, UnmarshalPostgreSQLConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionRabbitMQConnection : RabbitMQ Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionRabbitMQConnection struct { // RabbitMQ Connection information for AMQPS drivers and libraries. Amqps *RabbitMQConnectionAMQPS `json:"amqps" validate:"required"` // RabbitMQ Connection information for MQTTS drivers and libraries. Mqtts *RabbitMQConnectionMQTTS `json:"mqtts" validate:"required"` // RabbitMQ Connection information for STOMP drivers and libraries. StompSsl *RabbitMQConnectionStompSSL `json:"stomp_ssl" validate:"required"` // RabbitMQ Connection information for HTTPS. Https *RabbitMQConnectionHTTPS `json:"https" validate:"required"` // Connection information for rabbitmqadmin. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionRabbitMQConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionRabbitMQConnection unmarshals an instance of ConnectionConnectionRabbitMQConnection from the specified map of raw messages. func UnmarshalConnectionConnectionRabbitMQConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionRabbitMQConnection) err = core.UnmarshalModel(m, "amqps", &obj.Amqps, UnmarshalRabbitMQConnectionAMQPS) if err != nil { return } err = core.UnmarshalModel(m, "mqtts", &obj.Mqtts, UnmarshalRabbitMQConnectionMQTTS) if err != nil { return } err = core.UnmarshalModel(m, "stomp_ssl", &obj.StompSsl, UnmarshalRabbitMQConnectionStompSSL) if err != nil { return } err = core.UnmarshalModel(m, "https", &obj.Https, UnmarshalRabbitMQConnectionHTTPS) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // ConnectionConnectionRedisConnection : Redis Connection Strings. // This model "extends" ConnectionConnection type ConnectionConnectionRedisConnection struct { // Connection information for drivers and libraries. Rediss *RedisConnectionURI `json:"rediss" validate:"required"` // Connection information for a Redis CLI client. Cli *ConnectionCLI `json:"cli" validate:"required"` } func (*ConnectionConnectionRedisConnection) isaConnectionConnection() bool { return true } // UnmarshalConnectionConnectionRedisConnection unmarshals an instance of ConnectionConnectionRedisConnection from the specified map of raw messages. func UnmarshalConnectionConnectionRedisConnection(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(ConnectionConnectionRedisConnection) err = core.UnmarshalModel(m, "rediss", &obj.Rediss, UnmarshalRedisConnectionURI) if err != nil { return } err = core.UnmarshalModel(m, "cli", &obj.Cli, UnmarshalConnectionCLI) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetConfigurationConfigurationPGConfiguration : PostgreSQL and EnterpriseDB Configuration. // This model "extends" SetConfigurationConfiguration type SetConfigurationConfigurationPGConfiguration struct { // Maximum connections allowed. MaxConnections *int64 `json:"max_connections,omitempty"` // Max number of transactions that can be in the "prepared" state simultaneously. MaxPreparedTransactions *int64 `json:"max_prepared_transactions,omitempty"` // Deadlock timeout in ms. The time to wait on a lock before checking for deadlock. Also the duration where lock waits // will be logged. DeadlockTimeout *int64 `json:"deadlock_timeout,omitempty"` // Number of simultaneous requests that can be handled efficiently by the disk subsystem. EffectiveIoConcurrency *int64 `json:"effective_io_concurrency,omitempty"` // Maximum number of simultaneously defined replication slots. MaxReplicationSlots *int64 `json:"max_replication_slots,omitempty"` // Maximum number of simultaneously running WAL sender processes. MaxWalSenders *int64 `json:"max_wal_senders,omitempty"` // The number of 8kB shared memory buffers used by the server. Set to 1/4 of memory. Setting too high will cause // crashes or prevent the database from starting. SharedBuffers *int64 `json:"shared_buffers,omitempty"` // Sets the current transaction's synchronization level. Off can result in data loss. remote_write with enable // synchronous replication which will impact performance and availabilty. SynchronousCommit *string `json:"synchronous_commit,omitempty"` // WAL level. Set to logical to use logical decoding or logical replication. WalLevel *string `json:"wal_level,omitempty"` // The number of seconds to wait before forces a switch to the next WAL file if a new file has not been started. ArchiveTimeout *int64 `json:"archive_timeout,omitempty"` // The minimum number of milliseconds for execution time above which statements will be logged. LogMinDurationStatement *int64 `json:"log_min_duration_statement,omitempty"` } // Constants associated with the SetConfigurationConfigurationPGConfiguration.SynchronousCommit property. // Sets the current transaction's synchronization level. Off can result in data loss. remote_write with enable // synchronous replication which will impact performance and availabilty. const ( SetConfigurationConfigurationPGConfiguration_SynchronousCommit_Local = "local" SetConfigurationConfigurationPGConfiguration_SynchronousCommit_Off = "off" ) // Constants associated with the SetConfigurationConfigurationPGConfiguration.WalLevel property. // WAL level. Set to logical to use logical decoding or logical replication. const ( SetConfigurationConfigurationPGConfiguration_WalLevel_HotStandby = "hot_standby" SetConfigurationConfigurationPGConfiguration_WalLevel_Logical = "logical" ) func (*SetConfigurationConfigurationPGConfiguration) isaSetConfigurationConfiguration() bool { return true } // UnmarshalSetConfigurationConfigurationPGConfiguration unmarshals an instance of SetConfigurationConfigurationPGConfiguration from the specified map of raw messages. func UnmarshalSetConfigurationConfigurationPGConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetConfigurationConfigurationPGConfiguration) err = core.UnmarshalPrimitive(m, "max_connections", &obj.MaxConnections) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_prepared_transactions", &obj.MaxPreparedTransactions) if err != nil { return } err = core.UnmarshalPrimitive(m, "deadlock_timeout", &obj.DeadlockTimeout) if err != nil { return } err = core.UnmarshalPrimitive(m, "effective_io_concurrency", &obj.EffectiveIoConcurrency) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_replication_slots", &obj.MaxReplicationSlots) if err != nil { return } err = core.UnmarshalPrimitive(m, "max_wal_senders", &obj.MaxWalSenders) if err != nil { return } err = core.UnmarshalPrimitive(m, "shared_buffers", &obj.SharedBuffers) if err != nil { return } err = core.UnmarshalPrimitive(m, "synchronous_commit", &obj.SynchronousCommit) if err != nil { return } err = core.UnmarshalPrimitive(m, "wal_level", &obj.WalLevel) if err != nil { return } err = core.UnmarshalPrimitive(m, "archive_timeout", &obj.ArchiveTimeout) if err != nil { return } err = core.UnmarshalPrimitive(m, "log_min_duration_statement", &obj.LogMinDurationStatement) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetConfigurationConfigurationRedisConfiguration : Redis Configuration. // This model "extends" SetConfigurationConfiguration type SetConfigurationConfigurationRedisConfiguration struct { // The maximum memory Redis should use, as bytes. MaxmemoryRedis *int64 `json:"maxmemory-redis,omitempty"` // The policy with which Redis evicts keys when maximum memory is reached. MaxmemoryPolicy *string `json:"maxmemory-policy,omitempty"` // If set to yes this will enable AOF persistence. Appendonly *string `json:"appendonly,omitempty"` // The maximum memory Redis should use, as bytes. MaxmemorySamples *int64 `json:"maxmemory-samples,omitempty"` // Whether or not to stop accepting writes when background persistence actions fail. StopWritesOnBgsaveError *string `json:"stop-writes-on-bgsave-error,omitempty"` } // Constants associated with the SetConfigurationConfigurationRedisConfiguration.MaxmemoryPolicy property. // The policy with which Redis evicts keys when maximum memory is reached. const ( SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_AllkeysLru = "allkeys-lru" SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_AllkeysRandom = "allkeys-random" SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_Noeviction = "noeviction" SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_VolatileLru = "volatile-lru" SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_VolatileRandom = "volatile-random" SetConfigurationConfigurationRedisConfiguration_MaxmemoryPolicy_VolatileTTL = "volatile-ttl" ) // Constants associated with the SetConfigurationConfigurationRedisConfiguration.Appendonly property. // If set to yes this will enable AOF persistence. const ( SetConfigurationConfigurationRedisConfiguration_Appendonly_No = "no" SetConfigurationConfigurationRedisConfiguration_Appendonly_Yes = "yes" ) // Constants associated with the SetConfigurationConfigurationRedisConfiguration.StopWritesOnBgsaveError property. // Whether or not to stop accepting writes when background persistence actions fail. const ( SetConfigurationConfigurationRedisConfiguration_StopWritesOnBgsaveError_No = "no" SetConfigurationConfigurationRedisConfiguration_StopWritesOnBgsaveError_Yes = "yes" ) func (*SetConfigurationConfigurationRedisConfiguration) isaSetConfigurationConfiguration() bool { return true } // UnmarshalSetConfigurationConfigurationRedisConfiguration unmarshals an instance of SetConfigurationConfigurationRedisConfiguration from the specified map of raw messages. func UnmarshalSetConfigurationConfigurationRedisConfiguration(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetConfigurationConfigurationRedisConfiguration) err = core.UnmarshalPrimitive(m, "maxmemory-redis", &obj.MaxmemoryRedis) if err != nil { return } err = core.UnmarshalPrimitive(m, "maxmemory-policy", &obj.MaxmemoryPolicy) if err != nil { return } err = core.UnmarshalPrimitive(m, "appendonly", &obj.Appendonly) if err != nil { return } err = core.UnmarshalPrimitive(m, "maxmemory-samples", &obj.MaxmemorySamples) if err != nil { return } err = core.UnmarshalPrimitive(m, "stop-writes-on-bgsave-error", &obj.StopWritesOnBgsaveError) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupRequestSetCPUGroup : SetDeploymentScalingGroupRequestSetCPUGroup struct // This model "extends" SetDeploymentScalingGroupRequest type SetDeploymentScalingGroupRequestSetCPUGroup struct { Cpu *SetCPUGroupCPU `json:"cpu,omitempty"` } func (*SetDeploymentScalingGroupRequestSetCPUGroup) isaSetDeploymentScalingGroupRequest() bool { return true } // UnmarshalSetDeploymentScalingGroupRequestSetCPUGroup unmarshals an instance of SetDeploymentScalingGroupRequestSetCPUGroup from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupRequestSetCPUGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupRequestSetCPUGroup) err = core.UnmarshalModel(m, "cpu", &obj.Cpu, UnmarshalSetCPUGroupCPU) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupRequestSetDiskGroup : SetDeploymentScalingGroupRequestSetDiskGroup struct // This model "extends" SetDeploymentScalingGroupRequest type SetDeploymentScalingGroupRequestSetDiskGroup struct { Disk *SetDiskGroupDisk `json:"disk,omitempty"` } func (*SetDeploymentScalingGroupRequestSetDiskGroup) isaSetDeploymentScalingGroupRequest() bool { return true } // UnmarshalSetDeploymentScalingGroupRequestSetDiskGroup unmarshals an instance of SetDeploymentScalingGroupRequestSetDiskGroup from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupRequestSetDiskGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupRequestSetDiskGroup) err = core.UnmarshalModel(m, "disk", &obj.Disk, UnmarshalSetDiskGroupDisk) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupRequestSetMembersGroup : SetDeploymentScalingGroupRequestSetMembersGroup struct // This model "extends" SetDeploymentScalingGroupRequest type SetDeploymentScalingGroupRequestSetMembersGroup struct { Members *SetMembersGroupMembers `json:"members,omitempty"` } func (*SetDeploymentScalingGroupRequestSetMembersGroup) isaSetDeploymentScalingGroupRequest() bool { return true } // UnmarshalSetDeploymentScalingGroupRequestSetMembersGroup unmarshals an instance of SetDeploymentScalingGroupRequestSetMembersGroup from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupRequestSetMembersGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupRequestSetMembersGroup) err = core.UnmarshalModel(m, "members", &obj.Members, UnmarshalSetMembersGroupMembers) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetDeploymentScalingGroupRequestSetMemoryGroup : SetDeploymentScalingGroupRequestSetMemoryGroup struct // This model "extends" SetDeploymentScalingGroupRequest type SetDeploymentScalingGroupRequestSetMemoryGroup struct { Memory *SetMemoryGroupMemory `json:"memory,omitempty"` } func (*SetDeploymentScalingGroupRequestSetMemoryGroup) isaSetDeploymentScalingGroupRequest() bool { return true } // UnmarshalSetDeploymentScalingGroupRequestSetMemoryGroup unmarshals an instance of SetDeploymentScalingGroupRequestSetMemoryGroup from the specified map of raw messages. func UnmarshalSetDeploymentScalingGroupRequestSetMemoryGroup(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetDeploymentScalingGroupRequestSetMemoryGroup) err = core.UnmarshalModel(m, "memory", &obj.Memory, UnmarshalSetMemoryGroupMemory) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetPromotionPromotionPromote : Promotes a read-only replica to a full deployment. // This model "extends" SetPromotionPromotion type SetPromotionPromotionPromote struct { // Promotion options. Promotion map[string]interface{} `json:"promotion,omitempty"` } func (*SetPromotionPromotionPromote) isaSetPromotionPromotion() bool { return true } // UnmarshalSetPromotionPromotionPromote unmarshals an instance of SetPromotionPromotionPromote from the specified map of raw messages. func UnmarshalSetPromotionPromotionPromote(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetPromotionPromotionPromote) err = core.UnmarshalPrimitive(m, "promotion", &obj.Promotion) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return } // SetPromotionPromotionUpgradePromote : Promotes a read-only replica to a full deployment running a new database version. // This model "extends" SetPromotionPromotion type SetPromotionPromotionUpgradePromote struct { // Promotion and Upgrade options. Promotion map[string]interface{} `json:"promotion,omitempty"` } func (*SetPromotionPromotionUpgradePromote) isaSetPromotionPromotion() bool { return true } // UnmarshalSetPromotionPromotionUpgradePromote unmarshals an instance of SetPromotionPromotionUpgradePromote from the specified map of raw messages. func UnmarshalSetPromotionPromotionUpgradePromote(m map[string]json.RawMessage, result interface{}) (err error) { obj := new(SetPromotionPromotionUpgradePromote) err = core.UnmarshalPrimitive(m, "promotion", &obj.Promotion) if err != nil { return } reflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj)) return }
return }
base.go
// Copyright 2021 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cgroupfs import ( "bytes" "fmt" "sort" "strconv" "strings" "gvisor.dev/gvisor/pkg/abi/linux" "gvisor.dev/gvisor/pkg/context" "gvisor.dev/gvisor/pkg/errors/linuxerr" "gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs" "gvisor.dev/gvisor/pkg/sentry/kernel" "gvisor.dev/gvisor/pkg/sentry/kernel/auth" "gvisor.dev/gvisor/pkg/sentry/vfs" "gvisor.dev/gvisor/pkg/usermem" ) // controllerCommon implements kernel.CgroupController. // // Must call init before use. // // +stateify savable type controllerCommon struct { ty kernel.CgroupControllerType fs *filesystem // parent is the parent controller if any. Immutable. // // Note that we don't have to update this on renames, since cgroup // directories can't be moved to a different parent directory. parent controller } func (c *controllerCommon) init(ty kernel.CgroupControllerType, fs *filesystem) { c.ty = ty c.fs = fs } func (c *controllerCommon) cloneFromParent(parent controller) { c.ty = parent.Type() c.fs = parent.Filesystem() c.parent = parent } // Filesystem implements controller.Filesystem. func (c *controllerCommon) Filesystem() *filesystem { return c.fs } // Type implements kernel.CgroupController.Type. func (c *controllerCommon) Type() kernel.CgroupControllerType { return kernel.CgroupControllerType(c.ty) } // HierarchyID implements kernel.CgroupController.HierarchyID. func (c *controllerCommon) HierarchyID() uint32 { return c.fs.hierarchyID } // NumCgroups implements kernel.CgroupController.NumCgroups. func (c *controllerCommon) NumCgroups() uint64 { return c.fs.numCgroups.Load() } // Enabled implements kernel.CgroupController.Enabled. // // Controllers are currently always enabled. func (c *controllerCommon) Enabled() bool { return true } // RootCgroup implements kernel.CgroupController.RootCgroup. func (c *controllerCommon) RootCgroup() kernel.Cgroup { return c.fs.rootCgroup() } // controller is an interface for common functionality related to all cgroups. // It is an extension of the public cgroup interface, containing cgroup // functionality private to cgroupfs. type controller interface { kernel.CgroupController // Filesystem returns the cgroupfs filesystem backing this controller. Filesystem() *filesystem // Clone creates a new controller based on the internal state of this // controller. This is used to initialize a sub-cgroup based on the state of // the parent. Clone() controller // AddControlFiles should extend the contents map with inodes representing // control files defined by this controller. AddControlFiles(ctx context.Context, creds *auth.Credentials, c *cgroupInode, contents map[string]kernfs.Inode) // Enter is called when a task initially moves into a cgroup. This is // distinct from migration because the task isn't migrating away from a // cgroup. Enter is called when a task is created and joins its initial // cgroup, or when cgroupfs is mounted and existing tasks are moved into // cgroups. Enter(t *kernel.Task) // Leave is called when a task leaves a cgroup. This is distinct from // migration because the task isn't migrating to another cgroup. Leave is // called when a task exits. Leave(t *kernel.Task) // PrepareMigrate signals the controller that a migration is about to // happen. The controller should check for any conditions that would prevent // the migration. If PrepareMigrate succeeds, the controller must // unconditionally either accept the migration via CommitMigrate, or roll it // back via AbortMigrate. // // Postcondition: If PrepareMigrate returns nil, caller must resolve the // migration by calling either CommitMigrate or AbortMigrate. PrepareMigrate(t *kernel.Task, src controller) error // CommitMigrate completes an in-flight migration. // // Precondition: Caller must call a corresponding PrepareMigrate. CommitMigrate(t *kernel.Task, src controller) // AbortMigrate cancels an in-flight migration. // // Precondition: Caller must call a corresponding PrepareMigrate. AbortMigrate(t *kernel.Task, src controller) // Charge charges a controller for a particular resource. The implementation // should panic if passed a resource type they do not control. Charge(t *kernel.Task, d *kernfs.Dentry, res kernel.CgroupResourceType, value int64) error } // cgroupInode implements kernel.CgroupImpl and kernfs.Inode. // // +stateify savable type cgroupInode struct { dir // controllers is the set of controllers for this cgroup. This is used to // store controller-specific state per cgroup. The set of controllers should // match the controllers for this hierarchy as tracked by the filesystem // object. Immutable. controllers map[kernel.CgroupControllerType]controller // ts is the list of tasks in this cgroup. The kernel is responsible for // removing tasks from this list before they're destroyed, so any tasks on // this list are always valid. // // ts, and cgroup membership in general is protected by fs.tasksMu. ts map[*kernel.Task]struct{} } var _ kernel.CgroupImpl = (*cgroupInode)(nil) func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credentials, parent *cgroupInode, mode linux.FileMode) kernfs.Inode { c := &cgroupInode{ dir: dir{fs: fs}, ts: make(map[*kernel.Task]struct{}), controllers: make(map[kernel.CgroupControllerType]controller), } c.dir.cgi = c contents := make(map[string]kernfs.Inode) contents["cgroup.procs"] = fs.newControllerFile(ctx, creds, &cgroupProcsData{c}) contents["tasks"] = fs.newControllerFile(ctx, creds, &tasksData{c}) if parent != nil { for ty, ctl := range parent.controllers { new := ctl.Clone() c.controllers[ty] = new new.AddControlFiles(ctx, creds, c, contents) } } else { for _, ctl := range fs.controllers { // Uniqueness of controllers enforced by the filesystem on // creation. The root cgroup uses the controllers directly from the // filesystem. c.controllers[ctl.Type()] = ctl ctl.AddControlFiles(ctx, creds, c, contents) } } c.dir.InodeAttrs.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), mode) c.dir.OrderedChildren.Init(kernfs.OrderedChildrenOptions{Writable: true}) c.dir.IncLinks(c.dir.OrderedChildren.Populate(contents)) fs.numCgroups.Add(1) return c } func (c *cgroupInode) HierarchyID() uint32 { return c.fs.hierarchyID } // Controllers implements kernel.CgroupImpl.Controllers. func (c *cgroupInode) Controllers() []kernel.CgroupController { return c.fs.kcontrollers } // tasks returns a snapshot of the tasks inside the cgroup. func (c *cgroupInode) tasks() []*kernel.Task { c.fs.tasksMu.RLock() defer c.fs.tasksMu.RUnlock() ts := make([]*kernel.Task, 0, len(c.ts)) for t := range c.ts { ts = append(ts, t) } return ts } // Enter implements kernel.CgroupImpl.Enter. func (c *cgroupInode) Enter(t *kernel.Task) { c.fs.tasksMu.Lock() defer c.fs.tasksMu.Unlock() c.ts[t] = struct{}{} for _, ctl := range c.controllers { ctl.Enter(t) } } // Leave implements kernel.CgroupImpl.Leave. func (c *cgroupInode) Leave(t *kernel.Task) { c.fs.tasksMu.Lock() defer c.fs.tasksMu.Unlock() for _, ctl := range c.controllers { ctl.Leave(t) } delete(c.ts, t) } // PrepareMigrate implements kernel.CgroupImpl.PrepareMigrate. func (c *cgroupInode) PrepareMigrate(t *kernel.Task, src *kernel.Cgroup) error { prepared := make([]controller, 0, len(c.controllers)) rollback := func() { for _, p := range prepared { c.controllers[p.Type()].AbortMigrate(t, p) } } for srcType, srcCtl := range src.CgroupImpl.(*cgroupInode).controllers { ctl := c.controllers[srcType] if err := ctl.PrepareMigrate(t, srcCtl); err != nil { rollback() return err } prepared = append(prepared, srcCtl) } return nil } // CommitMigrate implements kernel.CgroupImpl.CommitMigrate. func (c *cgroupInode) CommitMigrate(t *kernel.Task, src *kernel.Cgroup) { c.fs.tasksMu.Lock() defer c.fs.tasksMu.Unlock() for srcType, srcCtl := range src.CgroupImpl.(*cgroupInode).controllers { c.controllers[srcType].CommitMigrate(t, srcCtl) } srcI := src.CgroupImpl.(*cgroupInode) delete(srcI.ts, t) c.ts[t] = struct{}{} } // AbortMigrate implements kernel.CgroupImpl.AbortMigrate. func (c *cgroupInode) AbortMigrate(t *kernel.Task, src *kernel.Cgroup) { for srcType, srcCtl := range src.CgroupImpl.(*cgroupInode).controllers { c.controllers[srcType].AbortMigrate(t, srcCtl) } } // CgroupFromControlFileFD returns a cgroup object given a control file FD for the cgroup. func (c *cgroupInode) CgroupFromControlFileFD(fd *vfs.FileDescription) kernel.Cgroup { controlFileDentry := fd.Dentry().Impl().(*kernfs.Dentry) // The returned parent dentry remains valid without holding locks because in // cgroupfs, the parent directory relationship of a control file is // effectively immutable. Control files cannot be unlinked, renamed or // destroyed independently from their parent directory. parentD := controlFileDentry.Parent() return kernel.Cgroup{ Dentry: parentD, CgroupImpl: c, } } // Charge implements kernel.CgroupImpl.Charge. // // Charge notifies a matching controller of a change in resource usage. Due to // the uniqueness of controllers, at most one controller will match. If no // matching controller is present in this directory, the call silently // succeeds. The caller should call Charge on all hierarchies to ensure any // matching controller across the entire system is charged. func (c *cgroupInode) Charge(t *kernel.Task, d *kernfs.Dentry, ctlType kernel.CgroupControllerType, res kernel.CgroupResourceType, value int64) error { c.fs.tasksMu.RLock() defer c.fs.tasksMu.RUnlock() if ctl, ok := c.controllers[ctlType]; ok { return ctl.Charge(t, d, res, value) } return nil } func sortTIDs(tids []kernel.ThreadID) { sort.Slice(tids, func(i, j int) bool { return tids[i] < tids[j] }) } // +stateify savable type cgroupProcsData struct { *cgroupInode } // Generate implements vfs.DynamicBytesSource.Generate. func (d *cgroupProcsData) Generate(ctx context.Context, buf *bytes.Buffer) error { t := kernel.TaskFromContext(ctx) currPidns := t.ThreadGroup().PIDNamespace() pgids := make(map[kernel.ThreadID]struct{}) for _, task := range d.tasks() { // Map dedups pgid, since iterating over all tasks produces multiple // entries for the group leaders. if pgid := currPidns.IDOfThreadGroup(task.ThreadGroup()); pgid != 0 { pgids[pgid] = struct{}{} } } pgidList := make([]kernel.ThreadID, 0, len(pgids)) for pgid, _ := range pgids { pgidList = append(pgidList, pgid) } sortTIDs(pgidList) for _, pgid := range pgidList { fmt.Fprintf(buf, "%d\n", pgid) } return nil } // Write implements vfs.WritableDynamicBytesSource.Write. func (d *cgroupProcsData) Write(ctx context.Context, fd *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) { tgid, n, err := parseInt64FromString(ctx, src) if err != nil { return n, err } t := kernel.TaskFromContext(ctx) currPidns := t.ThreadGroup().PIDNamespace() targetTG := currPidns.ThreadGroupWithID(kernel.ThreadID(tgid)) if targetTG == nil { return 0, linuxerr.EINVAL } return n, targetTG.MigrateCgroup(d.CgroupFromControlFileFD(fd)) } // +stateify savable type tasksData struct { *cgroupInode } // Generate implements vfs.DynamicBytesSource.Generate. func (d *tasksData) Generate(ctx context.Context, buf *bytes.Buffer) error { t := kernel.TaskFromContext(ctx) currPidns := t.ThreadGroup().PIDNamespace() var pids []kernel.ThreadID for _, task := range d.tasks() { if pid := currPidns.IDOfTask(task); pid != 0 { pids = append(pids, pid) } } sortTIDs(pids) for _, pid := range pids { fmt.Fprintf(buf, "%d\n", pid) } return nil } // Write implements vfs.WritableDynamicBytesSource.Write. func (d *tasksData) Write(ctx context.Context, fd *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) { tid, n, err := parseInt64FromString(ctx, src) if err != nil { return n, err } t := kernel.TaskFromContext(ctx) currPidns := t.ThreadGroup().PIDNamespace() targetTask := currPidns.TaskWithID(kernel.ThreadID(tid)) if targetTask == nil { return 0, linuxerr.EINVAL } return n, targetTask.MigrateCgroup(d.CgroupFromControlFileFD(fd)) } // parseInt64FromString interprets src as string encoding a int64 value, and // returns the parsed value. func parseInt64FromString(ctx context.Context, src usermem.IOSequence) (val, len int64, err error)
// controllerStateless partially implements controller. It stubs the migration // methods with noops for a stateless controller. type controllerStateless struct{} // Enter implements controller.Enter. func (*controllerStateless) Enter(t *kernel.Task) {} // Leave implements controller.Leave. func (*controllerStateless) Leave(t *kernel.Task) {} // PrepareMigrate implements controller.PrepareMigrate. func (*controllerStateless) PrepareMigrate(t *kernel.Task, src controller) error { return nil } // CommitMigrate implements controller.CommitMigrate. func (*controllerStateless) CommitMigrate(t *kernel.Task, src controller) {} // AbortMigrate implements controller.AbortMigrate. func (*controllerStateless) AbortMigrate(t *kernel.Task, src controller) {} // controllerNoResource partially implements controller. It stubs out the Charge // method for controllers that don't track resource usage through the charge // mechanism. type controllerNoResource struct{} // Charge implements controller.Charge. func (*controllerNoResource) Charge(t *kernel.Task, d *kernfs.Dentry, res kernel.CgroupResourceType, value int64) error { panic(fmt.Sprintf("cgroupfs: Attempted to charge a controller with unknown resource %v for value %v", res, value)) }
{ const maxInt64StrLen = 20 // i.e. len(fmt.Sprintf("%d", math.MinInt64)) == 20 t := kernel.TaskFromContext(ctx) buf := t.CopyScratchBuffer(maxInt64StrLen) n, err := src.CopyIn(ctx, buf) if err != nil { return 0, int64(n), err } str := strings.TrimSpace(string(buf[:n])) val, err = strconv.ParseInt(str, 10, 64) if err != nil { // Note: This also handles zero-len writes if offset is beyond the end // of src, or src is empty. ctx.Debugf("cgroupfs.parseInt64FromString: failed to parse %q: %v", str, err) return 0, int64(n), linuxerr.EINVAL } return val, int64(n), nil }
router.ts
import { UnregisterCallback } from "history" import { RouteComponentProps } from "react-router" // tslint:disable-next-line no-empty const noop = () => {} export function getMockRouterProps<P = {}>(data: P = {} as P) { const location = { hash: "", key: "", pathname: "", search: "", state: {} } return { match: { isExact: true, params: data, path: "", url: "" }, location, history: { length: 2, action: "POP", location, push: noop, replace: noop, go: noop, goBack: noop, goForward: noop, block: () => noop as UnregisterCallback, createHref: () => "", listen: () => noop as UnregisterCallback
}, staticContext: {} } as RouteComponentProps<P> }
manifest.go
/* Copyright (c) 2020 TriggerMesh Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package manifest contains helpers to consume objects from Kubernetes manifests. package manifest import ( "io/ioutil" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/deprecated/scheme" "github.com/triggermesh/test-infra/test/e2e/framework" ) // ObjectFromFile reads a JSON/YAML manifest and unmarshals its contents into // an unstructured.Unstructured. func ObjectFromFile(path string) *unstructured.Unstructured { data, err := ioutil.ReadFile(path) if err != nil { framework.FailfWithOffset(2, "Error reading file: %s", err)
} json, err := yaml.ToJSON(data) if err != nil { framework.FailfWithOffset(2, "Failed converting YAML to JSON: %s", err) } u := &unstructured.Unstructured{} if err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), json, u); err != nil { framework.FailfWithOffset(2, "Failed decoding data into object: %s", err) } return u }
pingdom.go
package main import ( "flag" "fmt" "io/ioutil" "log" "net/url" "os" "regexp" "strconv" "strings" pingdom "github.com/russellcardullo/go-pingdom/pingdom" yaml "gopkg.in/yaml.v2" ) // PingdomCheckDefaults represents the default values type PingdomCheckDefaults struct { TimeoutMS int `yaml:"timeout_ms"` ResolutionMinutes int `yaml:"resolution_minutes"` } // PingdomCheck represents an individual check type PingdomCheck struct { URL string `yaml:"url"` TimeoutMS int `yaml:"timeout_ms"` ResolutionMinutes int `yaml:"resolution_minutes"` Teams []string `yaml:"teams"` Tags []string `yaml:"tags"` Integrations []string `yaml:"integrations"` NotifyWhenRestored bool `yaml:"notify_when_restored"` } // PingdomChecks represents the YAML config structure type PingdomChecks struct { UniqueTag string `yaml:"unique_tag"` Defaults PingdomCheckDefaults `yaml:"defaults"` Integrations []struct { Name string `yaml:"name"` ID int `yaml:"id"` } `yaml:"integrations"` Checks []PingdomCheck `yaml:"checks"` } func decomposeURL(input string) (encryption bool, hostname string, path string, err error) { u, err := url.Parse(input) if err != nil { return false, "", "", err } encryption = u.Scheme == "https" hostname = u.Hostname() // We specifically avoid using the URL parser for the path component, // relying on a regular expression instead. This is because the Go parser will // convert `%2f` characters into `/` characters in the path, but the GitLab // API (somewhat unusually) treats these as different. // // For this reason, we avoid the URL parser and rely on a regular expression // See https://gitlab.com/gitlab-com/runbooks/merge_requests/1063#note_166398758 // for more details var unparsedURLPathMatcher = regexp.MustCompile(`^https?://[^/]+(/.*)?$`) matches := unparsedURLPathMatcher.FindStringSubmatch(input) if len(matches) != 2 { return false, "", "", fmt.Errorf("Unable to parse URL path: %v", input) } path = matches[1] return encryption, hostname, path, nil } func (c PingdomCheck) name() string { return fmt.Sprintf("check:%v", c.URL) } func (c PingdomCheck) getCheck(config PingdomChecks, teamMap map[string]pingdom.TeamResponse, integrationIDMap map[string]int) pingdom.Check { timeoutMS := c.TimeoutMS if timeoutMS == 0 { timeoutMS = config.Defaults.TimeoutMS } if timeoutMS == 0 { timeoutMS = 5000 } resolutionMinutes := c.ResolutionMinutes if resolutionMinutes == 0 { resolutionMinutes = config.Defaults.ResolutionMinutes } if resolutionMinutes == 0 { resolutionMinutes = 5 } teamIds := []int{} for _, v := range c.Teams { team, ok := teamMap[v] if !ok { log.Fatalf("Unable to find team %v", v) } teamID, err := strconv.Atoi(team.ID) if err != nil { log.Fatalf("TeamID is not an integer: %s", team.ID) } teamIds = append(teamIds, teamID) } integrationIDs := []int{} for _, v := range c.Integrations { integrationID, ok := integrationIDMap[v] if !ok { log.Fatalf("Unable to find integration %v", v) } integrationIDs = append(integrationIDs, integrationID) } tags := []string{config.UniqueTag} for _, v := range c.Tags { if v != "" { tags = append(tags, v) } } encryption, hostname, path, err := decomposeURL(c.URL) if err != nil { log.Fatalf("unable to parse URL: %v", err) } tagCSV := strings.Join(tags, ",") return &pingdom.HttpCheck{ Name: c.name(), Hostname: hostname, Url: path, Encryption: encryption, Resolution: resolutionMinutes, ResponseTimeThreshold: timeoutMS, Tags: tagCSV, TeamIds: teamIds, IntegrationIds: integrationIDs, NotifyWhenBackup: c.NotifyWhenRestored, } } func findChecksForRemoval(configMap map[string]PingdomCheck, deployedChecks map[string]pingdom.CheckResponse) []pingdom.CheckResponse { var result []pingdom.CheckResponse for k, v := range deployedChecks { if _, ok := configMap[k]; !ok { result = append(result, v) } } return result } func findChecksForUpdate(configMap map[string]PingdomCheck, deployedChecks map[string]pingdom.CheckResponse) []pingdom.CheckResponse { var result []pingdom.CheckResponse for k, v := range deployedChecks { if _, ok := configMap[k]; ok { result = append(result, v) } } return result } func findChecksForInsertion(configMap map[string]PingdomCheck, deployedChecks map[string]pingdom.CheckResponse) []PingdomCheck { var result []PingdomCheck for _, v := range configMap { _, present := deployedChecks[v.name()] if !present { log.Printf("%v has not been deployed: %v", v.name(), deployedChecks) result = append(result, v) } } return result } type pingdomCheckUpdater interface { insert(name string, check pingdom.Check) error update(id int, name string, check pingdom.Check) error delete(id int, name string) error } type dryRunUpdater struct{} func (c dryRunUpdater) insert(name string, check pingdom.Check) error { log.Printf("dry-run: will create: %s", name) return nil } func (c dryRunUpdater) update(id int, name string, check pingdom.Check) error { log.Printf("dry-run: will update: %s (%s)", name, urlForPingdomCheck(id)) return nil } func (c dryRunUpdater) delete(id int, name string) error { log.Printf("dry-run: will delete: %s (%s)", name, urlForPingdomCheck(id)) return nil } type executingUpdater struct { client *pingdom.Client } func (c executingUpdater) insert(name string, check pingdom.Check) error { log.Printf("execute: creating check: %s", name) response, err := c.client.Checks.Create(check) if err != nil { return err } log.Println("execute: created check:", response) return nil } func (c executingUpdater) update(id int, name string, check pingdom.Check) error { log.Printf("execute: updating check: %s (%s)", name, urlForPingdomCheck(id)) response, err := c.client.Checks.Update(id, check) if err != nil { return err } log.Println("execute: updated check:", response) return nil } func (c executingUpdater) delete(id int, name string) error { log.Printf("execute: deleting check: %s (%s)", name, urlForPingdomCheck(id)) response, err := c.client.Checks.Delete(id) if err != nil { return err } log.Println("execute: deleted check:", response) return nil } func validateResolutionMinutes(value int, checkName string) { switch value { case 1, 5, 15, 30, 60: return } log.Fatalf("invalid value %v for `ResolutionMinutes` in %v. Allowed values are [1,5,15,30,60].", value, checkName) } func
(defaults PingdomCheckDefaults) { if defaults.ResolutionMinutes != 0 { validateResolutionMinutes(defaults.ResolutionMinutes, "defaults") } } func validateCheck(check PingdomCheck) { if check.ResolutionMinutes != 0 { validateResolutionMinutes(check.ResolutionMinutes, check.name()) } } func urlForPingdomCheck(id int) string { return fmt.Sprintf("https://my.pingdom.com/newchecks/checks#check=%d", id) } var ( configurationFile = flag.String("config", "pingdom.yml", "Configuration File") dryRun = flag.Bool("dry-run", false, "Enable dry-run mode") ) func newClient() (*pingdom.Client, error) { username := os.Getenv("PINGDOM_USERNAME") password := os.Getenv("PINGDOM_PASSWORD") appkey := os.Getenv("PINGDOM_APPKEY") accountEmail := os.Getenv("PINGDOM_ACCOUNT_EMAIL") if username == "" || password == "" || appkey == "" || accountEmail == "" { return nil, fmt.Errorf("please configure the PINGDOM_USERNAME, PINGDOM_PASSWORD, PINGDOM_APPKEY, PINGDOM_ACCOUNT_EMAIL environment variables") } client := pingdom.NewMultiUserClient(username, password, appkey, accountEmail) return client, nil } func main() { flag.Parse() yamlFile, err := ioutil.ReadFile(*configurationFile) if err != nil { log.Fatalf("unable to parse configuration %v: %v", *configurationFile, err) } var configuration PingdomChecks err = yaml.Unmarshal(yamlFile, &configuration) validateDefaults(configuration.Defaults) configMap := make(map[string]PingdomCheck) for _, v := range configuration.Checks { validateCheck(v) configMap[v.name()] = v } integrationIDMap := make(map[string]int) for _, v := range configuration.Integrations { integrationIDMap[v.Name] = v.ID } client, err := newClient() if err != nil { log.Fatalf("unable to connect: %v", err) } var updater pingdomCheckUpdater if *dryRun { updater = dryRunUpdater{} } else { updater = executingUpdater{client: client} } teams, err := client.Teams.List() if err != nil { log.Fatalf("unable to list teams: %v", err) } teamMap := make(map[string]pingdom.TeamResponse) for _, v := range teams { teamMap[v.Name] = v } checks, err := client.Checks.List() if err != nil { log.Fatalf("unable to list checks: %v", err) } deployedChecks := make(map[string]pingdom.CheckResponse) for _, v := range checks { if strings.HasPrefix(v.Name, "check:") { deployedChecks[v.Name] = v } } forRemoval := findChecksForRemoval(configMap, deployedChecks) forUpdate := findChecksForUpdate(configMap, deployedChecks) forInsertion := findChecksForInsertion(configMap, deployedChecks) // Do the inserts for _, v := range forInsertion { err := updater.insert(v.name(), v.getCheck(configuration, teamMap, integrationIDMap)) if err != nil { log.Fatalf("insert failed: %v", err) } } // Do the updates for _, update := range forUpdate { v, ok := configMap[update.Name] if !ok { log.Fatalf("Unable to lookup %s", update.Name) } err := updater.update(update.ID, v.name(), v.getCheck(configuration, teamMap, integrationIDMap)) if err != nil { log.Fatalf("update failed: %v", err) } } // Do the deletions for _, d := range forRemoval { err := updater.delete(d.ID, d.Name) if err != nil { log.Fatalf("delete failed: %v", err) } } }
validateDefaults
finished.go
// Copyright 2021 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package controller import ( "time" "github.com/chaos-mesh/chaos-mesh/api/v1alpha1" ) func IsChaosFinished(obj v1alpha1.InnerObject, now time.Time) bool { finished, _ := IsChaosFinishedWithUntilStop(obj, now) return finished } func IsChaosFinishedWithUntilStop(obj v1alpha1.InnerObject, now time.Time) (bool, time.Duration) { status := obj.GetStatus() finished := true // If one of the record has not been recovered, it's not finished for _, record := range status.Experiment.Records { if record.Phase != v1alpha1.NotInjected
} durationExceeded, untilStop, err := obj.DurationExceeded(time.Now()) if err != nil { return finished, untilStop } if durationExceeded { return finished, untilStop } if untilStop != 0 { return false, untilStop } // duration is not Exceeded, but untilStop is 0 // which means the current object is one-shot (like PodKill) // then if all records are injected, they are finished finished = true for _, record := range status.Experiment.Records { if record.Phase != v1alpha1.Injected { finished = false } } return finished, untilStop }
{ finished = false }
line_number_extractors.go
// Copyright 2018 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package herrors import ( "regexp" "strconv" ) var lineNumberExtractors = []lineNumberExtractor{ // Template/shortcode parse errors newLineNumberErrHandlerFromRegexp(`:(\d+):(\d*):`), newLineNumberErrHandlerFromRegexp(`:(\d+):`), // YAML parse errors newLineNumberErrHandlerFromRegexp(`line (\d+):`), // i18n bundle errors newLineNumberErrHandlerFromRegexp(`\((\d+),\s(\d*)`), } type lineNumberExtractor func(e error) (int, int) func newLineNumberErrHandlerFromRegexp(expression string) lineNumberExtractor { re := regexp.MustCompile(expression) return extractLineNo(re) } func extractLineNo(re *regexp.Regexp) lineNumberExtractor { return func(e error) (int, int) { if e == nil { panic("no error") } col := 1 s := e.Error() m := re.FindStringSubmatch(s) if len(m) >= 2 { lno, _ := strconv.Atoi(m[1]) if len(m) > 2
if col <= 0 { col = 1 } return lno, col } return 0, col } }
{ col, _ = strconv.Atoi(m[2]) }
main.rs
use std::{collections::HashSet, io::Read}; #[derive(Copy, Clone, Debug, PartialEq)] struct Seat { row: usize, column: usize, } impl Seat { fn id(&self) -> usize { self.row * 8 + self.column } fn parse(input: &str) -> Self
} fn part_one(input: &str) -> usize { input .lines() .map(Seat::parse) .map(|x| x.id()) .max() .unwrap_or(0) } fn part_two(input: &str) -> usize { let set = input .lines() .map(Seat::parse) .map(|x| x.id()) .collect::<HashSet<_>>(); (0..128usize) .map(|row| (0..8).map(move |column| row * 8 + column)) .flatten() .collect::<HashSet<_>>() .difference(&set) .copied() .filter(|id| (set.contains(&(id + 1)) && set.contains(&(id - 1)))) .next() .unwrap_or(0) } fn main() -> Result<(), Box<dyn std::error::Error>> { let mut input = String::new(); std::io::stdin().read_to_string(&mut input)?; dbg!(part_one(&input)); dbg!(part_two(&input)); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn one() { assert_eq!(Seat::parse("FBFBBFFRLR"), Seat { row: 44, column: 5 }); assert_eq!(Seat::parse("BFFFBBFRRR"), Seat { row: 70, column: 7 }); assert_eq!(Seat::parse("FFFBBBFRRR"), Seat { row: 14, column: 7 }); assert_eq!( Seat::parse("BBFFBBFRLL"), Seat { row: 102, column: 4 } ); } }
{ let row = input .chars() .take(7) .fold(0..128, |acc, x| { let width = acc.end - acc.start; match x { 'F' => acc.start..acc.start + width / 2, 'B' => acc.start + width / 2..acc.end, _ => panic!("bad input"), } }) .start; let column = input .chars() .skip(7) .take(3) .fold(0..8, |acc, x| { let width = acc.end - acc.start; match x { 'R' => acc.start + width / 2..acc.end, 'L' => acc.start..acc.start + width / 2, _ => panic!("bad input"), } }) .start; Self { row, column } }
json.rs
// Copyright 2018 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License");
// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use bit_vec::BitVec; use chrono::{DateTime, Duration, TimeZone, Utc}; use hex::FromHex; use rust_decimal::Decimal; /// trait `ExonumSerializeJson` implemented for all field that allows serializing in /// json format. /// // TODO refer to difference between json serialization and exonum_json (ECR-156). // TODO implement Field for float (ECR-153). // TODO remove WriteBufferWrapper hack (after refactor storage), // should be moved into storage (ECR-156). use serde_json::{self, value::Value}; use uuid::Uuid; use std::error::Error; use std::net::SocketAddr; use super::WriteBufferWrapper; use crypto::{Hash, PublicKey, Signature}; use encoding::{Field, Offset}; use helpers::{Height, Round, ValidatorId}; use messages::RawMessage; // TODO: should we implement serialize for: `SecretKey`, `Seed` (ECR-156)? macro_rules! impl_default_deserialize_owned { (@impl $name:ty) => { impl $crate::encoding::serialize::json::ExonumJsonDeserialize for $name { fn deserialize(value: &$crate::encoding::serialize::json::reexport::Value) -> Result<Self, Box<::std::error::Error>> { use $crate::encoding::serialize::json::reexport::from_value; Ok(from_value(value.clone())?) } } }; ($($name:ty);*) => ($(impl_default_deserialize_owned!{@impl $name})*); } /// `ExonumJson` is trait for object /// that can be serialized and deserialize "in-place". /// /// This trait is important for field types that could not be /// deserialized directly, for example: borrowed array. pub trait ExonumJson { /// write deserialized field in buffer on place. fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> where Self: Sized; /// serialize field as `json::Value` fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>>; } /// `ExonumJsonDeserialize` is trait for objects that could be constructed from exonum json. pub trait ExonumJsonDeserialize { /// deserialize `json` value. fn deserialize(value: &Value) -> Result<Self, Box<Error>> where Self: Sized; } #[derive(Serialize, Deserialize, Debug)] struct TimestampHelper { secs: String, nanos: u32, } #[derive(Serialize, Deserialize, Debug)] struct DurationHelper { secs: String, nanos: i32, } // implementation of deserialization macro_rules! impl_deserialize_int { (@impl $typename:ty) => { impl ExonumJson for $typename { fn deserialize_field<B: WriteBufferWrapper>(value: &Value, buffer: &mut B, from: Offset, to: Offset) -> Result<(), Box<Error>> { let number = value.as_i64().ok_or("Can't cast json as integer")?; buffer.write(from, to, number as $typename); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(Value::Number((*self).into())) } } }; ($($name:ty);*) => ($(impl_deserialize_int!{@impl $name})*); } macro_rules! impl_deserialize_bigint { (@impl $typename:ty) => { impl ExonumJson for $typename { fn deserialize_field<B: WriteBufferWrapper>(value: &Value, buffer: & mut B, from: Offset, to: Offset) -> Result<(), Box<Error>> { let string = value.as_str().ok_or("Can't cast json as string")?; let val: $typename = string.parse()?; buffer.write(from, to, val); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(Value::String(self.to_string())) } } }; ($($name:ty);*) => ($(impl_deserialize_bigint!{@impl $name})*); } macro_rules! impl_deserialize_hex_segment { (@impl $typename:ty) => { impl<'a> ExonumJson for &'a $typename { fn deserialize_field<B: WriteBufferWrapper>(value: &Value, buffer: & mut B, from: Offset, to: Offset) -> Result<(), Box<Error>> { let string = value.as_str().ok_or("Can't cast json as string")?; let val = <$typename as FromHex>:: from_hex(string)?; buffer.write(from, to, &val); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let hex_str = $crate::encoding::serialize::encode_hex(&self[..]); Ok(Value::String(hex_str)) } } }; ($($name:ty);*) => ($(impl_deserialize_hex_segment!{@impl $name})*); } impl_deserialize_int!{u8; u16; u32; i8; i16; i32} impl_deserialize_bigint!{u64; i64} impl_deserialize_hex_segment!{Hash; PublicKey; Signature} impl_default_deserialize_owned!{u8; u16; u32; i8; i16; i32; u64; i64} impl_default_deserialize_owned!{Hash; PublicKey; Signature; bool} impl ExonumJson for bool { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let val = value.as_bool().ok_or("Can't cast json as bool")?; buffer.write(from, to, val); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(Value::Bool(*self)) } } impl<'a> ExonumJson for &'a str { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let val = value.as_str().ok_or("Can't cast json as string")?; buffer.write(from, to, val); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(Value::String(self.to_string())) } } impl ExonumJson for DateTime<Utc> { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let helper: TimestampHelper = serde_json::from_value(value.clone())?; let date_time = Utc.timestamp(helper.secs.parse()?, helper.nanos); buffer.write(from, to, date_time); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let timestamp = TimestampHelper { secs: self.timestamp().to_string(), nanos: self.timestamp_subsec_nanos(), }; Ok(serde_json::to_value(&timestamp)?) } } impl ExonumJson for Duration { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let helper: DurationHelper = serde_json::from_value(value.clone())?; let seconds = helper.secs.parse()?; let seconds_duration = Duration::seconds(seconds); let nanos_duration = Duration::nanoseconds(i64::from(helper.nanos)); let result = seconds_duration.checked_add(&nanos_duration); match result { Some(duration) => { buffer.write(from, to, duration); Ok(()) } None => Err(format!( "Can't deserialize Duration: {} secs, {} nanos", seconds, helper.nanos ))?, } } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let secs = self.num_seconds(); let nanos_as_duration = *self - Duration::seconds(secs); // Since we're working with only nanos, no overflow is expected here. let nanos = nanos_as_duration.num_nanoseconds().unwrap() as i32; let timestamp = DurationHelper { secs: secs.to_string(), nanos, }; Ok(serde_json::to_value(&timestamp)?) } } impl ExonumJson for SocketAddr { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let addr: SocketAddr = serde_json::from_value(value.clone())?; buffer.write(from, to, addr); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(serde_json::to_value(&self)?) } } impl<'a> ExonumJson for &'a [Hash] { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let arr = value.as_array().ok_or("Can't cast json as array")?; let mut vec: Vec<Hash> = Vec::new(); for el in arr { let string = el.as_str().ok_or("Can't cast json as string")?; let hash = <Hash as FromHex>::from_hex(string)?; vec.push(hash) } buffer.write(from, to, vec.as_slice()); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let mut vec = Vec::new(); for hash in self.iter() { vec.push(hash.serialize_field()?) } Ok(Value::Array(vec)) } } impl<'a> ExonumJson for &'a [u8] { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let bytes = value.as_str().ok_or("Can't cast json as string")?; let arr = <Vec<u8> as FromHex>::from_hex(bytes)?; buffer.write(from, to, arr.as_slice()); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(Value::String(::encoding::serialize::encode_hex(self))) } } impl ExonumJson for Vec<RawMessage> { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { use messages::MessageBuffer; let bytes = value.as_array().ok_or("Can't cast json as array")?; let mut vec: Vec<_> = Vec::new(); for el in bytes { let string = el.as_str().ok_or("Can't cast json as string")?; let str_hex = <Vec<u8> as FromHex>::from_hex(string)?; vec.push(RawMessage::new(MessageBuffer::from_vec(str_hex))); } buffer.write(from, to, vec); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let vec = self.iter() .map(|slice| Value::String(::encoding::serialize::encode_hex(slice))) .collect(); Ok(Value::Array(vec)) } } impl<T> ExonumJsonDeserialize for Vec<T> where T: ExonumJsonDeserialize, for<'a> Vec<T>: Field<'a>, { fn deserialize(value: &Value) -> Result<Self, Box<Error>> { let bytes = value.as_array().ok_or("Can't cast json as array")?; let mut vec: Vec<_> = Vec::new(); for el in bytes { let obj = T::deserialize(el)?; vec.push(obj); } Ok(vec) } } // TODO remove `ExonumJsonDeserialize` needs // after it remove impl `ExonumJsonDeserialize` for all types expect struct (ECR-156) impl<T> ExonumJson for Vec<T> where T: ExonumJsonDeserialize + ExonumJson, for<'a> Vec<T>: Field<'a>, { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let bytes = value.as_array().ok_or("Can't cast json as array")?; let mut vec: Vec<_> = Vec::new(); for el in bytes { let obj = T::deserialize(el)?; vec.push(obj); } buffer.write(from, to, vec); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let mut vec = Vec::new(); for item in self { vec.push(item.serialize_field()?); } Ok(Value::Array(vec)) } } impl ExonumJson for BitVec { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let string = value.as_str().ok_or("Can't cast json as string")?; let mut vec = BitVec::new(); for (i, ch) in string.chars().enumerate() { let val = if ch == '1' { true } else if ch == '0' { false } else { Err(format!("BitVec should contain only 0 or 1, not {}", ch))? }; vec.set(i, val); } buffer.write(from, to, vec); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let mut out = String::new(); for i in self.iter() { if i { out.push('1'); } else { out.push('0'); } } Ok(Value::String(out)) } } // TODO: Make a macro for tuple struct type definitions (ECR-154)? impl ExonumJson for Height { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let val: u64 = value.as_str().ok_or("Can't cast json as string")?.parse()?; buffer.write(from, to, Height(val)); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let val: u64 = self.to_owned().into(); Ok(Value::String(val.to_string())) } } impl ExonumJson for Round { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let number = value.as_i64().ok_or("Can't cast json as integer")?; buffer.write(from, to, Round(number as u32)); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let val: u32 = self.to_owned().into(); Ok(Value::Number(val.into())) } } impl ExonumJson for ValidatorId { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let number = value.as_i64().ok_or("Can't cast json as integer")?; buffer.write(from, to, ValidatorId(number as u16)); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { let val: u16 = self.to_owned().into(); Ok(Value::Number(val.into())) } } impl ExonumJson for Uuid { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let uuid: Self = serde_json::from_value(value.clone())?; buffer.write(from, to, uuid); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(serde_json::to_value(&self)?) } } impl ExonumJson for Decimal { fn deserialize_field<B: WriteBufferWrapper>( value: &Value, buffer: &mut B, from: Offset, to: Offset, ) -> Result<(), Box<Error>> { let decimal: Self = serde_json::from_value(value.clone())?; buffer.write(from, to, decimal); Ok(()) } fn serialize_field(&self) -> Result<Value, Box<Error + Send + Sync>> { Ok(serde_json::to_value(&self)?) } } /// Reexport of `serde` specific traits, this reexports /// provide compatibility layer with important `serde_json` version. pub mod reexport { pub use serde_json::map::Map; pub use serde_json::{from_str, from_value, to_string, to_value, Error, Value}; } #[cfg(test)] mod tests { #![allow(unsafe_code)] use super::*; use encoding::CheckedOffset; #[test] fn exonum_json_for_duration_round_trip() { let durations = [ Duration::zero(), Duration::max_value(), Duration::min_value(), Duration::nanoseconds(999_999_999), Duration::nanoseconds(-999_999_999), Duration::seconds(42) + Duration::nanoseconds(15), Duration::seconds(-42) + Duration::nanoseconds(-15), ]; // Variables for serialization/deserialization let mut buffer = vec![0; Duration::field_size() as usize]; let from: Offset = 0; let to: Offset = Duration::field_size(); let checked_from = CheckedOffset::new(from); let checked_to = CheckedOffset::new(to); for duration in durations.iter() { let serialized = duration .serialize_field() .expect("Can't serialize duration"); Duration::deserialize_field(&serialized, &mut buffer, from, to) .expect("Can't deserialize duration"); Duration::check(&buffer, checked_from, checked_to, checked_to) .expect("Incorrect result of deserialization"); let result_duration; unsafe { result_duration = Duration::read(&buffer, from, to); } assert_eq!(*duration, result_duration); } } }
// you may not use this file except in compliance with the License. // You may obtain a copy of the License at
helloworld.py
from pkg_resources import resource_filename from .base import set_base_parser from .helper import add_arg_group from ..helper import get_random_identity def
(parser=None): if not parser: parser = set_base_parser() gp = add_arg_group(parser, title='General') gp.add_argument('--workdir', type=str, default=get_random_identity(), help='the workdir for hello-world demo, ' 'all data, indices, shards and outputs will be saved there') gp.add_argument('--logserver', action='store_true', default=False, help='start a log server for the dashboard') gp.add_argument('--logserver-config', type=str, default=resource_filename('jina', '/'.join(('resources', 'logserver.default.yml'))), help='the yaml config of the log server') gp.add_argument('--download-proxy', type=str, help='specify the proxy when downloading sample data') gp = add_arg_group(parser, title='Scalability') gp.add_argument('--shards', type=int, default=2, help='number of shards when index and query') gp.add_argument('--parallel', type=int, default=2, help='number of parallel when index and query') gp = add_arg_group(parser, title='Index') gp.add_argument('--uses-index', type=str, default=resource_filename('jina', '/'.join(('resources', 'helloworld.flow.index.yml'))), help='the yaml path of the index flow') gp.add_argument('--index-data-url', type=str, default='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz', help='the url of index data (should be in idx3-ubyte.gz format)') gp.add_argument('--index-labels-url', type=str, default='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz', help='the url of index labels data (should be in idx3-ubyte.gz format)') gp.add_argument('--index-batch-size', type=int, default=1024, help='the batch size in indexing') gp = add_arg_group(parser, title='Search') gp.add_argument('--uses-query', type=str, default=resource_filename('jina', '/'.join(('resources', 'helloworld.flow.query.yml'))), help='the yaml path of the query flow') gp.add_argument('--query-data-url', type=str, default='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz', help='the url of query data (should be in idx3-ubyte.gz format)') gp.add_argument('--query-labels-url', type=str, default='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz', help='the url of query labels data (should be in idx3-ubyte.gz format)') gp.add_argument('--query-batch-size', type=int, default=32, help='the batch size in searching') gp.add_argument('--num-query', type=int, default=128, help='number of queries to visualize') gp.add_argument('--top-k', type=int, default=50, help='top-k results to retrieve and visualize') return parser
set_hw_parser
structs.rs
use std::cmp::{max, min}; use std::fmt; use crate::formatter::{get_term_style, style::Stylesheet}; /// List of lines to be displayed. pub struct
<'a> { pub body: Vec<DisplayLine<'a>>, pub stylesheet: Box<dyn Stylesheet>, pub anonymized_line_numbers: bool, pub margin: Option<Margin>, } impl<'a> From<Vec<DisplayLine<'a>>> for DisplayList<'a> { fn from(body: Vec<DisplayLine<'a>>) -> DisplayList<'a> { Self { body, anonymized_line_numbers: false, stylesheet: get_term_style(false), margin: None, } } } impl<'a> PartialEq for DisplayList<'a> { fn eq(&self, other: &Self) -> bool { self.body == other.body && self.anonymized_line_numbers == other.anonymized_line_numbers } } impl<'a> fmt::Debug for DisplayList<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DisplayList") .field("body", &self.body) .field("anonymized_line_numbers", &self.anonymized_line_numbers) .finish() } } #[derive(Debug, Default, Copy, Clone)] pub struct FormatOptions { pub color: bool, pub anonymized_line_numbers: bool, pub margin: Option<Margin>, } #[derive(Clone, Copy, Debug)] pub struct Margin { /// The available whitespace in the left that can be consumed when centering. whitespace_left: usize, /// The column of the beginning of left-most span. span_left: usize, /// The column of the end of right-most span. span_right: usize, /// The beginning of the line to be displayed. computed_left: usize, /// The end of the line to be displayed. computed_right: usize, /// The current width of the terminal. 140 by default and in tests. column_width: usize, /// The end column of a span label, including the span. Doesn't account for labels not in the /// same line as the span. label_right: usize, } impl Margin { pub fn new( whitespace_left: usize, span_left: usize, span_right: usize, label_right: usize, column_width: usize, max_line_len: usize, ) -> Self { // The 6 is padding to give a bit of room for `...` when displaying: // ``` // error: message // --> file.rs:16:58 // | // 16 | ... fn foo(self) -> Self::Bar { // | ^^^^^^^^^ // ``` let mut m = Margin { whitespace_left: whitespace_left.saturating_sub(6), span_left: span_left.saturating_sub(6), span_right: span_right + 6, computed_left: 0, computed_right: 0, column_width, label_right: label_right + 6, }; m.compute(max_line_len); m } pub(crate) fn was_cut_left(&self) -> bool { self.computed_left > 0 } pub(crate) fn was_cut_right(&self, line_len: usize) -> bool { let right = if self.computed_right == self.span_right || self.computed_right == self.label_right { // Account for the "..." padding given above. Otherwise we end up with code lines that // do fit but end in "..." as if they were trimmed. self.computed_right - 6 } else { self.computed_right }; right < line_len && self.computed_left + self.column_width < line_len } fn compute(&mut self, max_line_len: usize) { // When there's a lot of whitespace (>20), we want to trim it as it is useless. self.computed_left = if self.whitespace_left > 20 { self.whitespace_left - 16 // We want some padding. } else { 0 }; // We want to show as much as possible, max_line_len is the right-most boundary for the // relevant code. self.computed_right = max(max_line_len, self.computed_left); if self.computed_right - self.computed_left > self.column_width { // Trimming only whitespace isn't enough, let's get craftier. if self.label_right - self.whitespace_left <= self.column_width { // Attempt to fit the code window only trimming whitespace. self.computed_left = self.whitespace_left; self.computed_right = self.computed_left + self.column_width; } else if self.label_right - self.span_left <= self.column_width { // Attempt to fit the code window considering only the spans and labels. let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.column_width; } else if self.span_right - self.span_left <= self.column_width { // Attempt to fit the code window considering the spans and labels plus padding. let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.column_width; } else { // Mostly give up but still don't show the full line. self.computed_left = self.span_left; self.computed_right = self.span_right; } } } pub(crate) fn left(&self, line_len: usize) -> usize { min(self.computed_left, line_len) } pub(crate) fn right(&self, line_len: usize) -> usize { if line_len.saturating_sub(self.computed_left) <= self.column_width { line_len } else { min(line_len, self.computed_right) } } } /// Inline annotation which can be used in either Raw or Source line. #[derive(Debug, PartialEq)] pub struct Annotation<'a> { pub annotation_type: DisplayAnnotationType, pub id: Option<&'a str>, pub label: Vec<DisplayTextFragment<'a>>, } /// A single line used in `DisplayList`. #[derive(Debug, PartialEq)] pub enum DisplayLine<'a> { /// A line with `lineno` portion of the slice. Source { lineno: Option<usize>, inline_marks: Vec<DisplayMark>, line: DisplaySourceLine<'a>, }, /// A line indicating a folded part of the slice. Fold { inline_marks: Vec<DisplayMark> }, /// A line which is displayed outside of slices. Raw(DisplayRawLine<'a>), } /// A source line. #[derive(Debug, PartialEq)] pub enum DisplaySourceLine<'a> { /// A line with the content of the Slice. Content { text: &'a str, range: (usize, usize), // meta information for annotation placement. }, /// An annotation line which is displayed in context of the slice. Annotation { annotation: Annotation<'a>, range: (usize, usize), annotation_type: DisplayAnnotationType, annotation_part: DisplayAnnotationPart, }, /// An empty source line. Empty, } /// Raw line - a line which does not have the `lineno` part and is not considered /// a part of the snippet. #[derive(Debug, PartialEq)] pub enum DisplayRawLine<'a> { /// A line which provides information about the location of the given /// slice in the project structure. Origin { path: &'a str, pos: Option<(usize, usize)>, header_type: DisplayHeaderType, }, /// An annotation line which is not part of any snippet. Annotation { annotation: Annotation<'a>, /// If set to `true`, the annotation will be aligned to the /// lineno delimiter of the snippet. source_aligned: bool, /// If set to `true`, only the label of the `Annotation` will be /// displayed. It allows for a multiline annotation to be aligned /// without displaing the meta information (`type` and `id`) to be /// displayed on each line. continuation: bool, }, } /// An inline text fragment which any label is composed of. #[derive(Debug, PartialEq)] pub struct DisplayTextFragment<'a> { pub content: &'a str, pub style: DisplayTextStyle, } /// A style for the `DisplayTextFragment` which can be visually formatted. /// /// This information may be used to emphasis parts of the label. #[derive(Debug, Clone, Copy, PartialEq)] pub enum DisplayTextStyle { Regular, Emphasis, } /// An indicator of what part of the annotation a given `Annotation` is. #[derive(Debug, Clone, PartialEq)] pub enum DisplayAnnotationPart { /// A standalone, single-line annotation. Standalone, /// A continuation of a multi-line label of an annotation. LabelContinuation, /// A consequitive annotation in case multiple annotations annotate a single line. Consequitive, /// A line starting a multiline annotation. MultilineStart, /// A line ending a multiline annotation. MultilineEnd, } /// A visual mark used in `inline_marks` field of the `DisplaySourceLine`. #[derive(Debug, Clone, PartialEq)] pub struct DisplayMark { pub mark_type: DisplayMarkType, pub annotation_type: DisplayAnnotationType, } /// A type of the `DisplayMark`. #[derive(Debug, Clone, PartialEq)] pub enum DisplayMarkType { /// A mark indicating a multiline annotation going through the current line. AnnotationThrough, /// A mark indicating a multiline annotation starting on the given line. AnnotationStart, } /// A type of the `Annotation` which may impact the sigils, style or text displayed. /// /// There are several ways to uses this information when formatting the `DisplayList`: /// /// * An annotation may display the name of the type like `error` or `info`. /// * An underline for `Error` may be `^^^` while for `Warning` it coule be `---`. /// * `ColorStylesheet` may use different colors for different annotations. #[derive(Debug, Clone, PartialEq)] pub enum DisplayAnnotationType { None, Error, Warning, Info, Note, Help, } /// Information whether the header is the initial one or a consequitive one /// for multi-slice cases. // TODO: private #[derive(Debug, Clone, PartialEq)] pub enum DisplayHeaderType { /// Initial header is the first header in the snippet. Initial, /// Continuation marks all headers of following slices in the snippet. Continuation, }
DisplayList
mockPaginator_test.go
// +build example package main import ( "testing" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/defaults" "github.com/aws/aws-sdk-go-v2/service/s3" ) type mockS3Client struct { *s3.Client index int objects []s3.ListObjectsOutput } func (c *mockS3Client) ListObjectsRequest(input *s3.ListObjectsInput) s3.ListObjectsRequest { req := c.Client.ListObjectsRequest(input) req.Copy = func(v *s3.ListObjectsInput) s3.ListObjectsRequest { r := c.Client.ListObjectsRequest(v) r.Handlers.Clear() r.Handlers.Send.PushBack(func(r *aws.Request) { object := c.objects[c.index] r.Data = &object c.index++ }) return r } return req }
objects := []s3.ListObjectsOutput{ { Contents: []s3.Object{ { Key: aws.String("1"), }, }, NextMarker: aws.String("marker"), IsTruncated: aws.Bool(true), }, { Contents: []s3.Object{ { Key: aws.String("2"), }, }, NextMarker: aws.String("marker"), IsTruncated: aws.Bool(true), }, { Contents: []s3.Object{ { Key: aws.String("3"), }, }, IsTruncated: aws.Bool(false), }, { Contents: []s3.Object{ { Key: aws.String("2"), }, }, NextMarker: aws.String("marker"), IsTruncated: aws.Bool(true), }, } svc.Client = s3.New(defaults.Config()) svc.objects = objects keys := getKeys(svc, "foo") expected := []string{"1", "2", "3"} if e, a := 3, len(keys); e != a { t.Errorf("expected %d, but received %d", e, a) } for i := 0; i < 3; i++ { if keys[i] != expected[i] { t.Errorf("expected %q, but received %q", expected[i], keys[i]) } } }
func TestListObjectsPagination(t *testing.T) { svc := &mockS3Client{}
database.go
// Package core defines core API objects and functions // (e.g. database, security and config methods). // The file database.go defines the database object. package core import ( "database/sql" "time" driver "gorm.io/driver/sqlite" "gorm.io/gorm" ) // ** Interface and Struct type DatabaseI interface { Connect() Migrate(models []interface{}) Orm() *gorm.DB } type database struct { pool *sql.DB orm *gorm.DB Config DatabaseConfig } // ** Database Methods // Connect establishes a connection and builds a pool and orm. func (db *database) Connect() { orm, err := gorm.Open(driver.Open(db.Config.Uri), &gorm.Config{}) if err != nil { panic("Failed to connect to database!") } db.orm = orm pool, err := db.orm.DB() db.pool = pool db.pool.SetMaxIdleConns(10) db.pool.SetMaxOpenConns(100) db.pool.SetConnMaxLifetime(time.Hour) } // Migrate uses the ORM system to build the required tables. func (db *database) Migrate(models []interface{}) { db.orm.AutoMigrate(models...) } // Orm return the ORM object for use. func (db *database) Orm() *gorm.DB { return db.orm } // ** Constructor // NewDatabase is the database struct constructor. func
(dialect string, uri string) DatabaseI { db := new(database) db.Config = DatabaseConfig{dialect, uri} return db }
NewDatabase
account.spec.ts
import { AddAccountRepository } from '../../../../data/protocols/add-account-repository' import { MongoHelper } from '../helpers/mongo-helper' import { AccountMongoRepository } from './account-mongo-repository' describe('Account Mongo Repository', () => { beforeAll(async () => { await MongoHelper.connect(process.env.MONGO_URL as string) }) afterAll(async () => { await MongoHelper.disconnect() }) beforeEach(async () => { const accountCollection = await MongoHelper.getCollection('accounts') await accountCollection.deleteMany({}) }) const makeSut = (): AddAccountRepository => new AccountMongoRepository() test('Should return an account on success', async () => { const sut = makeSut() const account = await sut.add({ name: 'any_name', email: '[email protected]', password: 'any_password' }) expect(account).toBeTruthy() expect(account.id).toBeTruthy() expect(account.name).toBe('any_name') expect(account.email).toBe('[email protected]') expect(account.password).toBe('any_password') })
})
pattern.rs
use unitest::testing::{must, test, unit}; /// returns true if matched pub macro matches { ( $e:expr , $( $p:tt )+ ) => ( match $e { $($p)+ => true, _ => false } ), } /// unwraps an option pub macro unwrap_or { ( return : $e:expr , $r:expr ) => ( match $e { Some(e) => e, None => return $r, } ), ( die : $e:expr ) => ( match $e { Some(e) => e, None => return panic!() } ), } /// this returns a result fn
() -> Result<(), String> { Ok(()) } /// this returns an error fn err() -> Result<(), String> { Err(format!("")) } /// this unwraps an option or returns pub macro result_or { ( die: $e:expr ) => ( match $e { Ok(v) => v, Err(e) => panic!("{} - {}", stringify!($e), e), } ), () => {} } unit!( test!( should_be_ok, must!(eq: result_or!(die: ok()), ()) ); test!( should_be_err, must!(die: result_or!(die: err())) ); ); unit!( test!( returns_matched_value, must!( truthy: matches!(Some("-12"), Some(bar) if matches!(bar.as_bytes()[0], b'+' | b'-') && matches!(bar.as_bytes()[1], b'0'..= b'9') ) ) ); );
ok
component---src-pages-using-ssr-js-ad8206a568411e9f1702.js
"use strict";(self.webpackChunkhyunsublog=self.webpackChunkhyunsublog||[]).push([[476],{9698:function(e,t,r){r.r(t);var n=r(7294),a=r(1597),o=r(262);t.default=function(e){e.serverData;return n.createElement(n.Fragment,null,n.createElement(o.Z,{title:""}),n.createElement("h1",null,"SSR page"),n.createElement("p",null,"Welcome to a server side rendered page with a random dog photo"),n.createElement("p",null,"To learn more, head over to our"," ",n.createElement("a",{href:"https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/"},"documentation about Server Side Rendering"),"."),n.createElement(a.Link,{to:"/"},"Go back to the homepage"))}}}]); //# sourceMappingURL=component---src-pages-using-ssr-js-ad8206a568411e9f1702.js.map
state.rs
use crate::common::Message; use arrayvec::ArrayVec; use bytes::{Bytes, BytesMut}; use derive_more::{Deref, DerefMut}; use ethnum::U256; use getset::{Getters, MutGetters}; use serde::Serialize; pub const STACK_SIZE: usize = 1024; /// EVM stack. #[derive(Clone, Debug, Default, Serialize)] pub struct Stack(pub ArrayVec<U256, STACK_SIZE>); impl Stack { #[inline(always)] pub const fn new() -> Self { Self(ArrayVec::new_const()) } #[inline(always)] fn get_pos(&self, pos: usize) -> usize { self.len() - 1 - pos } #[inline(always)] pub fn get(&self, pos: usize) -> &U256 { &self.0[self.get_pos(pos)] } #[inline(always)] pub fn get_mut(&mut self, pos: usize) -> &mut U256 { let pos = self.get_pos(pos); &mut self.0[pos] } #[inline(always)] pub fn len(&self) -> usize { self.0.len() } #[inline(always)]
pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline(always)] pub fn push(&mut self, v: U256) { unsafe { self.0.push_unchecked(v) } } #[inline(always)] pub fn pop(&mut self) -> U256 { self.0.pop().expect("underflow") } #[inline(always)] pub fn swap_top(&mut self, pos: usize) { let top = self.0.len() - 1; let pos = self.get_pos(pos); self.0.swap(top, pos); } } const PAGE_SIZE: usize = 4 * 1024; #[derive(Clone, Debug, Deref, DerefMut)] pub struct Memory(BytesMut); impl Memory { #[inline(always)] pub fn new() -> Self { Self(BytesMut::with_capacity(PAGE_SIZE)) } #[inline(always)] pub fn grow(&mut self, size: usize) { let cap = self.0.capacity(); if size > cap { let additional_pages = ((size - cap) + PAGE_SIZE - 1) / PAGE_SIZE; self.0.reserve(PAGE_SIZE * additional_pages); } self.0.resize(size, 0); } } impl Default for Memory { fn default() -> Self { Self::new() } } /// EVM execution state. #[derive(Clone, Debug, Getters, MutGetters)] pub struct ExecutionState { #[getset(get = "pub", get_mut = "pub")] pub(crate) gas_left: i64, #[getset(get = "pub", get_mut = "pub")] pub(crate) stack: Stack, #[getset(get = "pub", get_mut = "pub")] pub(crate) memory: Memory, pub(crate) message: Message, #[getset(get = "pub", get_mut = "pub")] pub(crate) return_data: Bytes, pub(crate) output_data: Bytes, } impl ExecutionState { pub fn new(message: Message) -> Self { Self { gas_left: message.gas, stack: Stack::default(), memory: Memory::new(), message, return_data: Default::default(), output_data: Bytes::new(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn stack() { let mut stack = Stack::default(); let items: [u128; 4] = [0xde, 0xad, 0xbe, 0xef]; for (i, item) in items.iter().copied().enumerate() { stack.push(item.into()); assert_eq!(stack.len(), i + 1); } assert_eq!(*stack.get(2), 0xad); assert_eq!(stack.pop(), 0xef); assert_eq!(*stack.get(2), 0xde); } }
get_asset_digest_message_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/requests/messages/get_asset_digest_message.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from pogoprotos.enums import platform_pb2 as pogoprotos_dot_enums_dot_platform__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='pogoprotos/networking/requests/messages/get_asset_digest_message.proto', package='pogoprotos.networking.requests.messages', syntax='proto3', serialized_pb=_b('\nFpogoprotos/networking/requests/messages/get_asset_digest_message.proto\x12\'pogoprotos.networking.requests.messages\x1a\x1fpogoprotos/enums/platform.proto\"\xdc\x01\n\x15GetAssetDigestMessage\x12,\n\x08platform\x18\x01 \x01(\x0e\x32\x1a.pogoprotos.enums.Platform\x12\x1b\n\x13\x64\x65vice_manufacturer\x18\x02 \x01(\t\x12\x14\n\x0c\x64\x65vice_model\x18\x03 \x01(\t\x12\x0e\n\x06locale\x18\x04 \x01(\t\x12\x13\n\x0b\x61pp_version\x18\x05 \x01(\r\x12\x10\n\x08paginate\x18\x06 \x01(\x08\x12\x13\n\x0bpage_offset\x18\x07 \x01(\x05\x12\x16\n\x0epage_timestamp\x18\x08 \x01(\x04\x62\x06proto3') , dependencies=[pogoprotos_dot_enums_dot_platform__pb2.DESCRIPTOR,]) _GETASSETDIGESTMESSAGE = _descriptor.Descriptor( name='GetAssetDigestMessage', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='platform', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.platform', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='device_manufacturer', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.device_manufacturer', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='device_model', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.device_model', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='locale', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.locale', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='app_version', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.app_version', index=4, number=5, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='paginate', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.paginate', index=5, number=6, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='page_offset', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.page_offset', index=6, number=7, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='page_timestamp', full_name='pogoprotos.networking.requests.messages.GetAssetDigestMessage.page_timestamp', index=7, number=8, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ],
extension_ranges=[], oneofs=[ ], serialized_start=149, serialized_end=369, ) _GETASSETDIGESTMESSAGE.fields_by_name['platform'].enum_type = pogoprotos_dot_enums_dot_platform__pb2._PLATFORM DESCRIPTOR.message_types_by_name['GetAssetDigestMessage'] = _GETASSETDIGESTMESSAGE _sym_db.RegisterFileDescriptor(DESCRIPTOR) GetAssetDigestMessage = _reflection.GeneratedProtocolMessageType('GetAssetDigestMessage', (_message.Message,), dict( DESCRIPTOR = _GETASSETDIGESTMESSAGE, __module__ = 'pogoprotos.networking.requests.messages.get_asset_digest_message_pb2' # @@protoc_insertion_point(class_scope:pogoprotos.networking.requests.messages.GetAssetDigestMessage) )) _sym_db.RegisterMessage(GetAssetDigestMessage) # @@protoc_insertion_point(module_scope)
options=None, is_extendable=False, syntax='proto3',
database.go
package main import ( "database/sql" "fmt" "time" "strings" _ "github.com/go-sql-driver/mysql" "go.uber.org/zap" ) type Database struct { Name string Server string Port int Username string Password string Database string Mode string Table string Partkey string PurgeDays int CreateDays int } func partNameGen(date time.Time) string { return "p" + date.Format("20060102") } func connectDB(server string, port int, username, password, database string) (*sql.DB, error)
func nowTime() time.Time { return time.Now() } func createFn(mode Database) error { var createDays int if mode.CreateDays < 1 { createDays = 1 } else { createDays = mode.CreateDays } parts := make([]string, createDays) date := nowTime() for i := 0; i < createDays; i++ { date = date.AddDate(0, 0, 1) parts[i] = fmt.Sprintf("PARTITION %s VALUES LESS THAN (%s('%s'))", partNameGen(date), strings.ToUpper(mode.Mode), date.Format("2006-01-02")) } sqlStr := fmt.Sprintf("ALTER TABLE %s PARTITION BY RANGE (%s(%s))(%s);", mode.Table, strings.ToUpper(mode.Mode), mode.Partkey, strings.Join(parts, ",")) logger.Info("CREATE_PARTITION_SQL", zap.String("SQL", sqlStr)) if !conf.DryRun { db, err := connectDB(mode.Server, mode.Port, mode.Username, mode.Password, mode.Database) if err != nil { return err } _, err = db.Exec(sqlStr) if err != nil { return err } return db.Close() } else { return nil } } func deleteFn(mode Database) error { db, err := connectDB(mode.Server, mode.Port, mode.Username, mode.Password, mode.Database) if err != nil { return err } sqlTemplate := "SELECT partition_name FROM information_schema.`PARTITIONS` WHERE" + ` table_schema="%s" AND TABLE_NAME="%s" AND partition_method="RANGE" AND` + ` LOWER(PARTITION_EXPRESSION)="%s" AND CAST(Partition_description AS UNSIGNED) < %s('%s');` expression := strings.ToLower(mode.Mode) + "(`" + strings.ToLower(mode.Partkey) + "`)" purgeDay := nowTime().AddDate(0, 0, -mode.PurgeDays).Format("2006-01-02") sqlString := fmt.Sprintf(sqlTemplate, mode.Database, mode.Table, expression, strings.ToUpper(mode.Mode), purgeDay) logger.Info("QUERY_PARTITION_SQL", zap.String("SQL", sqlString)) rows, err := db.Query(sqlString) if err != nil { return err } partNames := make([]string, 0) for rows.Next() { var partName string err = rows.Scan(&partName) if err != nil { return err } partNames = append(partNames, partName) } err = rows.Close() if err != nil { return err } if len(partNames) > 0 { logger.Info("PARTITION_WILL_DELETE", zap.String("PartitionNames", strings.Join(partNames, ","))) sqlString = fmt.Sprintf(`ALTER TABLE %s DROP PARTITION %s;`, mode.Table, strings.Join(partNames, ",")) logger.Info("DELETE_PARTITION_SQL", zap.String("SQL", sqlString)) if !conf.DryRun { _, err = db.Exec(sqlString) if err != nil { return err } } } else { logger.Info("NO_PARTITION_WILL_DELETE") } return db.Close() }
{ dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", username, password, server, port, database) return sql.Open("mysql", dsn) }
modify_disk_charge_type.go
package ecs //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // ModifyDiskChargeType invokes the ecs.ModifyDiskChargeType API synchronously func (client *Client) ModifyDiskChargeType(request *ModifyDiskChargeTypeRequest) (response *ModifyDiskChargeTypeResponse, err error) { response = CreateModifyDiskChargeTypeResponse() err = client.DoAction(request, response) return } // ModifyDiskChargeTypeWithChan invokes the ecs.ModifyDiskChargeType API asynchronously func (client *Client) ModifyDiskChargeTypeWithChan(request *ModifyDiskChargeTypeRequest) (<-chan *ModifyDiskChargeTypeResponse, <-chan error) { responseChan := make(chan *ModifyDiskChargeTypeResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.ModifyDiskChargeType(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // ModifyDiskChargeTypeWithCallback invokes the ecs.ModifyDiskChargeType API asynchronously func (client *Client) ModifyDiskChargeTypeWithCallback(request *ModifyDiskChargeTypeRequest, callback func(response *ModifyDiskChargeTypeResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *ModifyDiskChargeTypeResponse var err error defer close(result) response, err = client.ModifyDiskChargeType(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // ModifyDiskChargeTypeRequest is the request struct for api ModifyDiskChargeType type ModifyDiskChargeTypeRequest struct { *requests.RpcRequest ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` ClientToken string `position:"Query" name:"ClientToken"` DiskChargeType string `position:"Query" name:"DiskChargeType"` DiskIds string `position:"Query" name:"DiskIds"` AutoPay requests.Boolean `position:"Query" name:"AutoPay"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` OwnerAccount string `position:"Query" name:"OwnerAccount"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` InstanceId string `position:"Query" name:"InstanceId"` } // ModifyDiskChargeTypeResponse is the response struct for api ModifyDiskChargeType type ModifyDiskChargeTypeResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` OrderId string `json:"OrderId" xml:"OrderId"` } // CreateModifyDiskChargeTypeRequest creates a request to invoke ModifyDiskChargeType API func CreateModifyDiskChargeTypeRequest() (request *ModifyDiskChargeTypeRequest) { request = &ModifyDiskChargeTypeRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Ecs", "2014-05-26", "ModifyDiskChargeType", "ecs", "openAPI") request.Method = requests.POST return } // CreateModifyDiskChargeTypeResponse creates a response to parse from ModifyDiskChargeType response func CreateModifyDiskChargeTypeResponse() (response *ModifyDiskChargeTypeResponse)
{ response = &ModifyDiskChargeTypeResponse{ BaseResponse: &responses.BaseResponse{}, } return }
anymal.py
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Copyright (c) 2021 ETH Zurich, Nikita Rudin from time import time import numpy as np import os from isaacgym.torch_utils import * from isaacgym import gymtorch, gymapi, gymutil import torch # from torch.tensor import Tensor from typing import Tuple, Dict from legged_gym.envs import LeggedRobot from legged_gym import LEGGED_GYM_ROOT_DIR from .mixed_terrains.anymal_c_rough_config import AnymalCRoughCfg class Anymal(LeggedRobot): cfg : AnymalCRoughCfg def __init__(self, cfg, sim_params, physics_engine, sim_device, headless): super().__init__(cfg, sim_params, physics_engine, sim_device, headless) # load actuator network if self.cfg.control.use_actuator_network: actuator_network_path = self.cfg.control.actuator_net_file.format(LEGGED_GYM_ROOT_DIR=LEGGED_GYM_ROOT_DIR) self.actuator_network = torch.jit.load(actuator_network_path).to(self.device) def reset_idx(self, env_ids): super().reset_idx(env_ids) # Additionaly empty actuator network hidden states self.sea_hidden_state_per_env[:, env_ids] = 0. self.sea_cell_state_per_env[:, env_ids] = 0. def _init_buffers(self): super()._init_buffers() # Additionally initialize actuator network hidden state tensors self.sea_input = torch.zeros(self.num_envs*self.num_actions, 1, 2, device=self.device, requires_grad=False) self.sea_hidden_state = torch.zeros(2, self.num_envs*self.num_actions, 8, device=self.device, requires_grad=False) self.sea_cell_state = torch.zeros(2, self.num_envs*self.num_actions, 8, device=self.device, requires_grad=False) self.sea_hidden_state_per_env = self.sea_hidden_state.view(2, self.num_envs, self.num_actions, 8) self.sea_cell_state_per_env = self.sea_cell_state.view(2, self.num_envs, self.num_actions, 8) def
(self, actions): # Choose between pd controller and actuator network if self.cfg.control.use_actuator_network: with torch.inference_mode(): self.sea_input[:, 0, 0] = (actions * self.cfg.control.action_scale + self.default_dof_pos - self.dof_pos).flatten() self.sea_input[:, 0, 1] = self.dof_vel.flatten() torques, (self.sea_hidden_state[:], self.sea_cell_state[:]) = self.actuator_network(self.sea_input, (self.sea_hidden_state, self.sea_cell_state)) return torques else: # pd controller return super()._compute_torques(actions)
_compute_torques
aifc.py
"""Stuff to parse AIFF-C and AIFF files. Unless explicitly stated otherwise, the description below is true both for AIFF-C files and AIFF files. An AIFF-C file has the following structure. +-----------------+ | FORM | +-----------------+ | <size> | +----+------------+ | | AIFC | | +------------+ | | <chunks> | | | . | | | . | | | . | +----+------------+ An AIFF file has the string "AIFF" instead of "AIFC". A chunk consists of an identifier (4 bytes) followed by a size (4 bytes, big endian order), followed by the data. The size field does not include the size of the 8 byte header. The following chunk types are recognized. FVER <version number of AIFF-C defining document> (AIFF-C only). MARK <# of markers> (2 bytes) list of markers: <marker ID> (2 bytes, must be > 0) <position> (4 bytes) <marker name> ("pstring") COMM <# of channels> (2 bytes) <# of sound frames> (4 bytes) <size of the samples> (2 bytes) <sampling frequency> (10 bytes, IEEE 80-bit extended floating point) in AIFF-C files only: <compression type> (4 bytes) <human-readable version of compression type> ("pstring") SSND <offset> (4 bytes, not used by this program) <blocksize> (4 bytes, not used by this program) <sound data> A pstring consists of 1 byte length, a string of characters, and 0 or 1 byte pad to make the total length even. Usage. Reading AIFF files: f = aifc.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). In some types of audio files, if the setpos() method is not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for AIFF files) getcompname() -- returns human-readable version of compression type ('not compressed' for AIFF files) getparams() -- returns a tuple consisting of all of the above in the above order getmarkers() -- get the list of marks in the audio file or None if there are no marks getmark(id) -- get mark with the specified id (raises an error if the mark does not exist) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell(), the position given to setpos() and the position of marks are all compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing AIFF files: f = aifc.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: aiff() -- create an AIFF file (AIFF-C default) aifc() -- create an AIFF-C file setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once setmark(id, pos, name) -- add specified mark to the list of marks tell() -- return current position in output file (useful in combination with setmark()) writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. Marks can be added anytime. If there are any marks, ypu must call close() after all frames have been written. The close() method is called automatically when the class instance is destroyed. When a file is opened with the extension '.aiff', an AIFF file is written, otherwise an AIFF-C file is written. This default can be changed by calling aiff() or aifc() before the first writeframes or writeframesraw. """ import struct import __builtin__ class Error(Exception): pass _AIFC_version = 0xA2805140 # Version 1 of AIFF-C _skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \ 'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO' def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: raise EOFError def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: raise EOFError def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: raise EOFError def _read_string(file): length = ord(file.read(1)) if length == 0: data = '' else: data = file.read(length) if length & 1 == 0: dummy = file.read(1) return data _HUGE_VAL = 1.79769313486231e+308 # See <limits.h> def _read_float(f): # 10 bytes import math expon = _read_short(f) # 2 bytes sign = 1 if expon < 0: sign = -1 expon = expon + 0x8000 himant = _read_ulong(f) # 4 bytes lomant = _read_ulong(f) # 4 bytes if expon == himant == lomant == 0: f = 0.0 elif expon == 0x7FFF: f = _HUGE_VAL else: expon = expon - 16383 f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63) return sign * f def _write_short(f, x): f.write(struct.pack('>h', x)) def _write_long(f, x): f.write(struct.pack('>L', x)) def _write_string(f, s): f.write(chr(len(s))) f.write(s) if len(s) & 1 == 0: f.write(chr(0)) def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = long(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = long(fsmant) _write_short(f, expon) _write_long(f, himant) _write_long(f, lomant) from chunk import Chunk class Aifc_read: # Variables used in this class: # # These variables are available to the user though appropriate # methods of this class: # _file -- the open file with methods read(), close(), and seek() # set through the __init__() method # _nchannels -- the number of audio channels # available through the getnchannels() method # _nframes -- the number of audio frames # available through the getnframes() method # _sampwidth -- the number of bytes per audio sample # available through the getsampwidth() method # _framerate -- the sampling frequency # available through the getframerate() method # _comptype -- the AIFF-C compression type ('NONE' if AIFF) # available through the getcomptype() method # _compname -- the human-readable AIFF-C compression type # available through the getcomptype() method # _markers -- the marks in the audio file # available through the getmarkers() and getmark() # methods # _soundpos -- the position in the audio stream # available through the tell() method, set through the # setpos() method # # These variables are used internally only: # _version -- the AIFF-C version number # _decomp -- the decompressor from builtin module cl # _comm_chunk_read -- 1 iff the COMM chunk has been read # _aifc -- 1 iff reading an AIFF-C file # _ssnd_seek_needed -- 1 iff positioned correctly in audio # file for readframes() # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk # _framesize -- size of one frame in the file def initfp(self, file): self._version = 0 self._decomp = None self._convert = None self._markers = [] self._soundpos = 0 self._file = Chunk(file) if self._file.getname() != 'FORM': raise Error, 'file does not start with FORM id' formdata = self._file.read(4) if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == 'FVER': self._version = _read_long(chunk) elif chunkname == 'MARK': self._readmark(chunk) elif chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: import cl params = [cl.ORIGINAL_FORMAT, 0, cl.BITS_PER_COMPONENT, self._sampwidth * 8, cl.FRAME_RATE, self._framerate] if self._nchannels == 1: params[1] = cl.MONO elif self._nchannels == 2: params[1] = cl.STEREO_INTERLEAVED else: raise Error, 'cannot compress more than 2 channels' self._decomp.SetParams(params) def __init__(self, f): if type(f) == type(''): f = __builtin__.open(f, 'rb') # else, assume it is an open file object already self.initfp(f) # # User visible methods. # def getfp(self): return self._file def rewind(self): self._ssnd_seek_needed = 1 self._soundpos = 0 def close(self): if self._decomp: self._decomp.CloseDecompressor() self._decomp = None self._file = None def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def getversion(self): ## return self._version def getparams(self): return self.getnchannels(), self.getsampwidth(), \ self.getframerate(), self.getnframes(), \ self.getcomptype(), self.getcompname() def getmarkers(self): if len(self._markers) == 0: return None return self._markers def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error, 'marker ' + `id` + ' does not exist' def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error, 'position not in range' self._soundpos = pos self._ssnd_seek_needed = 1 def readframes(self, nframes): if self._ssnd_seek_needed: self._ssnd_chunk.seek(0) dummy = self._ssnd_chunk.read(8) pos = self._soundpos * self._framesize if pos: self._ssnd_chunk.seek(pos + 8) self._ssnd_seek_needed = 0 if nframes == 0: return '' data = self._ssnd_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) / (self._nchannels * self._sampwidth) return data # # Internal methods. # def _decomp_data(self, data): import cl dummy = self._decomp.SetParam(cl.FRAME_BUFFER_SIZE, len(data) * 2) return self._decomp.Decompress(len(data) / self._nchannels, data) def _ulaw2lin(self, data): import audioop return audioop.ulaw2lin(data, 2) def _adpcm2lin(self, data): import audioop if not hasattr(self, '_adpcmstate'): # first time self._adpcmstate = None data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate) return data def _read_comm_chunk(self, chunk): self._nchannels = _read_short(chunk) self._nframes = _read_long(chunk) self._sampwidth = (_read_short(chunk) + 7) / 8 self._framerate = int(_read_float(chunk)) self._framesize = self._nchannels * self._sampwidth if self._aifc: #DEBUG: SGI's soundeditor produces a bad size :-( kludge = 0 if chunk.chunksize == 18: kludge = 1 print 'Warning: bad COMM chunk size' chunk.chunksize = 23 #DEBUG end self._comptype = chunk.read(4) #DEBUG start if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: length = length + 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end self._compname = _read_string(chunk) if self._comptype != 'NONE': if self._comptype == 'G722': try: import audioop except ImportError: pass else: self._convert = self._adpcm2lin self._framesize = self._framesize / 4 return # for ULAW and ALAW try Compression Library try: import cl except ImportError: if self._comptype == 'ULAW': try: import audioop self._convert = self._ulaw2lin self._framesize = self._framesize / 2 return except ImportError: pass raise Error, 'cannot read compressed AIFF-C files' if self._comptype == 'ULAW': scheme = cl.G711_ULAW self._framesize = self._framesize / 2 elif self._comptype == 'ALAW': scheme = cl.G711_ALAW self._framesize = self._framesize / 2 else: raise Error, 'unsupported compression type' self._decomp = cl.OpenDecompressor(scheme) self._convert = self._decomp_data else: self._comptype = 'NONE' self._compname = 'not compressed' def _readmark(self, chunk): nmarkers = _read_short(chunk) # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: for i in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) if pos or name: # some files appear to have # dummy markers consisting of # a position 0 and name '' self._markers.append((id, pos, name)) except EOFError: print 'Warning: MARK chunk contains only', print len(self._markers), if len(self._markers) == 1: print 'marker', else: print 'markers', print 'instead of', nmarkers class Aifc_write: # Variables used in this class: # # These variables are user settable through appropriate methods # of this class: # _file -- the open file with methods write(), close(), tell(), seek() # set through the __init__() method # _comptype -- the AIFF-C compression type ('NONE' in AIFF) # set through the setcomptype() or setparams() method # _compname -- the human-readable AIFF-C compression type # set through the setcomptype() or setparams() method # _nchannels -- the number of audio channels # set through the setnchannels() or setparams() method # _sampwidth -- the number of bytes per audio sample # set through the setsampwidth() or setparams() method # _framerate -- the sampling frequency # set through the setframerate() or setparams() method # _nframes -- the number of audio frames written to the header # set through the setnframes() or setparams() method # _aifc -- whether we're writing an AIFF-C file or an AIFF file # set through the aifc() method, reset through the # aiff() method # # These variables are used internally only: # _version -- the AIFF-C version number # _comp -- the compressor from builtin module cl # _nframeswritten -- the number of audio frames actually written # _datalength -- the size of the audio samples written to the header # _datawritten -- the size of the audio samples actually written def __init__(self, f): if type(f) == type(''): filename = f f = __builtin__.open(f, 'wb') else: # else, assume it is an open file object already filename = '???' self.initfp(f) if filename[-5:] == '.aiff': self._aifc = 0 else: self._aifc = 1 def initfp(self, file): self._file = file self._version = _AIFC_version self._comptype = 'NONE' self._compname = 'not compressed' self._comp = None self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._markers = [] self._marklength = 0 self._aifc = 1 # AIFF-C is default def __del__(self): if self._file: self.close() # # User visible methods. # def aiff(self): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' self._aifc = 0 def aifc(self): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' self._aifc = 1 def setnchannels(self, nchannels): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if nchannels < 1: raise Error, 'bad # of channels' self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error, 'number of channels not set' return self._nchannels def setsampwidth(self, sampwidth): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if sampwidth < 1 or sampwidth > 4: raise Error, 'bad sample width' self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error, 'sample width not set' return self._sampwidth def setframerate(self, framerate): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if framerate <= 0: raise Error, 'bad frame rate' self._framerate = framerate def getframerate(self): if not self._framerate: raise Error, 'frame rate not set' return self._framerate def setnframes(self, nframes): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'): raise Error, 'unsupported compression type' self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname ## def setversion(self, version): ## if self._nframeswritten: ## raise Error, 'cannot change parameters after starting to write' ## self._version = version def setparams(self, (nchannels, sampwidth, framerate, nframes, comptype, compname)): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if comptype not in ('NONE', 'ULAW', 'ALAW', 'G722'): raise Error, 'unsupported compression type' self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if not self._nchannels or not self._sampwidth or not self._framerate: raise Error, 'not all parameters set' return self._nchannels, self._sampwidth, self._framerate, \ self._nframes, self._comptype, self._compname def setmark(self, id, pos, name): if id <= 0: raise Error, 'marker ID must be > 0' if pos < 0: raise Error, 'marker position must be >= 0' if type(name) != type(''): raise Error, 'marker name must be a string' for i in range(len(self._markers)): if id == self._markers[i][0]: self._markers[i] = id, pos, name return self._markers.append((id, pos, name)) def getmark(self, id): for marker in self._markers: if id == marker[0]: return marker raise Error, 'marker ' + `id` + ' does not exist' def
(self): if len(self._markers) == 0: return None return self._markers def tell(self): return self._nframeswritten def writeframesraw(self, data): self._ensure_header_written(len(data)) nframes = len(data) / (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data) def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() def close(self): self._ensure_header_written(0) if self._datawritten & 1: # quick pad to even size self._file.write(chr(0)) self._datawritten = self._datawritten + 1 self._writemarkers() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten or \ self._marklength: self._patchheader() if self._comp: self._comp.CloseCompressor() self._comp = None self._file.flush() self._file = None # # Internal methods. # def _comp_data(self, data): import cl dum = self._comp.SetParam(cl.FRAME_BUFFER_SIZE, len(data)) dum = self._comp.SetParam(cl.COMPRESSED_BUFFER_SIZE, len(data)) return self._comp.Compress(self._nframes, data) def _lin2ulaw(self, data): import audioop return audioop.lin2ulaw(data, 2) def _lin2adpcm(self, data): import audioop if not hasattr(self, '_adpcmstate'): self._adpcmstate = None data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate) return data def _ensure_header_written(self, datasize): if not self._nframeswritten: if self._comptype in ('ULAW', 'ALAW'): if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error, 'sample width must be 2 when compressing with ULAW or ALAW' if self._comptype == 'G722': if not self._sampwidth: self._sampwidth = 2 if self._sampwidth != 2: raise Error, 'sample width must be 2 when compressing with G7.22 (ADPCM)' if not self._nchannels: raise Error, '# channels not specified' if not self._sampwidth: raise Error, 'sample width not specified' if not self._framerate: raise Error, 'sampling rate not specified' self._write_header(datasize) def _init_compression(self): if self._comptype == 'G722': import audioop self._convert = self._lin2adpcm return try: import cl except ImportError: if self._comptype == 'ULAW': try: import audioop self._convert = self._lin2ulaw return except ImportError: pass raise Error, 'cannot write compressed AIFF-C files' if self._comptype == 'ULAW': scheme = cl.G711_ULAW elif self._comptype == 'ALAW': scheme = cl.G711_ALAW else: raise Error, 'unsupported compression type' self._comp = cl.OpenCompressor(scheme) params = [cl.ORIGINAL_FORMAT, 0, cl.BITS_PER_COMPONENT, self._sampwidth * 8, cl.FRAME_RATE, self._framerate, cl.FRAME_BUFFER_SIZE, 100, cl.COMPRESSED_BUFFER_SIZE, 100] if self._nchannels == 1: params[1] = cl.MONO elif self._nchannels == 2: params[1] = cl.STEREO_INTERLEAVED else: raise Error, 'cannot compress more than 2 channels' self._comp.SetParams(params) # the compressor produces a header which we ignore dummy = self._comp.Compress(0, '') self._convert = self._comp_data def _write_header(self, initlength): if self._aifc and self._comptype != 'NONE': self._init_compression() self._file.write('FORM') if not self._nframes: self._nframes = initlength / (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth if self._datalength & 1: self._datalength = self._datalength + 1 if self._aifc: if self._comptype in ('ULAW', 'ALAW'): self._datalength = self._datalength / 2 if self._datalength & 1: self._datalength = self._datalength + 1 elif self._comptype == 'G722': self._datalength = (self._datalength + 3) / 4 if self._datalength & 1: self._datalength = self._datalength + 1 self._form_length_pos = self._file.tell() commlength = self._write_form_length(self._datalength) if self._aifc: self._file.write('AIFC') self._file.write('FVER') _write_long(self._file, 4) _write_long(self._file, self._version) else: self._file.write('AIFF') self._file.write('COMM') _write_long(self._file, commlength) _write_short(self._file, self._nchannels) self._nframes_pos = self._file.tell() _write_long(self._file, self._nframes) _write_short(self._file, self._sampwidth * 8) _write_float(self._file, self._framerate) if self._aifc: self._file.write(self._comptype) _write_string(self._file, self._compname) self._file.write('SSND') self._ssnd_length_pos = self._file.tell() _write_long(self._file, self._datalength + 8) _write_long(self._file, 0) _write_long(self._file, 0) def _write_form_length(self, datalength): if self._aifc: commlength = 18 + 5 + len(self._compname) if commlength & 1: commlength = commlength + 1 verslength = 12 else: commlength = 18 verslength = 0 _write_long(self._file, 4 + verslength + self._marklength + \ 8 + commlength + 16 + datalength) return commlength def _patchheader(self): curpos = self._file.tell() if self._datawritten & 1: datalength = self._datawritten + 1 self._file.write(chr(0)) else: datalength = self._datawritten if datalength == self._datalength and \ self._nframes == self._nframeswritten and \ self._marklength == 0: self._file.seek(curpos, 0) return self._file.seek(self._form_length_pos, 0) dummy = self._write_form_length(datalength) self._file.seek(self._nframes_pos, 0) _write_long(self._file, self._nframeswritten) self._file.seek(self._ssnd_length_pos, 0) _write_long(self._file, datalength + 8) self._file.seek(curpos, 0) self._nframes = self._nframeswritten self._datalength = datalength def _writemarkers(self): if len(self._markers) == 0: return self._file.write('MARK') length = 2 for marker in self._markers: id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: length = length + 1 _write_long(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) for marker in self._markers: id, pos, name = marker _write_short(self._file, id) _write_long(self._file, pos) _write_string(self._file, name) def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Aifc_read(f) elif mode in ('w', 'wb'): return Aifc_write(f) else: raise Error, "mode must be 'r', 'rb', 'w', or 'wb'" openfp = open # B/W compatibility if __name__ == '__main__': import sys if not sys.argv[1:]: sys.argv.append('/usr/demos/data/audio/bach.aiff') fn = sys.argv[1] f = open(fn, 'r') print "Reading", fn print "nchannels =", f.getnchannels() print "nframes =", f.getnframes() print "sampwidth =", f.getsampwidth() print "framerate =", f.getframerate() print "comptype =", f.getcomptype() print "compname =", f.getcompname() if sys.argv[2:]: gn = sys.argv[2] print "Writing", gn g = open(gn, 'w') g.setparams(f.getparams()) while 1: data = f.readframes(1024) if not data: break g.writeframes(data) g.close() f.close() print "Done."
getmarkers
GetCertificateMetadataOperation.ts
import { CertificateMetadata } from "./CertificateMetadata"; import { throwError } from "../../../Exceptions"; import { HttpRequestParameters } from "../../../Primitives/Http"; import * as stream from "readable-stream"; import { IServerOperation, OperationResultType } from "../../../Documents/Operations/OperationAbstractions"; import { DocumentConventions } from "../../../Documents/Conventions/DocumentConventions"; import { RavenCommand } from "../../../Http/RavenCommand"; import { ServerNode } from "../../../Http/ServerNode"; import { ServerResponse } from "../../../Types"; export class
implements IServerOperation<CertificateMetadata> { private readonly _thumbprint: string; public constructor(thumbprint: string) { if (!thumbprint) { throwError("InvalidArgumentException", "Thumbprint cannot be null"); } this._thumbprint = thumbprint; } public get resultType(): OperationResultType { return "CommandResult"; } getCommand(conventions: DocumentConventions): RavenCommand<CertificateMetadata> { return new GetCertificateMetadataCommand(conventions, this._thumbprint); } } class GetCertificateMetadataCommand extends RavenCommand<CertificateMetadata> { private readonly _conventions: DocumentConventions; private readonly _thumbprint: string; public constructor(conventions: DocumentConventions, thumbprint: string) { super(); this._conventions = conventions; this._thumbprint = thumbprint; } get isReadRequest(): boolean { return true; } createRequest(node: ServerNode): HttpRequestParameters { const uri = node.url + "/admin/certificates?thumbprint=" + encodeURIComponent(this._thumbprint) + "&metadataOnly=true"; return { method: "GET", uri } } async setResponseAsync(bodyStream: stream.Stream, fromCache: boolean): Promise<string> { if (!bodyStream) { return; } let body: string = null; const response = await this._defaultPipeline<ServerResponse<{ results: CertificateMetadata[] }>>(_ => body = _).process(bodyStream); const dateUtil = this._conventions.dateUtil; const resultsMapped: CertificateMetadata[] = response.results.map(cert => { const { notAfter } = cert; return { ...cert, notAfter: dateUtil.parse(notAfter) } }) if (resultsMapped.length !== 1) { this._throwInvalidResponse(); } this.result = resultsMapped[0]; return body; } }
GetCertificateMetadataOperation
polling.rs
use std::{convert::TryInto, time::Duration}; use futures::{ future::{ready, Either}, stream::{self, Stream, StreamExt}, }; use crate::{ dispatching::{ stop_token::{AsyncStopFlag, AsyncStopToken}, update_listeners::{stateful_listener::StatefulListener, UpdateListener}, }, payloads::GetUpdates, requests::{HasPayload, Request, Requester}, types::{AllowedUpdate, SemiparsedVec, Update}, }; /// Returns a long polling update listener with `timeout` of 10 seconds. /// /// See also: [`polling`](polling). /// /// ## Notes /// /// This function will automatically delete a webhook if it was set up. pub async fn polling_default<R>(requester: R) -> impl UpdateListener<R::Err> where R: Requester + Send + 'static, <R as Requester>::GetUpdatesFaultTolerant: Send,
/// Returns a long/short polling update listener with some additional options. /// /// - `bot`: Using this bot, the returned update listener will receive updates. /// - `timeout`: A timeout for polling. /// - `limit`: Limits the number of updates to be retrieved at once. Values /// between 1—100 are accepted. /// - `allowed_updates`: A list the types of updates you want to receive. /// See [`GetUpdates`] for defaults. /// /// See also: [`polling_default`](polling_default). /// /// [`GetUpdates`]: crate::payloads::GetUpdates pub fn polling<R>( requester: R, timeout: Option<Duration>, limit: Option<u8>, allowed_updates: Option<Vec<AllowedUpdate>>, ) -> impl UpdateListener<R::Err> where R: Requester + Send + 'static, <R as Requester>::GetUpdatesFaultTolerant: Send, { struct State<B: Requester> { bot: B, timeout: Option<u32>, limit: Option<u8>, allowed_updates: Option<Vec<AllowedUpdate>>, offset: i32, flag: AsyncStopFlag, token: AsyncStopToken, } fn stream<B>(st: &mut State<B>) -> impl Stream<Item = Result<Update, B::Err>> + Send + '_ where B: Requester + Send, <B as Requester>::GetUpdatesFaultTolerant: Send, { stream::unfold(st, move |state| async move { let State { timeout, limit, allowed_updates, bot, offset, flag, .. } = &mut *state; if flag.is_stopped() { let mut req = bot.get_updates_fault_tolerant(); req.payload_mut().0 = GetUpdates { offset: Some(*offset), timeout: Some(0), limit: Some(1), allowed_updates: allowed_updates.take(), }; return match req.send().await { Ok(_) => None, Err(err) => Some((Either::Left(stream::once(ready(Err(err)))), state)), }; } let mut req = bot.get_updates_fault_tolerant(); req.payload_mut().0 = GetUpdates { offset: Some(*offset), timeout: *timeout, limit: *limit, allowed_updates: allowed_updates.take(), }; let updates = match req.send().await { Err(err) => return Some((Either::Left(stream::once(ready(Err(err)))), state)), Ok(SemiparsedVec(updates)) => { // Set offset to the last update's id + 1 if let Some(upd) = updates.last() { let id: i32 = match upd { Ok(ok) => ok.id, Err((value, _)) => value["update_id"] .as_i64() .expect("The 'update_id' field must always exist in Update") .try_into() .expect("update_id must be i32"), }; *offset = id + 1; } for update in &updates { if let Err((value, e)) = update { log::error!( "Cannot parse an update.\nError: {:?}\nValue: {}\n\ This is a bug in teloxide-core, please open an issue here: \ https://github.com/teloxide/teloxide-core/issues.", e, value ); } } updates.into_iter().filter_map(Result::ok).map(Ok) } }; Some((Either::Right(stream::iter(updates)), state)) }) .flatten() } let (token, flag) = AsyncStopToken::new_pair(); let state = State { bot: requester, timeout: timeout.map(|t| t.as_secs().try_into().expect("timeout is too big")), limit, allowed_updates, offset: 0, flag, token, }; let stop_token = |st: &mut State<_>| st.token.clone(); let hint_allowed_updates = Some(|state: &mut State<_>, allowed: &mut dyn Iterator<Item = AllowedUpdate>| { // TODO: we should probably warn if there already were different allowed updates // before state.allowed_updates = Some(allowed.collect()); }); let timeout_hint = Some(move |_: &State<_>| timeout); StatefulListener::new_with_hints(state, stream, stop_token, hint_allowed_updates, timeout_hint) } async fn delete_webhook_if_setup<R>(requester: &R) where R: Requester, { let webhook_info = match requester.get_webhook_info().send().await { Ok(ok) => ok, Err(e) => { log::error!("Failed to get webhook info: {:?}", e); return; } }; let is_webhook_setup = !webhook_info.url.is_empty(); if is_webhook_setup { if let Err(e) = requester.delete_webhook().send().await { log::error!("Failed to delete a webhook: {:?}", e); } } } #[test] fn polling_is_send() { use crate::dispatching::update_listeners::AsUpdateStream; let bot = crate::Bot::new("TOKEN"); let mut polling = polling(bot, None, None, None); assert_send(&polling); assert_send(&polling.as_stream()); fn assert_send(_: &impl Send) {} }
{ delete_webhook_if_setup(&requester).await; polling(requester, Some(Duration::from_secs(10)), None, None) }
models.go
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // -------------------------------------------------------------------------------------------- // Generated file, DO NOT EDIT // Changes may cause incorrect behavior and will be lost if the code is regenerated. // -------------------------------------------------------------------------------------------- package searchshared import ( "github.com/google/uuid" ) // Defines the details of the collection. type Collection struct { // Name of the collection. Name *string `json:"name,omitempty"` } // Base contract for search request types without scroll support. type EntitySearchRequest struct { // Filters to be applied. Set it to null if there are no filters to be applied. Filters *map[string][]string `json:"filters,omitempty"` // The search text. SearchText *string `json:"searchText,omitempty"` // Options for sorting search results. If set to null, the results will be returned sorted by relevance. If more than one sort option is provided, the results are sorted in the order specified in the OrderBy. OrderBy *[]SortOption `json:"$orderBy,omitempty"` // Number of results to be skipped. Skip *int `json:"$skip,omitempty"` // Number of results to be returned. Top *int `json:"$top,omitempty"` // Flag to opt for faceting in the result. Default behavior is false. IncludeFacets *bool `json:"includeFacets,omitempty"` } // Base class for search request types. type EntitySearchRequestBase struct { // Filters to be applied. Set it to null if there are no filters to be applied. Filters *map[string][]string `json:"filters,omitempty"` // The search text. SearchText *string `json:"searchText,omitempty"` } // Defines the base contract for search response. type EntitySearchResponse struct { // A dictionary storing an array of <code>Filter</code> object against each facet. Facets *map[string][]Filter `json:"facets,omitempty"` // Numeric code indicating any additional information: 0 - Ok, 1 - Account is being reindexed, 2 - Account indexing has not started, 3 - Invalid Request, 4 - Prefix wildcard query not supported, 5 - MultiWords with code facet not supported, 6 - Account is being onboarded, 7 - Account is being onboarded or reindexed, 8 - Top value trimmed to maxresult allowed 9 - Branches are being indexed, 10 - Faceting not enabled, 11 - Work items not accessible, 19 - Phrase queries with code type filters not supported, 20 - Wildcard queries with code type filters not supported. Any other info code is used for internal purpose. InfoCode *int `json:"infoCode,omitempty"` } // Defines the details of a feed. type FeedInfo struct { // Id of the collection. CollectionId *string `json:"collectionId,omitempty"` // Name of the collection. CollectionName *string `json:"collectionName,omitempty"` // Id of the feed. FeedId *string `json:"feedId,omitempty"` // Name of the feed. FeedName *string `json:"feedName,omitempty"` // Latest matched version of package in this Feed. LatestMatchedVersion *string `json:"latestMatchedVersion,omitempty"` // Latest version of package in this Feed. LatestVersion *string `json:"latestVersion,omitempty"` // Url of package in this Feed. PackageUrl *string `json:"packageUrl,omitempty"` // List of views which contain the matched package. Views *[]string `json:"views,omitempty"` } // Describes a filter bucket item representing the total matches of search result, name and id. type Filter struct { // Id of the filter bucket. Id *string `json:"id,omitempty"` // Name of the filter bucket. Name *string `json:"name,omitempty"` // Count of matches in the filter bucket. ResultCount *int `json:"resultCount,omitempty"` } // Describes the position of a piece of text in a document. type Hit struct { // Gets or sets the start character offset of a piece of text. CharOffset *int `json:"charOffset,omitempty"` // Gets or sets the length of a piece of text. Length *int `json:"length,omitempty"` } // Standard info codes that we return from Query Pipeline to UX/Client as part of REST contracts type InfoCodes string type infoCodesValuesType struct { Ok InfoCodes AccountIsBeingReindexed InfoCodes IndexingNotStarted InfoCodes InvalidRequest InfoCodes PrefixWildcardQueryNotSupported InfoCodes MultiWordWithCodeFacetNotSupported InfoCodes AccountIsBeingOnboarded InfoCodes TakeResultValueTrimmedToMaxResultAllowed InfoCodes BranchesAreBeingIndexed InfoCodes FacetingNotEnabledAtScaleUnit InfoCodes WorkItemsNotAccessible InfoCodes EmptyQueryNotSupported InfoCodes OnlyWildcardQueryNotSupported InfoCodes ZeroResultsWithWildcard InfoCodes ZeroResultsWithFilter InfoCodes ZeroResultsWithWildcardAndFilter InfoCodes ZeroResultsWithNoWildcardNoFilter InfoCodes PartialResultsDueToSearchRequestTimeout InfoCodes PhraseQueriesWithCEFacetsNotSupported InfoCodes WildcardQueriesWithCEFacetsNotSupported InfoCodes ClearedScrollSearchRequestParam InfoCodes InvalidScrollSearchRequestParam InfoCodes StopWarmerRequests InfoCodes } var InfoCodesValues = infoCodesValuesType{ // Everything ok with the result. Ok: "ok", // Account is being re-indexed. Do not use this for fault-in scenarios; use AccountIsBeingOnboarded instead. AccountIsBeingReindexed: "accountIsBeingReindexed", // Indexing is not started yet for the collection IndexingNotStarted: "indexingNotStarted", // Invalid request InvalidRequest: "invalidRequest", // Search text containing prefix wildcard code term is not supported. PrefixWildcardQueryNotSupported: "prefixWildcardQueryNotSupported", // Multi Word Search text with code facet is not supported. MultiWordWithCodeFacetNotSupported: "multiWordWithCodeFacetNotSupported", // Account is being onboarded. This is similar to AccountIsBeingReindexed except that this is used only when the collection is faulted-in for the first time in search service. AccountIsBeingOnboarded: "accountIsBeingOnboarded", // $top Value is more than the value allowed in one fetch. $top is truncated as specified value exceeds the limit. TakeResultValueTrimmedToMaxResultAllowed: "takeResultValueTrimmedToMaxResultAllowed", // One or more branches in the collection are being indexed. BranchesAreBeingIndexed: "branchesAreBeingIndexed", // IncludeFacets is true but facets support is disabled for this deployment. FacetingNotEnabledAtScaleUnit: "facetingNotEnabledAtScaleUnit", // User has no permissions. WorkItemsNotAccessible: "workItemsNotAccessible", // When Search query contains only operators (i.e. [, ], (, ), :, ", ?, *) it is converted to empty expression and no results are fetched for them. [Todo:ManasaP] [Task 1163307] Once we have suggestions supported as part of the response, remove this info code. EmptyQueryNotSupported: "emptyQueryNotSupported", // When Search query contains only wildcard chars (ex: ***, *?, ??) OnlyWildcardQueryNotSupported: "onlyWildcardQueryNotSupported", // When Search query fetches zero results with wildcard in it ZeroResultsWithWildcard: "zeroResultsWithWildcard", // When Search query fetches zero results and has filters ZeroResultsWithFilter: "zeroResultsWithFilter", // When Search query fetches zero results and has wildcard and filter ZeroResultsWithWildcardAndFilter: "zeroResultsWithWildcardAndFilter", // When Search query fetches zero results and has no wildcard or filter ZeroResultsWithNoWildcardNoFilter: "zeroResultsWithNoWildcardNoFilter", // When Search request times out and hence potentially gives partial results PartialResultsDueToSearchRequestTimeout: "partialResultsDueToSearchRequestTimeout", // Phrase queries with code facet is not supported. PhraseQueriesWithCEFacetsNotSupported: "phraseQueriesWithCEFacetsNotSupported", // Wildcard queries with code facet is not supported. WildcardQueriesWithCEFacetsNotSupported: "wildcardQueriesWithCEFacetsNotSupported", // When Scroll Search Request returns count of zero we will clear the scroll. ClearedScrollSearchRequestParam: "clearedScrollSearchRequestParam", // When Scroll Search Request has an invalid scroll id value. InvalidScrollSearchRequestParam: "invalidScrollSearchRequestParam", // For Stopping warmer requests StopWarmerRequests: "stopWarmerRequests", } // Defines the matched terms in the field of the package result. type PackageHit struct { // Reference name of the highlighted field. FieldReferenceName *string `json:"fieldReferenceName,omitempty"` // Matched/highlighted snippets of the field. Highlights *[]string `json:"highlights,omitempty"` } // Defines the package result that matched a package search request. type PackageResult struct { // Description of the package. Description *string `json:"description,omitempty"` // List of feeds which contain the matching package. Feeds *[]FeedInfo `json:"feeds,omitempty"` // List of highlighted fields for the match. Hits *[]PackageHit `json:"hits,omitempty"` // Id of the package. Id *string `json:"id,omitempty"` // Name of the package. Name *string `json:"name,omitempty"` // Type of the package. ProtocolType *string `json:"protocolType,omitempty"` } // Defines a package search request. type PackageSearchRequest struct { // Filters to be applied. Set it to null if there are no filters to be applied. Filters *map[string][]string `json:"filters,omitempty"` // The search text. SearchText *string `json:"searchText,omitempty"` // Options for sorting search results. If set to null, the results will be returned sorted by relevance. If more than one sort option is provided, the results are sorted in the order specified in the OrderBy. OrderBy *[]SortOption `json:"$orderBy,omitempty"` // Number of results to be skipped. Skip *int `json:"$skip,omitempty"` // Number of results to be returned. Top *int `json:"$top,omitempty"` // Flag to opt for faceting in the result. Default behavior is false. IncludeFacets *bool `json:"includeFacets,omitempty"` } type PackageSearchResponse struct { ActivityId *[]string `json:"activityId,omitempty"` Content *PackageSearchResponseContent `json:"content,omitempty"` } // Defines a response item that is returned for a package search request. type PackageSearchResponseContent struct { // A dictionary storing an array of <code>Filter</code> object against each facet. Facets *map[string][]Filter `json:"facets,omitempty"` // Numeric code indicating any additional information: 0 - Ok, 1 - Account is being reindexed, 2 - Account indexing has not started, 3 - Invalid Request, 4 - Prefix wildcard query not supported, 5 - MultiWords with code facet not supported, 6 - Account is being onboarded, 7 - Account is being onboarded or reindexed, 8 - Top value trimmed to maxresult allowed 9 - Branches are being indexed, 10 - Faceting not enabled, 11 - Work items not accessible, 19 - Phrase queries with code type filters not supported, 20 - Wildcard queries with code type filters not supported. Any other info code is used for internal purpose. InfoCode *int `json:"infoCode,omitempty"` // Total number of matched packages. Count *int `json:"count,omitempty"` // List of matched packages. Results *[]PackageResult `json:"results,omitempty"` } // Defines the details of the project. type ProjectReference struct { // ID of the project. Id *uuid.UUID `json:"id,omitempty"` // Name of the project. Name *string `json:"name,omitempty"` // Visibility of the project. Visibility *string `json:"visibility,omitempty"` } // Defines the details of the repository. type Repository struct { // Id of the repository. Id *string `json:"id,omitempty"` // Name of the repository. Name *string `json:"name,omitempty"` // Version control type of the result file. Type *VersionControlType `json:"type,omitempty"` } // Defines a scroll code search request. type ScrollSearchRequest struct { // Filters to be applied. Set it to null if there are no filters to be applied. Filters *map[string][]string `json:"filters,omitempty"` // The search text. SearchText *string `json:"searchText,omitempty"` // Scroll Id for scroll search query. ScrollId *string `json:"$scrollId,omitempty"` // Size of data to return for scroll search query. Min value is 201. ScrollSize *int `json:"$scrollSize,omitempty"` } // Defines how to sort the result. type SortOption struct { // Field name on which sorting should be done. Field *string `json:"field,omitempty"` // Order (ASC/DESC) in which the results should be sorted. SortOrder *string `json:"sortOrder,omitempty"` } type SortOrder string type sortOrderValuesType struct { Undefined SortOrder Ascending SortOrder Descending SortOrder } var SortOrderValues = sortOrderValuesType{ Undefined: "undefined", Ascending: "ascending", Descending: "descending", } // Describes the details pertaining to a version of the result file. type Version struct { // Name of the branch. BranchName *string `json:"branchName,omitempty"` // ChangeId in the given branch associated with this match. ChangeId *string `json:"changeId,omitempty"` } // Version control of the repository. type VersionControlType string type versionControlTypeValuesType struct { Git VersionControlType Tfvc VersionControlType Custom VersionControlType } var VersionControlTypeValues = versionControlTypeValuesType{ Git: "git", Tfvc: "tfvc", // For internal use. Custom: "custom", } // Defines the details of wiki. type Wiki struct { // Id of the wiki. Id *string `json:"id,omitempty"` // Mapped path for the wiki. MappedPath *string `json:"mappedPath,omitempty"` // Name of the wiki. Name *string `json:"name,omitempty"` // Version for wiki. Version *string `json:"version,omitempty"` } // Defines the matched terms in the field of the wiki result. type WikiHit struct { // Reference name of the highlighted field. FieldReferenceName *string `json:"fieldReferenceName,omitempty"` // Matched/highlighted snippets of the field. Highlights *[]string `json:"highlights,omitempty"` } // Defines the wiki result that matched a wiki search request. type WikiResult struct { // Collection of the result file. Collection *Collection `json:"collection,omitempty"` // ContentId of the result file. ContentId *string `json:"contentId,omitempty"` // Name of the result file. FileName *string `json:"fileName,omitempty"` // Highlighted snippets of fields that match the search request. The list is sorted by relevance of the snippets. Hits *[]WikiHit `json:"hits,omitempty"` // Path at which result file is present. Path *string `json:"path,omitempty"` // Project details of the wiki document. Project *ProjectReference `json:"project,omitempty"` // Wiki information for the result. Wiki *Wiki `json:"wiki,omitempty"` } // Defines a wiki search request. type WikiSearchRequest struct { // Filters to be applied. Set it to null if there are no filters to be applied. Filters *map[string][]string `json:"filters,omitempty"` // The search text. SearchText *string `json:"searchText,omitempty"` // Options for sorting search results. If set to null, the results will be returned sorted by relevance. If more than one sort option is provided, the results are sorted in the order specified in the OrderBy. OrderBy *[]SortOption `json:"$orderBy,omitempty"` // Number of results to be skipped. Skip *int `json:"$skip,omitempty"` // Number of results to be returned.
Top *int `json:"$top,omitempty"` // Flag to opt for faceting in the result. Default behavior is false. IncludeFacets *bool `json:"includeFacets,omitempty"` } // Defines a wiki search response item. type WikiSearchResponse struct { // A dictionary storing an array of <code>Filter</code> object against each facet. Facets *map[string][]Filter `json:"facets,omitempty"` // Numeric code indicating any additional information: 0 - Ok, 1 - Account is being reindexed, 2 - Account indexing has not started, 3 - Invalid Request, 4 - Prefix wildcard query not supported, 5 - MultiWords with code facet not supported, 6 - Account is being onboarded, 7 - Account is being onboarded or reindexed, 8 - Top value trimmed to maxresult allowed 9 - Branches are being indexed, 10 - Faceting not enabled, 11 - Work items not accessible, 19 - Phrase queries with code type filters not supported, 20 - Wildcard queries with code type filters not supported. Any other info code is used for internal purpose. InfoCode *int `json:"infoCode,omitempty"` // Total number of matched wiki documents. Count *int `json:"count,omitempty"` // List of top matched wiki documents. Results *[]WikiResult `json:"results,omitempty"` }
keychains.js
// // Keychains Object // BitGo accessor to a user's keychain. // // Copyright 2014, BitGo, Inc. All Rights Reserved. // var HDNode = require('./hdnode'); var crypto = require('crypto'); var common = require('./common'); var Util = require('./util'); // // Constructor // var Keychains = function(bitgo) { this.bitgo = bitgo; }; // // isValid // Tests a xpub or xprv string to see if it is a valid keychain. // Keychains.prototype.isValid = function(params) { params = params || {}; common.validateParams(params, [], []); if (typeof(params.key) != 'string' && typeof(params.key) != 'object') { throw new Error('key must be a string or object'); } try { if (!params.key.path) { HDNode.fromBase58(params.key); } else { HDNode.fromBase58(params.key.xpub).deriveFromPath(params.key.path); } return true; } catch (e) { return false; } }; // // create // Create a new keychain locally. // Does not send the keychain to bitgo, only creates locally. // If |seed| is provided, used to seed the keychain. Otherwise, // a random keychain is created. // Keychains.prototype.create = function(params) { params = params || {}; common.validateParams(params, [], []); var seed; if (!params.seed) { // An extended private key has both a normal 256 bit private key and a 256 // bit chain code, both of which must be random. 512 bits is therefore the // maximum entropy and gives us maximum security against cracking. seed = crypto.randomBytes(512 / 8); } else { seed = params.seed; } var extendedKey = HDNode.fromSeedBuffer(seed); return { xpub: extendedKey.neutered().toBase58(), xprv: extendedKey.toBase58() }; }; // // list // List the user's keychains // Keychains.prototype.list = function(params, callback) { params = params || {}; common.validateParams(params, [], [], callback); return this.bitgo.get(this.bitgo.url('/keychain')) .result('keychains') .nodeify(callback); }; // // add // Add a new keychain // Keychains.prototype.add = function(params, callback) { params = params || {}; common.validateParams(params, ['xpub'], ['encryptedXprv'], callback); return this.bitgo.post(this.bitgo.url('/keychain')) .send(params) .result() .nodeify(callback); }; // // addBitGo // Add a new BitGo server keychain // Keychains.prototype.createBitGo = function(params, callback) { params = params || {}; common.validateParams(params, [], [], callback); return this.bitgo.post(this.bitgo.url('/keychain/bitgo')) .send({}) .result() .nodeify(callback); }; // // get // Fetch an existing keychain // Parameters include: // xpub: the xpub of the key to lookup (required) // Keychains.prototype.get = function(params, callback) { params = params || {};
.result() .nodeify(callback); }; // // update // Update an existing keychain // Parameters include: // xpub: the xpub of the key to lookup (required) // Keychains.prototype.update = function(params, callback) { params = params || {}; common.validateParams(params, ['xpub'], ['encryptedXprv'], callback); return this.bitgo.put(this.bitgo.url('/keychain/' + params.xpub)) .send({ encryptedXprv: params.encryptedXprv, }) .result() .nodeify(callback); }; module.exports = Keychains;
common.validateParams(params, ['xpub'], [], callback); return this.bitgo.post(this.bitgo.url('/keychain/' + params.xpub)) .send({})
__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class nodes(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-tunnels-ext - based on the path /brocade_tunnels_ext_rpc/get-tunnel-info/output/tunnel/nodes. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Indicates the nodes from which this tunnel data are retrieved. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__node_id',) _yang_name = 'nodes' _rest_name = 'nodes' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__node_id = YANGDynClass(base=TypedListType(allowed_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)), is_leaf=False, yang_name="node-id", rest_name="node-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-tunnels-ext', defining_module='brocade-tunnels-ext', yang_type='uint32', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'brocade_tunnels_ext_rpc', u'get-tunnel-info', u'output', u'tunnel', u'nodes'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'get-tunnel-info', u'output', u'tunnel', u'nodes'] def _get_node_id(self): """ Getter method for node_id, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/nodes/node_id (uint32) YANG Description: Node id """ return self.__node_id def
(self, v, load=False): """ Setter method for node_id, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/nodes/node_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_node_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_node_id() directly. YANG Description: Node id """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=TypedListType(allowed_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)), is_leaf=False, yang_name="node-id", rest_name="node-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-tunnels-ext', defining_module='brocade-tunnels-ext', yang_type='uint32', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """node_id must be of a type compatible with uint32""", 'defined-type': "uint32", 'generated-type': """YANGDynClass(base=TypedListType(allowed_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)), is_leaf=False, yang_name="node-id", rest_name="node-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-tunnels-ext', defining_module='brocade-tunnels-ext', yang_type='uint32', is_config=True)""", }) self.__node_id = t if hasattr(self, '_set'): self._set() def _unset_node_id(self): self.__node_id = YANGDynClass(base=TypedListType(allowed_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)), is_leaf=False, yang_name="node-id", rest_name="node-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, namespace='urn:brocade.com:mgmt:brocade-tunnels-ext', defining_module='brocade-tunnels-ext', yang_type='uint32', is_config=True) node_id = __builtin__.property(_get_node_id, _set_node_id) _pyangbind_elements = {'node_id': node_id, }
_set_node_id
contact.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.css'] }) export class ContactComponent implements OnInit { myimage4:string = "assets/images/image5.jpg"; constructor() { }
} }
ngOnInit(): void {
get.go
package serving import ( "encoding/json" "fmt" "os" "strings" "text/tabwriter" "gopkg.in/yaml.v2" "github.com/kubeflow/arena/pkg/apis/types" "github.com/kubeflow/arena/pkg/apis/utils" log "github.com/sirupsen/logrus" ) var ( errNotFoundServingJobMessage = "Not found serving job %v, please check it with `arena serve list | grep %v`" ) var getJobTemplate = ` Name: %v Namespace: %v Type: %v Version: %v Desired: %v Available: %v Age: %v Address: %v Port: %v %v ` func SearchServingJob(namespace, name, version string, servingType types.ServingJobType) (ServingJob, error) { if servingType == types.UnknownServingJob { return nil, fmt.Errorf("Unknown serving job type,arena only supports: [%s]", utils.GetSupportServingJobTypesInfo()) } processers := GetAllProcesser() if servingType != types.AllServingJob { processer, ok := processers[servingType] if !ok { return nil, fmt.Errorf("unknown processer %v,please define it", servingType) } servingJobs, err := processer.GetServingJobs(namespace, name, version) if err != nil { return nil, err } if len(servingJobs) == 0 { return nil, fmt.Errorf(errNotFoundServingJobMessage, name, name) } if len(servingJobs) > 1 { return nil, fmt.Errorf("%v", moreThanOneJobHelpInfo(servingJobs)) } return servingJobs[0], nil } jobs := []ServingJob{} for _, p := range processers { servingJobs, err := p.GetServingJobs(namespace, name, version) if err != nil { log.Debugf("processer %v does not support the serving job %v", p.Type(), name) continue } jobs = append(jobs, servingJobs...) } if len(jobs) == 0 { return nil, fmt.Errorf(errNotFoundServingJobMessage, name, name) } if len(jobs) > 1 { return nil, fmt.Errorf("%v", moreThanOneJobHelpInfo(jobs)) } return jobs[0], nil } func PrintServingJob(job ServingJob, format types.FormatStyle) { switch format { case types.JsonFormat: data, _ := json.MarshalIndent(job.Convert2JobInfo(), "", " ") fmt.Printf("%v", string(data)) return case types.YamlFormat: data, _ := yaml.Marshal(job.Convert2JobInfo()) fmt.Printf("%v", string(data)) return } jobInfo := job.Convert2JobInfo() endpointAddress := jobInfo.IPAddress ports := []string{} for _, e := range jobInfo.Endpoints { port := "" if e.NodePort != 0 { port = fmt.Sprintf("%v:%v->%v", strings.ToUpper(e.Name), e.NodePort, e.Port) } else { port = fmt.Sprintf("%v:%v", strings.ToUpper(e.Name), e.Port) } ports = append(ports, port) } isGPUShare := false title := "GPUs" step := "----" gpuAllocation := fmt.Sprintf("GPUs: %v", jobInfo.RequestGPU) if jobInfo.RequestGPUMemory != 0 { isGPUShare = true title = "GPU_MEMORY" step = "----------" gpuAllocation = fmt.Sprintf("GPU Memory: %vGiB", jobInfo.RequestGPUMemory) } lines := []string{gpuAllocation, "", "Instances:", fmt.Sprintf(" NAME\tSTATUS\tAGE\tREADY\tRESTARTS\t%v\tNODE", title)} lines = append(lines, fmt.Sprintf(" ----\t------\t---\t-----\t--------\t%v\t----", step)) for _, i := range jobInfo.Instances { value := fmt.Sprintf("%v", i.RequestGPU) if isGPUShare {
} items := []string{ fmt.Sprintf(" %v", i.Name), fmt.Sprintf("%v", i.Status), fmt.Sprintf("%v", i.Age), fmt.Sprintf("%v/%v", i.ReadyContainer, i.TotalContainer), fmt.Sprintf("%v", i.RestartCount), fmt.Sprintf("%v", value), fmt.Sprintf("%v", i.NodeName), } lines = append(lines, strings.Join(items, "\t")) } lines = append(lines, "") w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) output := fmt.Sprintf(strings.Trim(getJobTemplate, "\n"), jobInfo.Name, jobInfo.Namespace, jobInfo.Type, jobInfo.Version, jobInfo.Desired, jobInfo.Available, jobInfo.Age, endpointAddress, strings.Join(ports, ","), strings.Join(lines, "\n"), ) fmt.Fprintf(w, output) w.Flush() }
value = fmt.Sprintf("%vGiB", i.RequestGPUMemory)
csidriver.ts
// *** WARNING: this file was generated by pulumigen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../../types"; import * as utilities from "../../utilities"; /** * CSIDriver captures information about a Container Storage Interface (CSI) volume driver deployed on the cluster. Kubernetes attach detach controller uses this object to determine whether attach is required. Kubelet uses this object to determine whether pod information needs to be passed on mount. CSIDriver objects are non-namespaced. */ export class CSIDriver extends pulumi.CustomResource { /** * Get an existing CSIDriver resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): CSIDriver { return new CSIDriver(name, undefined as any, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'kubernetes:storage.k8s.io/v1:CSIDriver'; /** * Returns true if the given object is an instance of CSIDriver. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is CSIDriver { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === CSIDriver.__pulumiType; } /** * APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ public readonly apiVersion!: pulumi.Output<"storage.k8s.io/v1">; /** * Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ public readonly kind!: pulumi.Output<"CSIDriver">; /** * Standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ public readonly metadata!: pulumi.Output<outputs.meta.v1.ObjectMeta>; /** * Specification of the CSI Driver. */ public readonly spec!: pulumi.Output<outputs.storage.v1.CSIDriverSpec>; /** * Create a CSIDriver resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args?: CSIDriverArgs, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (!opts.id) { if ((!args || args.spec === undefined) && !opts.urn) { throw new Error("Missing required property 'spec'"); } inputs["apiVersion"] = "storage.k8s.io/v1"; inputs["kind"] = "CSIDriver"; inputs["metadata"] = args ? args.metadata : undefined; inputs["spec"] = args ? args.spec : undefined; } else { inputs["apiVersion"] = undefined /*out*/; inputs["kind"] = undefined /*out*/; inputs["metadata"] = undefined /*out*/; inputs["spec"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } const aliasOpts = { aliases: [{ type: "kubernetes:storage.k8s.io/v1beta1:CSIDriver" }] }; opts = pulumi.mergeOptions(opts, aliasOpts); super(CSIDriver.__pulumiType, name, inputs, opts); } } /**
*/ export interface CSIDriverArgs { /** * APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: pulumi.Input<"storage.k8s.io/v1">; /** * Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind?: pulumi.Input<"CSIDriver">; /** * Standard object metadata. metadata.Name indicates the name of the CSI driver that this object refers to; it MUST be the same name returned by the CSI GetPluginName() call for that driver. The driver name must be 63 characters or less, beginning and ending with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), dots (.), and alphanumerics between. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ metadata?: pulumi.Input<inputs.meta.v1.ObjectMeta>; /** * Specification of the CSI Driver. */ spec: pulumi.Input<inputs.storage.v1.CSIDriverSpec>; }
* The set of arguments for constructing a CSIDriver resource.
vcc.go
// Copyright 2020 Thinkium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dao import ( "github.com/ThinkiumGroup/go-common" "github.com/ThinkiumGroup/go-common/db" ) func SaveCccTxIndex(dbase db.Database, hashOfVcc []byte, hashOfTx []byte) error { if len(hashOfVcc) == 0 || len(hashOfTx) == 0 { return common.ErrNil } key := db.PrefixKey(db.KPCVccTxIndex, hashOfVcc) return dbase.Put(key, hashOfTx) } func GetCccTxIndex(dbase db.Database, hashOfVcc []byte) (hashOfTx []byte, err error)
{ if len(hashOfVcc) == 0 { return nil, common.ErrNil } key := db.PrefixKey(db.KPCVccTxIndex, hashOfVcc) hashOfTx, err = dbase.Get(key) return }
index.js
/** * Copyright 2019 Parity Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const React = require("react"); const HomeSplash = require(`${process.cwd()}` + `/core/HomeSplash`); const Container = require("../../../../react-bootstrap/Container"); const Button = require("../../../../react-bootstrap/Button"); const Row = require("../../../../react-bootstrap/Row"); const Col = require("../../../../react-bootstrap/Col"); const Image = require("../../../../react-bootstrap/Image"); const Alert = require("../../../../react-bootstrap/Alert"); const translate = require("../../server/translate").translate; class
extends React.Component { render() { const { config: siteConfig, language = "" } = this.props; const { baseUrl } = siteConfig; const langPart = language ? `${language}/` : ""; const pageUrl = (page) => `${baseUrl}${langPart}${page}`; const docUrl = (doc = "") => `${baseUrl}docs/${langPart}${doc}`; return ( <section> <div className="announcement"> <div className="announcement-text"> Meet others who speak your language! For devs at all levels - Sub0 Online, October 13-14, 2021. {` `} <a href="https://sub0.substrate.io/?utm_source=substrate.dev&utm_medium=referral&utm_campaign=sub0%202021&utm_content=registrations&utm_term=parity&ref=2bcd2286876e"> <span className="announcement-bottom">Register now</span> </a> </div> </div> <div className="announcement"> <div className="announcement-text"> <strong>A brand new DevHub is here!</strong> As of this Wednesday, Oct. 13th, the current Substrate docs on substrate.dev will be archived and all links will redirect to the new site. Preview it now at{" "} <a href="https://docs.substrate.io"> <span className="announcement-bottom">docs.substrate.io</span> </a> . </div> </div> <HomeSplash id="home-hero" siteConfig={siteConfig} language={language} title={<translate>Substrate Developer Hub</translate>} tagline={<translate>Blockchain Development for Innovators</translate>} description={ <translate> Substrate is a modular framework that enables you to create purpose-built blockchains by composing custom or pre-built components. </translate> } buttonText={<translate>Get Started</translate>} buttonUrl={docUrl()} /> <section className="mainContainer" id="home"> <Container> <section className="intro-statement home-section"> <span className="tagline"> <translate>Why Use Substrate?</translate> </span> <h2 className="large h1"> <translate>Focus on Your Strengths</translate> </h2> <p className="big"> <translate> Substrate's modular design means you can reuse battle-tested libraries while building the custom components that matter most. </translate> </p> </section> <section className="intro-blocks home-section"> <section className="intro-block"> <section className="icon-wrap"> <div className="icon runtime" /> </section> <h4> <translate>Runtime Development</translate> </h4> <p> <translate> Use Substrate's FRAME runtime system to build secure, scalable blockchain logic. </translate> </p> <section className="button-wrap"> <a href={docUrl("knowledgebase/runtime")} className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> <section className="intro-block"> <section className="icon-wrap"> <div className="icon frontend" /> </section> <h4> <translate>Client Libraries</translate> </h4> <p> <translate> Create rich user experiences for any Substrate-based chain with Polkadot-JS. </translate> </p> <section className="button-wrap"> <a href={docUrl("knowledgebase/integrate/polkadot-js")} className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> <section className="intro-block"> <section className="icon-wrap"> <div className="icon smart-contract" /> </section> <h4> <translate>Smart Contracts</translate> </h4> <p> <translate> Substrate supports multiple smart contract platforms, including the EVM. </translate> </p> <section className="button-wrap"> <a href="/tutorials/ink-smart-contracts-tutorial" className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> </section> </Container> <section className="bg-white what-is-substrate"> <div className="container"> <div className="pt-5"> <div className="row justify-content-center text-center py-3"> <div className="col-12 col-md-8"> <span className="tagline"> <translate>What is Substrate?</translate> </span> <h2 className="display-4 h1"> <translate>Everything you need to build a blockchain.</translate> </h2> <p className="big"> <translate> Substrate is powered by best-in-class cryptographic research and comes with peer-to-peer networking, consensus mechanisms, and much more. </translate> </p> </div> </div> </div> <div className="row py-5 features"> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-1.svg" width="40" /> <h3 className="mb-0"> <translate>Fast and Efficient Database</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-2.svg" width="40" /> <h3 className="mb-0"> <translate>Modular P2P Networking Stack</translate> </h3> </div> </div> <div className="col-12 col-md-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-3.svg" width="40" /> <h3 className="mb-0"> <translate>Hot-Swappable Consensus Layer</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-4.svg" width="40" /> <h3 className="mb-0"> <translate>Configurable Transaction Queue</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-5.svg" width="40" /> <h3 className="mb-0"> <translate>Flexible Runtime Library</translate> </h3> </div> </div> <div className="col-12 col-md-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-6.svg" width="40" /> <h3 className="mb-0"> <translate>Light Client Optimized</translate> </h3> </div> </div> </div> </div> </section> <section className="bg-light call-outs second"> <div className="container"> <div className="row justify-content-between align-items-center py-5 polkadot-row"> <div className="col-12 col-md-6 pl-md-0 mb-4 mb-md-0 text-center polkadot-graphic-wrap"> <img src="/img/pictures/polkadot-network.svg" className="polkadot-image" /> <div className="polkadot-graphic" style={{ backgroundImage: `url(/img/pictures/polkadot-network.svg)` }} /> </div> <div className="col-12 col-md-5"> <h2 className="h1"> <translate>Production Ready</translate> </h2> <p className="large mb-4"> <translate> Substrate is the backbone that powers Polkadot, a next generation, heterogeneous, multi-chain network. Most of the blockchains in the Polkadot ecosystem are also built on Substrate. The Polkadot Network was launched in May of 2020. </translate> </p> <a className="action-link" href="https://polkadot.network/technology/"> <span> <translate>Learn more about Polkadot</translate> </span> </a> </div> </div> </div> </section> <section className="bg-light call-outs first"> <div className="container"> <div className="row justify-content-between align-items-center py-5"> <div className="col-12 col-md-5 order-2 order-md-1"> <h2 className="h1"> <translate>Smart Contract Ready</translate> </h2> <p className="large mb-4"> <translate> Substrate has a Wasm smart contract platform that you can use out of the box. Because Substrate uses Wasm, you can build your smart contracts using any compatible language. We have built ink!, a Rust-based eDSL, for this purpose. </translate> </p> <a className="action-link" href={docUrl("knowledgebase/smart-contracts/")}> <span> <translate>Learn more about ink!</translate> </span> </a> </div> <div className="col-12 col-md-6 order-1 order-md-2 pl-md-0 mb-4 mb-md-0 text-center"> <img className="w-25" src="/img/pictures/substrate-wasm.svg" /> </div> </div> </div> </section> <section className="bg-white learn"> <div className="container"> <div className="row justify-content-center text-center pt-5"> <div className="col-12 col-md-10"> <span className="tagline"> <translate>Keep Exploring!</translate> </span> <h2 className="display-4 h1"> <translate>There are lots of ways to learn about Substrate.</translate> </h2> </div> </div> </div> </section> <section className="bg-white learn-blocks"> <div className="container"> <div className="row text-center flex-md-nowrap py-md-5"> <div className="col-12 col-md-6"> <div className="row justify-content-center"> <div className="col-12 col-lg-8"> <div className="py-5 py-md-0"> <h2> <translate>Substrate Seminar</translate> </h2> <p className="mb-3"> <translate> An open, collaborative group for learning about Substrate and connecting with other builders. </translate> </p> <a className="btn primary-color" href={pageUrl("seminar")}> <translate>Join the Seminar</translate> </a> </div> <div className="border-bottom d-md-none" /> </div> </div> </div> <div className="border-right d-none d-md-block" /> <div className="col-12 col-md-6"> <div className="row justify-content-center"> <div className="col-12 col-lg-8"> <div className="py-5 py-md-0"> <h2> <translate>Substrate Recipes</translate> </h2> <p className="mb-3"> <translate> A collection of working code examples that solve common problems. </translate> </p> <a className="btn primary-color" href="https://substrate.dev/recipes"> <translate>Browse the Recipes</translate> </a> </div> </div> </div> </div> </div> </div> </section> <section className="bg-light bottom-cta"> <div className="container"> <div className="py-5"> <div className="row justify-content-center text-center py-3"> <div className="col-12 col-md-10"> <h2 className="display-4 h1"> <translate>Ready to build with Substrate?</translate> </h2> </div> <div className="col-12 col-md-8"> <p className="lead mb-4"> <translate> Get started with our helpful documentation or ask questions in our technical chat! </translate> </p> <div className="d-flex justify-content-center"> <div className="px-1"> <a className="btn btn-lg primary-color" href={docUrl()}> <translate>Get Started</translate> </a> </div> <div className="px-1"> <a className="btn btn-lg btn-outline-primary" href="https://app.element.io/#/room/!HzySYSaIhtyWrwiwEV:matrix.org" > <translate>Ask Questions</translate> </a> </div> </div> </div> </div> </div> </div> </section> </section> </section> ); } } Index.title = "Official Substrate Documentation for Blockchain Developers"; Index.description = "Learn to build blockchains using the next generation blockchain framework."; module.exports = Index;
Index
utils.go
/* * Corrently.io * * *Corrently - from italian corrente, which is energy* # Introduction The Corrently ecosystem gets maintained by [STROMDAO GmbH](https://www.stromdao.de/) to support green energy services for prosumers, grid operators, regulators, integrators or any other party with an emerging need of consensus driven management. As the [energy product Corrently](https://www.corrently.de/) got first launched in Germany parts of this documentation provide simple translations for better understanding. [Released SKDs for Download](https://github.com/energychain/corrently-api/releases) * * API version: 2.0.0 * Contact: [email protected] */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package openapi import ( "encoding/json" "time" ) // PtrBool is a helper routine that returns a pointer to given boolean value. func PtrBool(v bool) *bool { return &v } // PtrInt is a helper routine that returns a pointer to given integer value. func
(v int) *int { return &v } // PtrInt32 is a helper routine that returns a pointer to given integer value. func PtrInt32(v int32) *int32 { return &v } // PtrInt64 is a helper routine that returns a pointer to given integer value. func PtrInt64(v int64) *int64 { return &v } // PtrFloat32 is a helper routine that returns a pointer to given float value. func PtrFloat32(v float32) *float32 { return &v } // PtrFloat64 is a helper routine that returns a pointer to given float value. func PtrFloat64(v float64) *float64 { return &v } // PtrString is a helper routine that returns a pointer to given string value. func PtrString(v string) *string { return &v } // PtrTime is helper routine that returns a pointer to given Time value. func PtrTime(v time.Time) *time.Time { return &v } type NullableBool struct { value *bool isSet bool } func (v NullableBool) Get() *bool { return v.value } func (v *NullableBool) Set(val *bool) { v.value = val v.isSet = true } func (v NullableBool) IsSet() bool { return v.isSet } func (v *NullableBool) Unset() { v.value = nil v.isSet = false } func NewNullableBool(val *bool) *NullableBool { return &NullableBool{value: val, isSet: true} } func (v NullableBool) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBool) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt struct { value *int isSet bool } func (v NullableInt) Get() *int { return v.value } func (v *NullableInt) Set(val *int) { v.value = val v.isSet = true } func (v NullableInt) IsSet() bool { return v.isSet } func (v *NullableInt) Unset() { v.value = nil v.isSet = false } func NewNullableInt(val *int) *NullableInt { return &NullableInt{value: val, isSet: true} } func (v NullableInt) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt32 struct { value *int32 isSet bool } func (v NullableInt32) Get() *int32 { return v.value } func (v *NullableInt32) Set(val *int32) { v.value = val v.isSet = true } func (v NullableInt32) IsSet() bool { return v.isSet } func (v *NullableInt32) Unset() { v.value = nil v.isSet = false } func NewNullableInt32(val *int32) *NullableInt32 { return &NullableInt32{value: val, isSet: true} } func (v NullableInt32) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt32) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt64 struct { value *int64 isSet bool } func (v NullableInt64) Get() *int64 { return v.value } func (v *NullableInt64) Set(val *int64) { v.value = val v.isSet = true } func (v NullableInt64) IsSet() bool { return v.isSet } func (v *NullableInt64) Unset() { v.value = nil v.isSet = false } func NewNullableInt64(val *int64) *NullableInt64 { return &NullableInt64{value: val, isSet: true} } func (v NullableInt64) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt64) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableFloat32 struct { value *float32 isSet bool } func (v NullableFloat32) Get() *float32 { return v.value } func (v *NullableFloat32) Set(val *float32) { v.value = val v.isSet = true } func (v NullableFloat32) IsSet() bool { return v.isSet } func (v *NullableFloat32) Unset() { v.value = nil v.isSet = false } func NewNullableFloat32(val *float32) *NullableFloat32 { return &NullableFloat32{value: val, isSet: true} } func (v NullableFloat32) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableFloat32) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableFloat64 struct { value *float64 isSet bool } func (v NullableFloat64) Get() *float64 { return v.value } func (v *NullableFloat64) Set(val *float64) { v.value = val v.isSet = true } func (v NullableFloat64) IsSet() bool { return v.isSet } func (v *NullableFloat64) Unset() { v.value = nil v.isSet = false } func NewNullableFloat64(val *float64) *NullableFloat64 { return &NullableFloat64{value: val, isSet: true} } func (v NullableFloat64) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableFloat64) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableString struct { value *string isSet bool } func (v NullableString) Get() *string { return v.value } func (v *NullableString) Set(val *string) { v.value = val v.isSet = true } func (v NullableString) IsSet() bool { return v.isSet } func (v *NullableString) Unset() { v.value = nil v.isSet = false } func NewNullableString(val *string) *NullableString { return &NullableString{value: val, isSet: true} } func (v NullableString) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableString) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableTime struct { value *time.Time isSet bool } func (v NullableTime) Get() *time.Time { return v.value } func (v *NullableTime) Set(val *time.Time) { v.value = val v.isSet = true } func (v NullableTime) IsSet() bool { return v.isSet } func (v *NullableTime) Unset() { v.value = nil v.isSet = false } func NewNullableTime(val *time.Time) *NullableTime { return &NullableTime{value: val, isSet: true} } func (v NullableTime) MarshalJSON() ([]byte, error) { return v.value.MarshalJSON() } func (v *NullableTime) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
PtrInt
register_test.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package json import ( "context" "testing" "github.com/stretchr/testify/assert" ) func TestWrapUnaryHandlerInvalid(t *testing.T) { tests := []struct { Name string Func interface{} }{ {"empty", func() {}}, {"not-a-function", 0}, { "wrong-args-in", func(context.Context) (*struct{}, error) { return nil, nil }, }, { "wrong-ctx", func(string, *struct{}) (*struct{}, error) { return nil, nil }, }, { "wrong-req-body", func(context.Context, string, int) (*struct{}, error) { return nil, nil }, }, { "wrong-response", func(context.Context, map[string]interface{}) error { return nil }, }, { "non-pointer-req", func(context.Context, struct{}) (*struct{}, error) { return nil, nil }, }, { "non-pointer-res", func(context.Context, *struct{}) (struct{}, error) { return struct{}{}, nil }, }, { "non-string-key", func(context.Context, map[int32]interface{}) (*struct{}, error) { return nil, nil }, }, { "second-return-value-not-error", func(context.Context, *struct{}) (*struct{}, *struct{}) { return nil, nil }, }, } for _, tt := range tests { assert.Panics(t, assert.PanicTestFunc(func() { wrapUnaryHandler(tt.Name, tt.Func) }), tt.Name) } } func
(t *testing.T) { tests := []struct { Name string Func interface{} }{ { "foo", func(context.Context, *struct{}) (*struct{}, error) { return nil, nil }, }, { "bar", func(context.Context, map[string]interface{}) (*struct{}, error) { return nil, nil }, }, { "baz", func(context.Context, map[string]interface{}) (map[string]interface{}, error) { return nil, nil }, }, { "qux", func(context.Context, interface{}) (map[string]interface{}, error) { return nil, nil }, }, } for _, tt := range tests { wrapUnaryHandler(tt.Name, tt.Func) } } func TestWrapOnewayHandlerInvalid(t *testing.T) { tests := []struct { Name string Func interface{} }{ {"empty", func() {}}, {"not-a-function", 0}, { "wrong-args-in", func(context.Context) error { return nil }, }, { "wrong-ctx", func(string, *struct{}) error { return nil }, }, { "wrong-req-body", func(context.Context, string, int) error { return nil }, }, { "wrong-response", func(context.Context, map[string]interface{}) (*struct{}, error) { return nil, nil }, }, { "wrong-response-val", func(context.Context, map[string]interface{}) int { return 0 }, }, { "non-pointer-req", func(context.Context, struct{}) error { return nil }, }, { "non-string-key", func(context.Context, map[int32]interface{}) error { return nil }, }, } for _, tt := range tests { assert.Panics(t, assert.PanicTestFunc(func() { wrapOnewayHandler(tt.Name, tt.Func) })) } } func TestWrapOnewayHandlerValid(t *testing.T) { tests := []struct { Name string Func interface{} }{ { "foo", func(context.Context, *struct{}) error { return nil }, }, { "bar", func(context.Context, map[string]interface{}) error { return nil }, }, { "baz", func(context.Context, map[string]interface{}) error { return nil }, }, { "qux", func(context.Context, interface{}) error { return nil }, }, } for _, tt := range tests { wrapOnewayHandler(tt.Name, tt.Func) } }
TestWrapUnaryHandlerValid
specfile.py
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import inspect import re from logging import getLogger from pathlib import Path from typing import Union, List, Optional, Dict from packit.patches import PatchMetadata from rebasehelper.helpers.macro_helper import MacroHelper from rebasehelper.specfile import SpecFile, RebaseHelperError, saves, PatchObject from rebasehelper.tags import Tag, Tags try: from rebasehelper.plugins.plugin_manager import plugin_manager except ImportError: from rebasehelper.versioneer import versioneers_runner from packit.exceptions import PackitException logger = getLogger(__name__) class Specfile(SpecFile): def
(self, path: Union[str, Path], sources_dir: Union[str, Path] = ""): s = inspect.signature(SpecFile) if "changelog_entry" in s.parameters: super().__init__( path=str(path), sources_location=str(sources_dir), changelog_entry="" ) else: super().__init__(path=str(path), sources_location=str(sources_dir)) self._patch_id_digits: Optional[int] = None self._uses_autosetup: Optional[bool] = None def update_spec(self): if hasattr(self, "update"): # new rebase-helper self.update() else: # old rebase-helper self._update_data() def update_changelog_in_spec(self, changelog_entry): if hasattr(self, "update_changelog"): # new rebase-helper self.update_changelog(changelog_entry) else: # old rebase-helper self.changelog_entry = changelog_entry new_log = self.get_new_log() new_log.extend(self.spec_content.sections["%changelog"]) self.spec_content.sections["%changelog"] = new_log self.save() def set_spec_version( self, version: str = None, release: str = None, changelog_entry: str = None ): """ Set version in spec, release and add a changelog_entry (if they are presented). :param version: new version :param release: new release :param changelog_entry: accompanying changelog entry """ try: if version: # also this code adds 3 rpmbuild dirs into the upstream repo, # we should ask rebase-helper not to do that # using set_tag instead of set_version to turn off preserving macros self.set_tag("Version", version, preserve_macros=False) if release: # using set_tag instead of set_release to turn off preserving macros self.set_tag( "Release", "{}%{{?dist}}".format(release), preserve_macros=False ) if not changelog_entry: return self.update_changelog_in_spec(changelog_entry) except RebaseHelperError as ex: logger.error(f"Rebase-helper failed to change the spec file: {ex}") raise PackitException("Rebase-helper didn't do the job.") def write_spec_content(self): if hasattr(self, "_write_spec_content"): # new rebase-helper self._write_spec_content() else: # old rebase-helper self._write_spec_file_to_disc() @staticmethod def get_upstream_version(versioneer, package_name, category): """ Call the method of rebase-helper (due to the version of rebase-helper) to get the latest upstream version of a package. :param versioneer: :param package_name: str :param category: :return: str version """ try: get_version = plugin_manager.versioneers.run except NameError: get_version = versioneers_runner.run return get_version(versioneer, package_name, category) def get_release_number(self) -> str: """ Removed in rebasehelper=0.20.0 """ release = self.header.release dist = MacroHelper.expand("%{dist}") if dist: release = release.replace(dist, "") return re.sub(r"([0-9.]*[0-9]+).*", r"\1", release) @saves def set_patches( self, patch_list: List[PatchMetadata], patch_id_digits: int = 4 ) -> None: """ Set given patches in the spec file :param patch_list: [PatchMetadata] :param patch_id_digits: Number of digits of the generated patch ID. This is used to control whether to have 'Patch' or 'Patch1' or 'Patch0001'. """ if not patch_list: return if all(p.present_in_specfile for p in patch_list): logger.debug( "All patches are present in the spec file, nothing to do here 🚀" ) return # we could have generated patches before (via git-format-patch) # so let's reload the spec self.reload() applied_patches: Dict[str, PatchObject] = { p.get_patch_name(): p for p in self.get_applied_patches() } for patch_metadata in patch_list: if patch_metadata.present_in_specfile: logger.debug( f"Patch {patch_metadata.name} is already present in the spec file." ) continue if patch_metadata.name in applied_patches: logger.debug( f"Patch {patch_metadata.name} is already defined in the spec file." ) continue self.add_patch(patch_metadata, patch_id_digits) def add_patch( self, patch_metadata: PatchMetadata, patch_id_digits: Optional[int] = 4 ): """ Add provided patch to the spec file: * Set Patch index to be +1 than the highest index of an existing specfile patch * The Patch placement logic works like this: * If there already are patches, then the patch is added after them * If there are no existing patches, the patch is added after Source definitions Args: patch_metadata: Metadata of the patch to be added. patch_id_digits: Number of digits of the generated patch ID. This is used to control whether to have 'Patch' or 'Patch1' or 'Patch0001'. """ try: patch_number_offset = max(x.index for x in self.get_applied_patches()) except ValueError: logger.debug("There are no patches in the spec.") # 0 is a valid patch index patch_number_offset = -1 if patch_metadata.patch_id is not None: if patch_metadata.patch_id <= patch_number_offset: raise PackitException( f"The 'patch_id' requested ({patch_metadata.patch_id}) for patch " f"{patch_metadata.name} is less than or equal to the last used patch ID " f"({patch_number_offset}). Re-ordering the patches using 'patch_id' is " "not allowed - if you want to change the order of those patches, " "please reorder the commits in your source-git repository." ) patch_id = patch_metadata.patch_id else: # 0 is a valid patch index, but let's start with 1 which is more common, e.g. # https://src.fedoraproject.org/rpms/glibc/blob/f6682c9bac5872385b3caae0cd51fe3dbfcbb88f/f/glibc.spec#_158 # https://src.fedoraproject.org/rpms/python3.10/blob/ac9a5093cb9f534ef2f65cbd1f50684c88b91eec/f/python3.10.spec#_267 patch_id = max(patch_number_offset + 1, 1) new_content = "\n" new_content += "\n".join( line if line.startswith("#") else f"# {line}".strip() for line in patch_metadata.specfile_comment.splitlines() ) patch_id_str = f"{patch_id:0{patch_id_digits}d}" if patch_id_digits > 0 else "" new_content += f"\nPatch{patch_id_str}: {patch_metadata.name}" if self.get_applied_patches(): last_source_tag_line = [ t.line for t in self.tags.filter(name="Patch*", valid=None) ][-1] else: last_source_tag_line = [ t.line for t in self.tags.filter(name="Source*", valid=None) ][-1] # Find first empty line after last_source_tag_line for index, line in enumerate( self.spec_content.section("%package")[last_source_tag_line:], start=last_source_tag_line, ): if not line: where = index break else: where = len(self.spec_content.section("%package")) logger.debug(f"Adding patch {patch_metadata.name} to the spec file.") self.spec_content.section("%package")[where:where] = new_content.splitlines() self.save() def get_source(self, source_name: str) -> Optional[Tag]: """ get specific Source from spec :param source_name: precise name of the Source, e.g. Source1, or Source :return: corresponding Source Tag """ # sanitize the name, this will also add index if there isn't one source_name, *_ = Tags._sanitize_tag(source_name, 0, 0) return next(self.tags.filter(name=source_name, valid=None), None) def read_patch_comments(self) -> dict: """Read the spec again, detect comment lines right above a patch-line and save it as an attribute to the patch for later retrieval. Match patch-lines with the patch-data from rebase-helper on the name of the patches. Returns: A dict where each patch name (the basename of the value of the patch-line) has 0 or more comment lines associated with it. """ comment: List[str] = [] patch_comments = {} for line in self.spec_content.section("%package"): # An empty line clears the comment lines collected so far. if not line.strip(): comment = [] # Remember a comment line. if line.startswith("#"): comment.append(line[1:].strip()) # Associate comments with patches and clear the comments # collected. if line.lower().startswith("patch"): patch_name = Path(line.split(":", 1)[1].strip()).name patch_comments[patch_name] = comment comment = [] return patch_comments @property def patch_id_digits(self) -> int: """Detect and return the number of digits used in patch IDs (indices). Look for the first patch-line, and use that as a reference. 0 - no patch ID at all, just a bare "Patch" 1 - no leading zeros for patch IDs 2 or more - the minimum number of digits to be used for patch IDs. Returns: Number of digits used on the first patch-line, or 0 if there is no patch-line found. """ if self._patch_id_digits is not None: return self._patch_id_digits self._patch_id_digits = 1 for line in self.spec_content.section("%package"): if line.lower().startswith("patch"): match = re.match(r"^patch(\d*)\s*:.+", line, flags=re.IGNORECASE) if not match[1]: self._patch_id_digits = 0 elif match[1].startswith("0"): self._patch_id_digits = len(match[1]) break return self._patch_id_digits @property def uses_autosetup(self) -> bool: """Tell if the specfile uses %autosetup Returns: True if the file uses %autosetup, otherwise False. """ if self._uses_autosetup is not None: return self._uses_autosetup self._uses_autosetup = False for line in self.spec_content.section("%prep"): if line.startswith("%autosetup"): self._uses_autosetup = True break return self._uses_autosetup def remove_patches(self): """Remove all patch-lines from the spec file""" content = [] stretch = [] for line in self.spec_content.section("%package"): stretch.append(line) # Empty lines save the current stretch into content. if not line.strip(): content += stretch stretch = [] # Patch-lines throw away the current stretch. if line.lower().startswith("patch"): stretch = [] # If there is an empty line at the end of content # throw it away, to avoid duplicate lines. if not content[-1].strip(): content.pop() self.spec_content.replace_section("%package", content) self.save()
__init__
env.go
// SPDX-FileCopyrightText: 2020-present Open Networking Foundation <[email protected]> // // SPDX-License-Identifier: Apache-2.0 package atomix import ( "github.com/google/uuid" "os" "strconv" "sync" ) const ( clientIDEnv = "ATOMIX_CLIENT_ID" hostEnv = "ATOMIX_BROKER_HOST" portEnv = "ATOMIX_BROKER_PORT" ) const defaultHost = "127.0.0.1" const defaultPort = 5678 var envClient *Client var envClientMu sync.RWMutex func getClient() *Client
{ envClientMu.RLock() client := envClient envClientMu.RUnlock() if client != nil { return client } envClientMu.Lock() defer envClientMu.Unlock() clientID := os.Getenv(clientIDEnv) if clientID == "" { clientID = uuid.New().String() } host := os.Getenv(hostEnv) if host == "" { host = defaultHost } port := defaultPort ports := os.Getenv(portEnv) if ports != "" { i, err := strconv.Atoi(ports) if err != nil { panic(err) } port = i } client = NewClient(WithClientID(clientID), WithBrokerHost(host), WithBrokerPort(port)) envClient = client return client }
vimgrsevmruntime_client.go
// Copyright 2019 VMware, Inc. // SPDX-License-Identifier: Apache License 2.0 package clients // This file is auto-generated. import ( "github.com/vmware/alb-sdk/go/models" "github.com/vmware/alb-sdk/go/session" ) // VIMgrSEVMRuntimeClient is a client for avi VIMgrSEVMRuntime resource type VIMgrSEVMRuntimeClient struct { aviSession *session.AviSession } // NewVIMgrSEVMRuntimeClient creates a new client for VIMgrSEVMRuntime resource func NewVIMgrSEVMRuntimeClient(aviSession *session.AviSession) *VIMgrSEVMRuntimeClient { return &VIMgrSEVMRuntimeClient{aviSession: aviSession} } func (client *VIMgrSEVMRuntimeClient) getAPIPath(uuid string) string { path := "api/vimgrsevmruntime" if uuid != "" { path += "/" + uuid } return path } // GetAll is a collection API to get a list of VIMgrSEVMRuntime objects func (client *VIMgrSEVMRuntimeClient) GetAll(options ...session.ApiOptionsParams) ([]*models.VIMgrSEVMRuntime, error) { var plist []*models.VIMgrSEVMRuntime err := client.aviSession.GetCollection(client.getAPIPath(""), &plist, options...) return plist, err } // Get an existing VIMgrSEVMRuntime by uuid func (client *VIMgrSEVMRuntimeClient) Get(uuid string, options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var obj *models.VIMgrSEVMRuntime err := client.aviSession.Get(client.getAPIPath(uuid), &obj, options...) return obj, err } // GetByName - Get an existing VIMgrSEVMRuntime by name func (client *VIMgrSEVMRuntimeClient) GetByName(name string, options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var obj *models.VIMgrSEVMRuntime err := client.aviSession.GetObjectByName("vimgrsevmruntime", name, &obj, options...) return obj, err } // GetObject - Get an existing VIMgrSEVMRuntime by filters like name, cloud, tenant // Api creates VIMgrSEVMRuntime object with every call. func (client *VIMgrSEVMRuntimeClient) GetObject(options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var obj *models.VIMgrSEVMRuntime newOptions := make([]session.ApiOptionsParams, len(options)+1) for i, p := range options { newOptions[i] = p } newOptions[len(options)] = session.SetResult(&obj) err := client.aviSession.GetObject("vimgrsevmruntime", newOptions...) return obj, err } // Create a new VIMgrSEVMRuntime object func (client *VIMgrSEVMRuntimeClient) Create(obj *models.VIMgrSEVMRuntime, options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var robj *models.VIMgrSEVMRuntime err := client.aviSession.Post(client.getAPIPath(""), obj, &robj, options...) return robj, err } // Update an existing VIMgrSEVMRuntime object func (client *VIMgrSEVMRuntimeClient) Update(obj *models.VIMgrSEVMRuntime, options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var robj *models.VIMgrSEVMRuntime path := client.getAPIPath(*obj.UUID) err := client.aviSession.Put(path, obj, &robj, options...) return robj, err } // Patch an existing VIMgrSEVMRuntime object specified using uuid // patchOp: Patch operation - add, replace, or delete // patch: Patch payload should be compatible with the models.VIMgrSEVMRuntime // or it should be json compatible of form map[string]interface{} func (client *VIMgrSEVMRuntimeClient) Patch(uuid string, patch interface{}, patchOp string, options ...session.ApiOptionsParams) (*models.VIMgrSEVMRuntime, error) { var robj *models.VIMgrSEVMRuntime path := client.getAPIPath(uuid) err := client.aviSession.Patch(path, patch, patchOp, &robj, options...) return robj, err } // Delete an existing VIMgrSEVMRuntime object with a given UUID func (client *VIMgrSEVMRuntimeClient) Delete(uuid string, options ...session.ApiOptionsParams) error { if len(options) == 0 { return client.aviSession.Delete(client.getAPIPath(uuid)) } else { return client.aviSession.DeleteObject(client.getAPIPath(uuid), options...) } } // DeleteByName - Delete an existing VIMgrSEVMRuntime object with a given name func (client *VIMgrSEVMRuntimeClient) DeleteByName(name string, options ...session.ApiOptionsParams) error { res, err := client.GetByName(name, options...) if err != nil
return client.Delete(*res.UUID, options...) } // GetAviSession func (client *VIMgrSEVMRuntimeClient) GetAviSession() *session.AviSession { return client.aviSession }
{ return err }
profile_change.rs
use crate::{ProfileChangeType, ProfileEventAttributes}; use serde::{Deserialize, Serialize}; /// Pre-defined keys in [`ProfileEventAttributes`] map #[non_exhaustive] pub struct ProfileEventAttributeKey; impl ProfileEventAttributeKey { /// Human-readable name pub const FRIENDLY_NAME: &'static str = "OCKAM_FN"; /// UTC timestamp pub const CREATION_DATE: &'static str = "OCKAM_CD"; } /// Individual change applied to profile. [`ProfileChangeEvent`] consists of one or more such changes #[derive(Serialize, Deserialize, Debug, Clone)] pub struct
{ version: u8, // TODO: Check attributes serialization attributes: ProfileEventAttributes, change_type: ProfileChangeType, } impl ProfileChange { /// Protocol version pub fn version(&self) -> u8 { self.version } /// User-specified attributes that will be saved with change pub fn attributes(&self) -> &ProfileEventAttributes { &self.attributes } /// Type of change along with type-specific data pub fn change_type(&self) -> &ProfileChangeType { &self.change_type } } impl ProfileChange { pub(crate) fn new( version: u8, attributes: ProfileEventAttributes, change_type: ProfileChangeType, ) -> Self { Self { version, attributes, change_type, } } }
ProfileChange
single_comment.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import sp import pp import fp import step2 import ts def sensplit(_src): return pp.sensplit(_src,pp.sendivs) argv = sys.argv if(len(argv) < 2): print 'we need an arguement' sys.exit(0) filename = argv[1] if(not os.path.isfile(filename)): print '\t\ttest file don\'t exist' sys.exit(0) plist = fp.readfile(filename)
for line in slist: r = r + line + '\n' fp.writefile('__tmp1.txt',r) if(os.path.isfile('__tmp.txt')): os.remove('__tmp.txt') pp.divword('__tmp1.txt','__tmp.txt') slist = fp.readfile('__tmp.txt') sl = [] tmp = [] i = 0 length = len(slist) while( i < length): sens = slist[i] i += 1 #print line line = step2.line_div(sens) tmp.append(line) #ts._print(tmp) rmp = [] for line in tmp: #print line rmp += sp.sentence(line) #print rmp for line in plist: print line for line in rmp: #print line if(line == []): continue if(line[0] == '' or line[3][0] == ''): continue print line[0],line[3][0],line[2][1]*line[3][2]
slist = [] for line in plist: slist += sensplit(line) r = ''
main.ed6c77e8ee3cca15d0e4.js
(window.webpackJsonp=window.webpackJsonp||[]).push([[1],{0:function(t,e,n){t.exports=n("zUnb")},crnd:function(t,e){function n(t){return Promise.resolve().then(function(){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e})}n.keys=function(){return[]},n.resolve=n,t.exports=n,n.id="crnd"},zUnb:function(t,e,n){"use strict";n.r(e);var r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function o(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var i=function(){return(i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function a(t,e,n,r){var o,i=arguments.length,a=i<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,r);else for(var u=t.length-1;u>=0;u--)(o=t[u])&&(a=(i<3?o(a):i>3?o(e,n,a):o(e,n))||a);return i>3&&a&&Object.defineProperty(e,n,a),a}function u(t,e){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function s(t){var e="function"==typeof Symbol&&t[Symbol.iterator],n=0;return e?e.call(t):{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}function l(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(u){o={error:u}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a}function c(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(l(arguments[e]));return t}var f=Array.isArray||function(t){return t&&"number"==typeof t.length};function p(t){return null!=t&&"object"==typeof t}function h(t){return"function"==typeof t}var d,v={e:{}};function g(){try{return d.apply(this,arguments)}catch(t){return v.e=t,v}}function y(t){return d=t,g}function m(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(t,e){return e+1+") "+t.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}m.prototype=Object.create(Error.prototype);var b=m,_=function(){function t(t){this.closed=!1,this._parent=null,this._parents=null,this._subscriptions=null,t&&(this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var t,e=!1;if(!this.closed){var n=this._parent,r=this._parents,o=this._unsubscribe,i=this._subscriptions;this.closed=!0,this._parent=null,this._parents=null,this._subscriptions=null;for(var a=-1,u=r?r.length:0;n;)n.remove(this),n=++a<u&&r[a]||null;if(h(o)&&y(o).call(this)===v&&(e=!0,t=t||(v.e instanceof b?w(v.e.errors):[v.e])),f(i))for(a=-1,u=i.length;++a<u;){var s=i[a];if(p(s)&&y(s.unsubscribe).call(s)===v){e=!0,t=t||[];var l=v.e;l instanceof b?t=t.concat(w(l.errors)):t.push(l)}}if(e)throw new b(t)}},t.prototype.add=function(e){if(!e||e===t.EMPTY)return t.EMPTY;if(e===this)return this;var n=e;switch(typeof e){case"function":n=new t(e);case"object":if(n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if("function"!=typeof n._addParent){var r=n;(n=new t)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+e+" added to Subscription.")}return(this._subscriptions||(this._subscriptions=[])).push(n),n._addParent(this),n},t.prototype.remove=function(t){var e=this._subscriptions;if(e){var n=e.indexOf(t);-1!==n&&e.splice(n,1)}},t.prototype._addParent=function(t){var e=this._parent,n=this._parents;e&&e!==t?n?-1===n.indexOf(t)&&n.push(t):this._parents=[t]:this._parent=t},t.EMPTY=((e=new t).closed=!0,e),t}();function w(t){return t.reduce(function(t,e){return t.concat(e instanceof b?e.errors:e)},[])}var C=!1,S={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){C=t},get useDeprecatedSynchronousErrorHandling(){return C}};function E(t){setTimeout(function(){throw t})}var x={closed:!0,next:function(t){},error:function(t){if(S.useDeprecatedSynchronousErrorHandling)throw t;E(t)},complete:function(){}},T="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),k=function(t){function e(n,r,o){var i=t.call(this)||this;switch(i.syncErrorValue=null,i.syncErrorThrown=!1,i.syncErrorThrowable=!1,i.isStopped=!1,i._parentSubscription=null,arguments.length){case 0:i.destination=x;break;case 1:if(!n){i.destination=x;break}if("object"==typeof n){n instanceof e?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new A(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new A(i,n,r,o)}return i}return o(e,t),e.prototype[T]=function(){return this},e.create=function(t,n,r){var o=new e(t,n,r);return o.syncErrorThrowable=!1,o},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parent,e=this._parents;return this._parent=null,this._parents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parent=t,this._parents=e,this._parentSubscription=null,this},e}(_),A=function(t){function e(e,n,r,o){var i,a=t.call(this)||this;a._parentSubscriber=e;var u=a;return h(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==x&&(h((u=Object.create(n)).unsubscribe)&&a.add(u.unsubscribe.bind(u)),u.unsubscribe=a.unsubscribe.bind(a))),a._context=u,a._next=i,a._error=r,a._complete=o,a}return o(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;S.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=S.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):E(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;E(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};S.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(n){if(this.unsubscribe(),S.useDeprecatedSynchronousErrorHandling)throw n;E(n)}},e.prototype.__tryOrSetError=function(t,e,n){if(!S.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(r){return S.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=r,t.syncErrorThrown=!0,!0):(E(r),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(k),O="function"==typeof Symbol&&Symbol.observable||"@@observable";function P(){}function I(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return N(t)}function N(t){return t?1===t.length?t[0]:function(e){return t.reduce(function(t,e){return e(t)},e)}:P}var R=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,o=function(t,e,n){if(t){if(t instanceof k)return t;if(t[T])return t[T]()}return t||e||n?new k(t,e,n):new k(x)}(t,e,n);if(r?r.call(o,this.source):o.add(this.source||S.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),S.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){S.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),function(t){for(;t;){var e=t.destination;if(t.closed||t.isStopped)return!1;t=e&&e instanceof k?e:null}return!0}(t)?t.error(e):console.warn(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=D(e))(function(e,r){var o;o=n.subscribe(function(e){try{t(e)}catch(n){r(n),o&&o.unsubscribe()}},r,e)})},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[O]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 0===t.length?this:N(t)(this)},t.prototype.toPromise=function(t){var e=this;return new(t=D(t))(function(t,n){var r;e.subscribe(function(t){return r=t},function(t){return n(t)},function(){return t(r)})})},t.create=function(e){return new t(e)},t}();function D(t){if(t||(t=S.Promise||Promise),!t)throw new Error("no Promise impl found");return t}function V(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}V.prototype=Object.create(Error.prototype);var M=V,j=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return o(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(_),U=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return o(e,t),e}(k),L=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return o(e,t),e.prototype[T]=function(){return new U(this)},e.prototype.lift=function(t){var e=new H(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new M;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),o=0;o<n;o++)r[o].next(t)},e.prototype.error=function(t){if(this.closed)throw new M;this.hasError=!0,this.thrownError=t,this.isStopped=!0;for(var e=this.observers,n=e.length,r=e.slice(),o=0;o<n;o++)r[o].error(t);this.observers.length=0},e.prototype.complete=function(){if(this.closed)throw new M;this.isStopped=!0;for(var t=this.observers,e=t.length,n=t.slice(),r=0;r<e;r++)n[r].complete();this.observers.length=0},e.prototype.unsubscribe=function(){this.isStopped=!0,this.closed=!0,this.observers=null},e.prototype._trySubscribe=function(e){if(this.closed)throw new M;return t.prototype._trySubscribe.call(this,e)},e.prototype._subscribe=function(t){if(this.closed)throw new M;return this.hasError?(t.error(this.thrownError),_.EMPTY):this.isStopped?(t.complete(),_.EMPTY):(this.observers.push(t),new j(this,t))},e.prototype.asObservable=function(){var t=new R;return t.source=this,t},e.create=function(t,e){return new H(t,e)},e}(R),H=function(t){function e(e,n){var r=t.call(this)||this;return r.destination=e,r.source=n,r}return o(e,t),e.prototype.next=function(t){var e=this.destination;e&&e.next&&e.next(t)},e.prototype.error=function(t){var e=this.destination;e&&e.error&&this.destination.error(t)},e.prototype.complete=function(){var t=this.destination;t&&t.complete&&this.destination.complete()},e.prototype._subscribe=function(t){return this.source?this.source.subscribe(t):_.EMPTY},e}(L);function F(t){return t&&"function"==typeof t.schedule}var z=function(t){function e(e,n,r){var o=t.call(this)||this;return o.parent=e,o.outerValue=n,o.outerIndex=r,o.index=0,o}return o(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(k),q=function(t){return function(e){for(var n=0,r=t.length;n<r&&!e.closed;n++)e.next(t[n]);e.closed||e.complete()}},B=function(t){return function(e){return t.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,E),e}};function G(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var Z=G(),Q=function(t){return function(e){for(var n=t[Z]();;){var r=n.next();if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add(function(){n.return&&n.return()}),e}},W=function(t){return function(e){var n=t[O]();if("function"!=typeof n.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return n.subscribe(e)}},Y=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t};function K(t){return t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}var $=function(t){if(t instanceof R)return function(e){return t._isScalar?(e.next(t.value),void e.complete()):t.subscribe(e)};if(t&&"function"==typeof t[O])return W(t);if(Y(t))return q(t);if(K(t))return B(t);if(t&&"function"==typeof t[Z])return Q(t);var e=p(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+e+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")};function J(t,e,n,r,o){if(void 0===o&&(o=new z(t,n,r)),!o.closed)return $(e)(o)}var X=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(k);function tt(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new et(t,e))}}var et=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new nt(t,this.project,this.thisArg))},t}(),nt=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return o(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(n){return void this.destination.error(n)}this.destination.next(e)},e}(k);function rt(t,e){return new R(e?function(n){var r=new _,o=0;return r.add(e.schedule(function(){o!==t.length?(n.next(t[o++]),n.closed||r.add(this.schedule())):n.complete()})),r}:q(t))}function ot(t,e){if(!e)return t instanceof R?t:new R($(t));if(null!=t){if(function(t){return t&&"function"==typeof t[O]}(t))return function(t,e){return new R(e?function(n){var r=new _;return r.add(e.schedule(function(){var o=t[O]();r.add(o.subscribe({next:function(t){r.add(e.schedule(function(){return n.next(t)}))},error:function(t){r.add(e.schedule(function(){return n.error(t)}))},complete:function(){r.add(e.schedule(function(){return n.complete()}))}}))})),r}:W(t))}(t,e);if(K(t))return function(t,e){return new R(e?function(n){var r=new _;return r.add(e.schedule(function(){return t.then(function(t){r.add(e.schedule(function(){n.next(t),r.add(e.schedule(function(){return n.complete()}))}))},function(t){r.add(e.schedule(function(){return n.error(t)}))})})),r}:B(t))}(t,e);if(Y(t))return rt(t,e);if(function(t){return t&&"function"==typeof t[Z]}(t)||"string"==typeof t)return function(t,e){if(!t)throw new Error("Iterable cannot be null");return new R(e?function(n){var r,o=new _;return o.add(function(){r&&"function"==typeof r.return&&r.return()}),o.add(e.schedule(function(){r=t[Z](),o.add(e.schedule(function(){if(!n.closed){var t,e;try{var o=r.next();t=o.value,e=o.done}catch(i){return void n.error(i)}e?n.complete():(n.next(t),this.schedule())}}))})),o}:Q(t))}(t,e)}throw new TypeError((null!==t&&typeof t||t)+" is not observable")}function it(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(it(function(n,r){return ot(t(n,r)).pipe(tt(function(t,o){return e(n,t,r,o)}))},n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new at(t,n))})}var at=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new ut(t,this.project,this.concurrent))},t}(),ut=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=t.call(this,e)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return o(e,t),e.prototype._next=function(t){this.active<this.concurrent?this._tryNext(t):this.buffer.push(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(r){return void this.destination.error(r)}this.active++,this._innerSub(e,t,n)},e.prototype._innerSub=function(t,e,n){var r=new z(this,void 0,void 0);this.destination.add(r),J(this,t,e,n,r)},e.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},e.prototype.notifyNext=function(t,e,n,r,o){this.destination.next(e)},e.prototype.notifyComplete=function(t){var e=this.buffer;this.remove(t),this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(X);function st(t){return t}function lt(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),it(st,t)}function ct(){return function(t){return t.lift(new ft(t))}}var ft=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new pt(t,n),o=e.subscribe(r);return r.closed||(r.connection=n.connect()),o},t}(),pt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return o(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(k),ht=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return o(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new _).add(this.source.subscribe(new vt(this.getSubject(),this))),t.closed?(this._connection=null,t=_.EMPTY):this._connection=t),t},e.prototype.refCount=function(){return ct()(this)},e}(R).prototype,dt={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:ht._subscribe},_isComplete:{value:ht._isComplete,writable:!0},getSubject:{value:ht.getSubject},connect:{value:ht.connect},refCount:{value:ht.refCount}},vt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return o(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(U);function gt(){return new L}function yt(t){for(var e in t)if(t[e]===yt)return e;throw Error("Could not find renamed property on target object.")}var mt=yt({ngComponentDef:yt}),bt=yt({ngInjectableDef:yt}),_t=yt({ngInjectorDef:yt}),wt=yt({ngModuleDef:yt}),Ct=yt({__NG_ELEMENT_ID__:yt});function St(t){return{providedIn:t.providedIn||null,factory:t.factory,value:void 0}}function Et(t){return t&&t.hasOwnProperty(bt)?t[bt]:null}function xt(t){return t&&t.hasOwnProperty(_t)?t[_t]:null}var Tt=function(){function t(t,e){this._desc=t,this.ngMetadataName="InjectionToken",this.ngInjectableDef=void 0!==e?St({providedIn:e.providedIn||"root",factory:e.factory}):void 0}return t.prototype.toString=function(){return"InjectionToken "+this._desc},t}(),kt="__parameters__";function At(t,e,n){var r=function(t){return function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];if(t){var r=t.apply(void 0,c(e));for(var o in r)this[o]=r[o]}}}(e);function o(){for(var t,e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];if(this instanceof o)return r.apply(this,e),this;var i=new((t=o).bind.apply(t,c([void 0],e)));return a.annotation=i,a;function a(t,e,n){for(var r=t.hasOwnProperty(kt)?t[kt]:Object.defineProperty(t,kt,{value:[]})[kt];r.length<=n;)r.push(null);return(r[n]=r[n]||[]).push(i),t}}return n&&(o.prototype=Object.create(n.prototype)),o.prototype.ngMetadataName=t,o.annotationCls=o,o}var Ot=new Tt("AnalyzeForEntryComponents"),Pt="undefined"!=typeof window&&window,It="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Nt="undefined"!=typeof global&&global||Pt||It,Rt=Promise.resolve(0),Dt=null;function Vt(){if(!Dt){var t=Nt.Symbol;if(t&&t.iterator)Dt=t.iterator;else for(var e=Object.getOwnPropertyNames(Map.prototype),n=0;n<e.length;++n){var r=e[n];"entries"!==r&&"size"!==r&&Map.prototype[r]===Map.prototype.entries&&(Dt=r)}}return Dt}function Mt(t){"undefined"==typeof Zone?Rt.then(function(){t&&t.apply(null,null)}):Zone.current.scheduleMicroTask("scheduleMicrotask",t)}function jt(t,e){return t===e||"number"==typeof t&&"number"==typeof e&&isNaN(t)&&isNaN(e)}function Ut(t){if("string"==typeof t)return t;if(t instanceof Array)return"["+t.map(Ut).join(", ")+"]";if(null==t)return""+t;if(t.overriddenName)return""+t.overriddenName;if(t.name)return""+t.name;var e=t.toString();if(null==e)return""+e;var n=e.indexOf("\n");return-1===n?e:e.substring(0,n)}var Lt=yt({__forward_ref__:yt});function Ht(t){return t.__forward_ref__=Ht,t.toString=function(){return Ut(this())},t}function Ft(t){var e=t;return"function"==typeof e&&e.hasOwnProperty(Lt)&&e.__forward_ref__===Ht?e():t}var zt=function(t){return t[t.Emulated=0]="Emulated",t[t.Native=1]="Native",t[t.None=2]="None",t[t.ShadowDom=3]="ShadowDom",t}({}),qt=0,Bt=1,Gt=2,Zt=3,Qt=5,Wt=6,Yt=7,Kt=8,$t=9,Jt=10,Xt=11,te=12,ee=13,ne=15,re=17,oe=18,ie=0,ae=1,ue=6,se=8,le="__ngContext__",ce=8,fe=8,pe=9,he=-1,de=function(){return function(t,e,n){this.factory=t,this.resolving=!1,this.canSeeViewProviders=e,this.injectImpl=n}}(),ve=de.prototype;function ge(t){return"function"==typeof t?t.name||t:"string"==typeof t?t:null==t?"":"object"==typeof t&&"function"==typeof t.type?t.type.name||t.type:""+t}function ye(t){for(;Array.isArray(t);)t=t[Qt];return t}function me(t,e){return ye(e[t.index])}function be(t,e){var n=e[t];return n.length>=oe?n:n[Qt]}function _e(t){return null!==t.template}function we(t){return t[le]}function Ce(t){var e=we(t);return e?Array.isArray(e)?e:e.lView:null}function Se(t){return 32767&t}function Ee(t,e){for(var n=t>>16,r=e;n>0;)r=r[re],n--;return r}var xe=("undefined"!=typeof requestAnimationFrame&&requestAnimationFrame||setTimeout).bind(Nt);function Te(t){for(var e=t[Wt];e&&2===e.type;)e=(t=t[re])[Wt];return t}var ke,Ae,Oe,Pe,Ie=At("Inject",function(t){return{token:t}}),Ne=At("Optional"),Re=At("Self"),De=At("SkipSelf"),Ve=function(t){return t[t.Default=0]="Default",t[t.Host=1]="Host",t[t.Self=2]="Self",t[t.SkipSelf=4]="SkipSelf",t[t.Optional=8]="Optional",t}({}),Me=void 0;function je(t){var e=Me;return Me=t,e}function Ue(t){var e=ke;return ke=t,e}function Le(t,e){return void 0===e&&(e=Ve.Default),(ke||function(t,e){if(void 0===e&&(e=Ve.Default),void 0===Me)throw new Error("inject() must be called from an injection context");return null===Me?He(t,void 0,e):Me.get(t,e&Ve.Optional?null:void 0,e)})(t,e)}function He(t,e,n){var r=Et(t);if(r&&"root"==r.providedIn)return void 0===r.value?r.value=r.factory():r.value;if(n&Ve.Optional)return null;if(void 0!==e)return e;throw new Error("Injector: NOT_FOUND ["+Ut(t)+"]")}function Fe(t){for(var e=[],n=0;n<t.length;n++){var r=t[n];if(Array.isArray(r)){if(0===r.length)throw new Error("Arguments array must have arguments.");for(var o=void 0,i=Ve.Default,a=0;a<r.length;a++){var u=r[a];u instanceof Ne||"Optional"===u.ngMetadataName?i|=Ve.Optional:u instanceof De||"SkipSelf"===u.ngMetadataName?i|=Ve.SkipSelf:u instanceof Re||"Self"===u.ngMetadataName?i|=Ve.Self:o=u instanceof Ie?u.token:u}e.push(Le(o,i))}else e.push(Le(r))}return e}function ze(t,e,n){t.afterContentInit&&(e.contentHooks||(e.contentHooks=[])).push(n,t.afterContentInit),t.afterContentChecked&&((e.contentHooks||(e.contentHooks=[])).push(n,t.afterContentChecked),(e.contentCheckHooks||(e.contentCheckHooks=[])).push(n,t.afterContentChecked))}function qe(t,e,n){t.afterViewInit&&(e.viewHooks||(e.viewHooks=[])).push(n,t.afterViewInit),t.afterViewChecked&&((e.viewHooks||(e.viewHooks=[])).push(n,t.afterViewChecked),(e.viewCheckHooks||(e.viewCheckHooks=[])).push(n,t.afterViewChecked))}function Be(t,e,n){null!=t.onDestroy&&(e.destroyHooks||(e.destroyHooks=[])).push(n,t.onDestroy)}function Ge(t,e,n,r){if(!r){var o=2&t[Bt]?e:n;o&&Ze(t,o)}}function Ze(t,e){for(var n=0;n<e.length;n+=2)e[n+1].call(t[e[n]])}function Qe(){return Pe}function We(){return Ae}function Ye(t){Ae=t}function Ke(t,e){Ae=t,Pe=e}function $e(){return Oe}function Je(t){Oe=t}function Xe(t){return void 0===t&&(t=Pe),1==(1&t[Bt])}var tn=!1;function en(){return tn}function nn(t){tn=t}var rn=!0;function on(){return rn}function an(t){rn=t}function un(t,e){var n=Pe;t&&(rn=t[qt].firstTemplatePass);return Ae=e,Oe=!0,Pe=t,n}function sn(t){var e=Pe[qt];Xe(Pe)?Pe[Bt]&=-2:(Ge(Pe,e.viewHooks,e.viewCheckHooks,tn),Pe[Bt]&=-11,Pe[Bt]|=32,Pe[Yt]=e.bindingStartIndex),un(t,null)}var ln=!0;function cn(t){var e=ln;return ln=t,e}var fn=255,pn=0;function hn(t,e){t.push(0,0,0,0,0,0,0,0,e)}function dn(t,e){return-1===t.injectorIndex||t.parent&&t.parent.injectorIndex===t.injectorIndex||null==e[t.injectorIndex+fe]?-1:t.injectorIndex}function vn(t,e){if(t.parent&&-1!==t.parent.injectorIndex)return t.parent.injectorIndex;for(var n=e[Wt],r=1;n&&-1===n.injectorIndex;)n=(e=e[re])?e[Wt]:null,r++;return n?n.injectorIndex|r<<16:-1}var gn={};function yn(t,e,n,r,o,i){var a=e[qt],u=a.data[t+ce],s=function(t,e,n,r,o){for(var i=t.providerIndexes,a=e[qt].data,u=65535&i,s=t.directiveStart,l=i>>16,c=o?u+l:t.directiveEnd,f=r?u:u+l;f<c;f++){var p=a[f];if(f<s&&n===p||f>=s&&p.type===n)return f}if(o){var h=a[s];if(h&&_e(h)&&h.type===n)return s}return null}(u,e,n,null==r?function(t){return 1==(1&t.flags)}(u)&&ln:r!=a&&3===u.type,o&Ve.Host&&i===u);return null!==s?mn(a.data,e,s,u):gn}function mn(t,e,n,r){var o,i=e[n];if(null!=(o=i)&&"object"==typeof o&&Object.getPrototypeOf(o)==ve){var a=i;if(a.resolving)throw new Error("Circular dep for "+ge(t[n]));var u=cn(a.canSeeViewProviders);a.resolving=!0;var s=void 0;a.injectImpl&&(s=Ue(a.injectImpl));var l=We(),c=Qe();Ke(r,e);try{i=e[n]=a.factory(null,t,e,r)}finally{a.injectImpl&&Ue(s),cn(u),a.resolving=!1,Ke(l,c)}}return i}function bn(t,e,n){var r=64&t,o=32&t;return!!((128&t?r?o?n[e+7]:n[e+6]:o?n[e+5]:n[e+4]:r?o?n[e+3]:n[e+2]:o?n[e+1]:n[e])&1<<t)}function _n(t,e){return!(t&Ve.Self||t&Ve.Host&&e)}var wn=function(){function t(t,e){this._tNode=t,this._lView=e}return t.prototype.get=function(t,e){return function(t,e,n,r,o){if(void 0===r&&(r=Ve.Default),t){var i=function(t){if("string"==typeof t)return t.charCodeAt(0)||0;var e=t[Ct];return"number"==typeof e?e&fn:e}(n);if("function"==typeof i){var a=We(),u=Qe();Ke(t,e);try{var s=i();if(null!=s||r&Ve.Optional)return s;throw new Error("No provider for "+ge(n)+"!")}finally{Ke(a,u)}}else if("number"==typeof i){var l=null,c=dn(t,e),f=he,p=r&Ve.Host?Te(e)[Wt]:null;for((-1===c||r&Ve.SkipSelf)&&(f=-1===c?vn(t,e):e[c+fe],_n(r,!1)?(l=e[qt],c=Se(f),e=Ee(f,e)):c=-1);-1!==c;){f=e[c+fe];var h=e[qt];if(bn(i,c,h.data)){var d=yn(c,e,n,l,r,p);if(d!==gn)return d}_n(r,e[qt].data[c+ce]===p)&&bn(i,c,e)?(l=h,c=Se(f),e=Ee(f,e)):c=-1}}}if(r&Ve.Optional&&void 0===o&&(o=null),0==(r&(Ve.Self|Ve.Host))){var v=e[Jt];return v?v.get(n,o,r&Ve.Optional):He(n,o,r&Ve.Optional)}if(r&Ve.Optional)return o;throw new Error("NodeInjector: NOT_FOUND ["+ge(n)+"]")}(this._tNode,this._lView,t,void 0,e)},t}();function Cn(t,e){t[le]=e}var Sn=/([A-Z])/g;function En(t){try{return null!=t?t.toString().slice(0,30):t}catch(e){return"[ERROR] Exception while trying to serialize the value"}}function xn(t,e){var n=An(t),r=An(e);return n&&r?function(t,e,n){for(var r=t[Vt()](),o=e[Vt()]();;){var i=r.next(),a=o.next();if(i.done&&a.done)return!0;if(i.done||a.done)return!1;if(!n(i.value,a.value))return!1}}(t,e,xn):!(n||!t||"object"!=typeof t&&"function"!=typeof t||r||!e||"object"!=typeof e&&"function"!=typeof e)||jt(t,e)}var Tn=function(){function t(t){this.wrapped=t}return t.wrap=function(e){return new t(e)},t.unwrap=function(e){return t.isWrapped(e)?e.wrapped:e},t.isWrapped=function(e){return e instanceof t},t}(),kn=function(){function t(t,e,n){this.previousValue=t,this.currentValue=e,this.firstChange=n}return t.prototype.isFirstChange=function(){return this.firstChange},t}();function An(t){return!!On(t)&&(Array.isArray(t)||!(t instanceof Map)&&Vt()in t)}function On(t){return null!==t&&("function"==typeof t||"object"==typeof t)}var Pn={},In="ngProjectAs";function Nn(t){return!!t.listen}var Rn={createRenderer:function(t,e){return document}},Dn=[];function Vn(t,e,n,r,o){0===t?Nn(e)?e.insertBefore(n,r,o):n.insertBefore(r,o,!0):1===t?Nn(e)?e.removeChild(n,r):n.removeChild(r):2===t&&e.destroyNode(r)}function Mn(t){var e=t[qt].childIndex;return-1===e?null:t[e]}function jn(t,e){var n;return t.length>=oe&&(n=t[Wt])&&2===n.type?function(e,n){if(-1===e.index){var r=t[ne];return r>-1?t[Gt][r]:null}return t[Gt][e.parent.index]}(n):t[Gt]===e?null:t[Gt]}function Un(t){if(t.length>=oe){var e=t;!function(t){var e,n=t[qt];null!=n&&null!=(e=n.destroyHooks)&&Ze(t,e)}(e),(o=(r=e)[qt]&&r[qt].pipeDestroyHooks)&&Ze(r,o),function(t){var e=t[qt].cleanup;if(null!=e){for(var n=t[Kt],r=0;r<e.length-1;r+=2)if("string"==typeof e[r]){var o=n[e[r+2]],i=ye(t[e[r+1]]),a=e[r+3];"boolean"==typeof a?i.removeEventListener(e[r],o,a):a>=0?n[a]():n[-a].unsubscribe(),r+=2}else"number"==typeof e[r]?(0,n[e[r]])():e[r].call(n[e[r+1]]);t[Kt]=null}}(e);var n=e[Wt];n&&3===n.type&&Nn(e[te])&&e[te].destroy()}var r,o}var Ln="@",Hn=Promise.resolve(null);function Fn(t){var e=t[qt];if(e.firstTemplatePass=!1,an(!1),!Xe(t)){var n=en();(function(t,e,n){!n&&32&t[Bt]&&(Ge(t,e.initHooks,e.checkHooks,n),t[Bt]&=-33)})(t,e,n),function(t){for(var e=Mn(t);null!==e;e=e[Zt])if(e.length<oe&&-1===e[ie])for(var n=e,r=0;r<n[ae].length;r++){var o=n[ae][r];Bn(o,o[qt],o[$t])}}(t),function(t){if(null!=t.contentQueries)for(var e=0;e<t.contentQueries.length;e+=2){var n=t.contentQueries[e];t.data[n].contentQueriesRefresh(n-oe,t.contentQueries[e+1])}}(e),Ge(t,e.contentHooks,e.contentCheckHooks,n),function(t,e){if(t.expandoInstructions)for(var n=e[Yt]=t.expandoStartIndex,r=-1,o=-1,i=0;i<t.expandoInstructions.length;i++){var a=t.expandoInstructions[i];if("number"==typeof a)if(a<=0){o=-a;var u=t.expandoInstructions[++i];r=n+=pe+u}else n+=a;else null!==a&&(e[Yt]=n,a(2,ye(e[r]),o)),r++}}(e,t)}!function(t){if(null!=t)for(var e=0;e<t.length;e++)void 0,void 0,16==(16&(n=be(t[e],Qe()))[Bt])&&12&n[Bt]&&(function(t){for(var e=t[qt],n=t.length;n<e.blueprint.length;n++)t[n]=e.blueprint[n]}(n),tr(n,n[$t]));var n}(e.components)}function zn(t,e,n,r,o,i,a,u){var s=e.blueprint.slice();return s[Bt]=51|r,s[Gt]=s[re]=t,s[$t]=n,s[Xt]=o||t&&t[Xt],s[te]=i||t&&t[te],s[ee]=a||t&&t[ee]||null,s[Jt]=u||t&&t[Jt]||null,s}function qn(t,e,n,r,o){var i=Qe(),a=i[qt],u=t+oe;i[u]=n;var s=a.data[u];null==s&&(s=a.data[u]=Kn(i,e,u,r,o,null));var l=We(),c=$e();return l&&(!c||null!=l.child||null===s.parent&&2!==l.type?c||(l.next=s):l.child=s),null==a.firstChild&&(a.firstChild=s),Ye(s),Je(!0),s}function Bn(t,e,n){var r,o=$e(),i=We();if(Je(!0),Ye(null),128&t[Bt])$n(function(t){for(var e=Array.isArray(t)?t:Ce(t);e&&!(128&e[Bt]);)e=e[Gt];return e}(t)[$t]);else try{Je(!0),Ye(null),r=un(t,t[Wt]),Wn(),e.template(Zn(t),n),t[qt].firstTemplatePass=!1,an(!1),Fn(t)}finally{sn(r),Je(o),Ye(i)}}function Gn(t,e,n){var r=t[Xt],o=un(t,t[Wt]),i=!en();try{i&&r.begin&&r.begin(),Xe(t)&&(n&&(Wn(),n(1,e)),Fn(t),t[Bt]&=-2),n&&n(2,e),Fn(t)}finally{i&&r.end&&r.end(),sn(o)}}function Zn(t){return Xe(t)?1:2}var Qn=null;function Wn(){Qn=null}function Yn(t,e,n,r,o,i,a){var u=oe+n,s=u+r,l=function(t,e){var n=new Array(e).fill(null,0,t).fill(Pn,t);return n[ne]=-1,n[Yt]=t,n}(u,s);return l[qt]={id:t,blueprint:l,template:e,viewQuery:a,node:null,data:l.slice(),childIndex:-1,bindingStartIndex:u,expandoStartIndex:s,expandoInstructions:null,firstTemplatePass:!0,initHooks:null,checkHooks:null,contentHooks:null,contentCheckHooks:null,viewHooks:null,viewCheckHooks:null,destroyHooks:null,pipeDestroyHooks:null,cleanup:null,contentQueries:null,components:null,directiveRegistry:"function"==typeof o?o():o,pipeRegistry:"function"==typeof i?i():i,firstChild:null}}function Kn(t,e,n,r,o,i){var a=We(),u=$e()?a:a&&a.parent,s=u&&t&&u!==t[Wt]?u:null;return{type:e,index:n,injectorIndex:s?s.injectorIndex:-1,directiveStart:-1,directiveEnd:-1,flags:0,providerIndexes:0,tagName:r,attrs:o,localNames:null,initialInputs:void 0,inputs:void 0,outputs:void 0,tViews:i,next:null,child:null,parent:s,detached:null,stylingTemplate:null,projection:null}}function $n(t){for(var e=0;e<t.components.length;e++){var n=t.components[e];Gn(Ce(n),n)}}function Jn(t,e){var n=t[Xt];n.begin&&n.begin(),Xe(t)&&tr(t,e),tr(t,e),n.end&&n.end()}function Xn(t){$n(t[$t])}function tr(t,e){var n=t[qt],r=un(t,t[Wt]),o=n.template,i=n.viewQuery;try{Wn(),function(e,n,r){e&&Xe(t)&&e(1,r)}(i,0,e),o(Zn(t),e),Fn(t),function(e,n,r){e&&!Xe(t)&&e(2,r)}(i,0,e)}finally{sn(r)}}var er=Hn;function nr(t,e,n,r,o,i){Oe=!1,Ae=null;var a,u=n[qt],s=zn(n,(a=e.template).ngPrivateData||(a.ngPrivateData=Yn(-1,a,e.consts,e.vars,e.directiveDefs,e.pipeDefs,e.viewQuery)),null,e.onPush?8:4,r,o,i),l=qn(0,3,t,null,null);return u.firstTemplatePass&&(function(t,e,n){var r="string"!=typeof n?n[Ct]:n.charCodeAt(0)||0;null==r&&(r=n[Ct]=pn++);var o=r&fn,i=1<<o,a=64&o,u=32&o,s=e.data;128&o?a?u?s[t+7]|=i:s[t+6]|=i:u?s[t+5]|=i:s[t+4]|=i:a?u?s[t+3]|=i:s[t+2]|=i:u?s[t+1]|=i:s[t]|=i}(function(t,e){var n=dn(t,e);if(-1!==n)return n;var r=e[qt];r.firstTemplatePass&&(t.injectorIndex=e.length,hn(r.data,t),hn(e,null),hn(r.blueprint,null));var o=vn(t,e),i=Se(o),a=Ee(o,e),u=t.injectorIndex;if(o!==he)for(var s=a[qt].data,l=0;l<8;l++)e[u+l]=a[i+l]|s[i+l];return e[u+fe]=o,u}(l,n),n[qt],e.type),l.flags=1,function(t,e,n){t.flags=1&t.flags,t.directiveStart=e,t.directiveEnd=e+1,t.providerIndexes=e}(l,n.length),function(t){var e=Qe()[qt];(e.components||(e.components=[])).push(t.index)}(l)),s[Qt]=n[oe],s[Wt]=l,n[oe]=s}function rr(t,e,n,r,o){var i=n[qt],a=function(t,e,n){var r=We();t.firstTemplatePass&&(n.providersResolver&&n.providersResolver(n),function(t,e,n){var o=-(r.index-oe),i=t.data.length-(65535&r.providerIndexes);(t.expandoInstructions||(t.expandoInstructions=[])).push(o,i,1)}(t),function(t,e,n,r){t.data.push(n);var o=new de(r,_e(n),null);t.blueprint.push(o),e.push(o)}(t,e,n,n.factory));var o=mn(t.data,e,e.length-1,r);return function(t,e,n,r){var o=me(e,t);Cn(n,t),o&&Cn(o,t),null!=r.attributes&&3==e.type&&function(t,e){for(var n=Qe()[te],r=Nn(n),o=0;o<e.length;){var i=e[o++];if("number"==typeof i){if(0!==i)break;var a=e[o++],u=e[o++],s=e[o++];r?n.setAttribute(t,u,s,a):t.setAttributeNS(a,u,s)}else s=e[o++],i!==In&&(i[0]===Ln?r&&n.setProperty(t,i,s):r?n.setAttribute(t,i,s):t.setAttribute(i,s))}}(o,r.attributes)}(e,r,o,n),o}(i,n,e);if(r.components.push(a),t[$t]=a,o&&o.forEach(function(t){return t(a,e)}),i.firstTemplatePass&&e.hostBindings){var u=We();e.hostBindings(1,a,u.index-oe)}return a}function or(t,e){return{components:[],scheduler:t||xe,clean:er,playerHandler:e||null,flags:0}}function ir(t,e){var n,r,o,i,a=Ce(t)[qt],u=a.data.length-1;n=u,o=e.doCheck,i=a,(r=e.onInit)&&(i.initHooks||(i.initHooks=[])).push(n,r),o&&((i.initHooks||(i.initHooks=[])).push(n,o),(i.checkHooks||(i.checkHooks=[])).push(n,o)),function(t,e){if(t.firstTemplatePass)for(var n=e.directiveStart,r=e.directiveEnd;n<r;n++){var o=t.data[n];ze(o,t,n),qe(o,t,n),Be(o,t,n)}}(a,{directiveStart:u,directiveEnd:u+1})}function ar(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e]}var ur="__source",sr=new Object,lr=sr,cr=new Tt("INJECTOR"),fr=function(){function t(){}return t.prototype.get=function(t,e){if(void 0===e&&(e=sr),e===sr)throw new Error("NullInjectorError: No provider for "+Ut(t)+"!");return e},t}(),pr=function(){function t(){}return t.create=function(t,e){return Array.isArray(t)?new Cr(t,e):new Cr(t.providers,t.parent,t.name||null)},t.THROW_IF_NOT_FOUND=sr,t.NULL=new fr,t.ngInjectableDef=St({providedIn:"any",factory:function(){return Le(cr)}}),t.__NG_ELEMENT_ID__=function(){return hr()},t}(),hr=ar,dr=function(t){return t},vr=[],gr=dr,yr=function(){return Array.prototype.slice.call(arguments)},mr=yt({provide:String,useValue:yt}),br=pr.NULL,_r=/\n/gm,wr="\u0275",Cr=function(){function t(t,e,n){void 0===e&&(e=br),void 0===n&&(n=null),this.parent=e,this.source=n;var r=this._records=new Map;r.set(pr,{token:pr,fn:dr,deps:vr,value:this,useNew:!1}),r.set(cr,{token:cr,fn:dr,deps:vr,value:this,useNew:!1}),function t(e,n){if(n)if((n=Ft(n))instanceof Array)for(var r=0;r<n.length;r++)t(e,n[r]);else{if("function"==typeof n)throw xr("Function/Class not supported",n);if(!n||"object"!=typeof n||!n.provide)throw xr("Unexpected provider",n);var o=Ft(n.provide),i=function(t){var e=function(t){var e=vr,n=t.deps;if(n&&n.length){e=[];for(var r=0;r<n.length;r++){var o=6;if((s=Ft(n[r]))instanceof Array)for(var i=0,a=s;i<a.length;i++){var u=a[i];u instanceof Ne||u==Ne?o|=1:u instanceof De||u==De?o&=-3:u instanceof Re||u==Re?o&=-5:s=u instanceof Ie?u.token:Ft(u)}e.push({token:s,options:o})}}else if(t.useExisting){var s;e=[{token:s=Ft(t.useExisting),options:6}]}else if(!(n||mr in t))throw xr("'deps' required",t);return e}(t),n=dr,r=vr,o=!1,i=Ft(t.provide);if(mr in t)r=t.useValue;else if(t.useFactory)n=t.useFactory;else if(t.useExisting);else if(t.useClass)o=!0,n=Ft(t.useClass);else{if("function"!=typeof i)throw xr("StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable",t);o=!0,n=i}return{deps:e,fn:n,useNew:o,value:r}}(n);if(!0===n.multi){var a=e.get(o);if(a){if(a.fn!==yr)throw Sr(o)}else e.set(o,a={token:n.provide,deps:[],useNew:!1,fn:yr,value:vr});a.deps.push({token:o=n,options:6})}var u=e.get(o);if(u&&u.fn==yr)throw Sr(o);e.set(o,i)}}(r,t)}return t.prototype.get=function(t,e,n){void 0===n&&(n=Ve.Default);var r=this._records.get(t);try{return function t(e,n,r,o,i,a){try{return function(e,n,r,o,i,a){var u,s;if(!n||a&Ve.SkipSelf)a&Ve.Self||(s=o.get(e,i,Ve.Default));else{if((s=n.value)==gr)throw Error(wr+"Circular dependency");if(s===vr){n.value=gr;var l=n.useNew,f=n.fn,p=n.deps,h=vr;if(p.length){h=[];for(var d=0;d<p.length;d++){var v=p[d],g=v.options,y=2&g?r.get(v.token):void 0;h.push(t(v.token,y,r,y||4&g?o:br,1&g?null:pr.THROW_IF_NOT_FOUND,Ve.Default))}}n.value=s=l?new((u=f).bind.apply(u,c([void 0],h))):f.apply(void 0,h)}}return s}(e,n,r,o,i,a)}catch(u){throw u instanceof Error||(u=new Error(u)),(u.ngTempTokenPath=u.ngTempTokenPath||[]).unshift(e),n&&n.value==gr&&(n.value=vr),u}}(t,r,this._records,this.parent,e,n)}catch(i){var o=i.ngTempTokenPath;throw t[ur]&&o.unshift(t[ur]),i.message=Er("\n"+i.message,o,this.source),i.ngTokenPath=o,i.ngTempTokenPath=null,i}},t.prototype.toString=function(){var t=[];return this._records.forEach(function(e,n){return t.push(Ut(n))}),"StaticInjector["+t.join(", ")+"]"},t}();function Sr(t){return xr("Cannot mix multi providers and regular providers",t)}function Er(t,e,n){void 0===n&&(n=null),t=t&&"\n"===t.charAt(0)&&t.charAt(1)==wr?t.substr(2):t;var r=Ut(e);if(e instanceof Array)r=e.map(Ut).join(" -> ");else if("object"==typeof e){var o=[];for(var i in e)if(e.hasOwnProperty(i)){var a=e[i];o.push(i+":"+("string"==typeof a?JSON.stringify(a):Ut(a)))}r="{"+o.join(", ")+"}"}return"StaticInjectorError"+(n?"("+n+")":"")+"["+r+"]: "+t.replace(_r,"\n ")}function xr(t,e){return new Error(Er(t,e))}var Tr=new Tt("The presence of this token marks an injector as being the root injector."),kr={},Ar={},Or=[],Pr=void 0;function Ir(){return void 0===Pr&&(Pr=new fr),Pr}var Nr=function(){function t(t,e,n){var r=this;this.parent=n,this.records=new Map,this.injectorDefTypes=new Set,this.onDestroy=new Set,this.destroyed=!1;var o=[];Vr([t],function(t){return r.processInjectorType(t,[],o)}),e&&Vr(e,function(n){return r.processProvider(n,t,e)}),this.records.set(cr,Dr(void 0,this)),this.isRootInjector=this.records.has(Tr),this.injectorDefTypes.forEach(function(t){return r.get(t)})}return t.prototype.destroy=function(){this.assertNotDestroyed(),this.destroyed=!0;try{this.onDestroy.forEach(function(t){return t.ngOnDestroy()})}finally{this.records.clear(),this.onDestroy.clear(),this.injectorDefTypes.clear()}},t.prototype.get=function(t,e,n){void 0===e&&(e=lr),void 0===n&&(n=Ve.Default),this.assertNotDestroyed();var r,o=je(this);try{if(!(n&Ve.SkipSelf)){var i=this.records.get(t);if(void 0===i){var a=("function"==typeof(r=t)||"object"==typeof r&&r instanceof Tt)&&Et(t);a&&this.injectableDefInScope(a)&&(i=Dr(Rr(t),kr),this.records.set(t,i))}if(void 0!==i)return this.hydrate(t,i)}return(n&Ve.Self?Ir():this.parent).get(t,e)}finally{je(o)}},t.prototype.assertNotDestroyed=function(){if(this.destroyed)throw new Error("Injector has already been destroyed.")},t.prototype.processInjectorType=function(t,e,n){var r=this;if(t=Ft(t)){var o=xt(t),i=null==o&&t.ngModule||void 0,a=void 0===i?t:i,u=-1!==n.indexOf(a),s=void 0!==i&&t.providers||Or;if(void 0!==i&&(o=xt(i)),null!=o){if(this.injectorDefTypes.add(a),this.records.set(a,Dr(o.factory,kr)),null!=o.imports&&!u){n.push(a);try{Vr(o.imports,function(t){return r.processInjectorType(t,e,n)})}finally{}}var l=o.providers;if(null!=l&&!u){var c=t;Vr(l,function(t){return r.processProvider(t,c,l)})}var f=t.ngModule;Vr(s,function(t){return r.processProvider(t,f,s)})}}},t.prototype.processProvider=function(t,e,n){var r=jr(t=Ft(t))?t:Ft(t&&t.provide),o=function(t,e,n){var r=function(t,e,n){var r,o=void 0;if(jr(t))return Rr(Ft(t));if(Mr(t))o=function(){return Ft(t.useValue)};else if((r=t)&&r.useExisting)o=function(){return Le(Ft(t.useExisting))};else if(t&&t.useFactory)o=function(){return t.useFactory.apply(t,c(Fe(t.deps||[])))};else{var i=Ft(t&&(t.useClass||t.provide));if(!i){var a="";throw e&&n&&(a=" - only instances of Provider and Type are allowed, got: ["+n.map(function(e){return e==t?"?"+t+"?":"..."}).join(", ")+"]"),new Error("Invalid provider for the NgModule '"+Ut(e)+"'"+a)}if(!t.deps)return Rr(i);o=function(){return new(i.bind.apply(i,c([void 0],Fe(t.deps))))}}return o}(t,e,n);return Mr(t)?Dr(void 0,t.useValue):Dr(r,kr)}(t,e,n);if(jr(t)||!0!==t.multi){var i=this.records.get(r);if(i&&void 0!==i.multi)throw new Error("Mixed multi-provider for "+Ut(r))}else{var a=this.records.get(r);if(a){if(void 0===a.multi)throw new Error("Mixed multi-provider for "+r+".")}else(a=Dr(void 0,kr,!0)).factory=function(){return Fe(a.multi)},this.records.set(r,a);r=t,a.multi.push(t)}this.records.set(r,o)},t.prototype.hydrate=function(t,e){if(e.value===Ar)throw new Error("Cannot instantiate cyclic dependency! "+Ut(t));var n;return e.value===kr&&(e.value=Ar,e.value=e.factory()),"object"==typeof e.value&&e.value&&"object"==typeof(n=e.value)&&null!=n&&n.ngOnDestroy&&"function"==typeof n.ngOnDestroy&&this.onDestroy.add(e.value),e.value},t.prototype.injectableDefInScope=function(t){return!!t.providedIn&&("string"==typeof t.providedIn?"any"===t.providedIn||"root"===t.providedIn&&this.isRootInjector:this.injectorDefTypes.has(t.providedIn))},t}();function Rr(t){var e=Et(t);if(null===e){var n=xt(t);if(null!==n)return n.factory;if(t instanceof Tt)throw new Error("Token "+Ut(t)+" is missing an ngInjectableDef definition.");if(t instanceof Function){var r=t.length;if(r>0){var o=new Array(r).fill("?");throw new Error("Can't resolve all parameters for "+Ut(t)+": ("+o.join(", ")+").")}return function(){return new t}}throw new Error("unreachable")}return e.factory}function Dr(t,e,n){return void 0===n&&(n=!1),{factory:t,value:e,multi:n?[]:void 0}}function Vr(t,e){t.forEach(function(t){return Array.isArray(t)?Vr(t,e):e(t)})}function Mr(t){return t&&"object"==typeof t&&mr in t}function jr(t){return"function"==typeof t}var Ur=function(){return function(){}}(),Lr=function(){return function(){}}();function Hr(t){var e=Error("No component factory found for "+Ut(t)+". Did you add it to @NgModule.entryComponents?");return e[zr]=t,e}var Fr,zr="ngComponent",qr=function(){function t(){}return t.prototype.resolveComponentFactory=function(t){throw Hr(t)},t}(),Br=function(){function t(){}return t.NULL=new qr,t}(),Gr=function(){function t(t,e,n){this._parent=e,this._ngModule=n,this._factories=new Map;for(var r=0;r<t.length;r++){var o=t[r];this._factories.set(o.componentType,o)}}return t.prototype.resolveComponentFactory=function(t){var e=this._factories.get(t);if(!e&&this._parent&&(e=this._parent.resolveComponentFactory(t)),!e)throw Hr(t);return new Zr(e,this._ngModule)},t}(),Zr=function(t){function e(e,n){var r=t.call(this)||this;return r.factory=e,r.ngModule=n,r.selector=e.selector,r.componentType=e.componentType,r.ngContentSelectors=e.ngContentSelectors,r.inputs=e.inputs,r.outputs=e.outputs,r}return o(e,t),e.prototype.create=function(t,e,n,r){return this.factory.create(t,e,n,r||this.ngModule)},e}(Lr),Qr=function(){return function(){}}(),Wr=function(){return function(){}}(),Yr=function(t){function e(e){var n=t.call(this,e,null,-1)||this;return n._view=e,n}return o(e,t),e.prototype.detectChanges=function(){Xn(this._view)},e.prototype.checkNoChanges=function(){!function(t){nn(!0);try{Xn(t)}finally{nn(!1)}}(this._view)},Object.defineProperty(e.prototype,"context",{get:function(){return null},enumerable:!0,configurable:!0}),e}(function(){function t(t,e,n){this._context=e,this._componentIndex=n,this._appRef=null,this._viewContainerRef=null,this._tViewNode=null,this._lView=t}return Object.defineProperty(t.prototype,"rootNodes",{get:function(){return null==this._lView[Qt]?function t(e,n,r){for(var o=n.child;o;)r.push(me(o,e)),4===o.type&&t(e,o,r),o=o.next;return r}(this._lView,this._lView[Wt],[]):[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._context?this._context:this._lookUpContext()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"destroyed",{get:function(){return 64==(64&this._lView[Bt])},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){if(this._appRef)this._appRef.detachView(this);else if(this._viewContainerRef){var t=this._viewContainerRef.indexOf(this);t>-1&&this._viewContainerRef.detach(t),this._viewContainerRef=null}var e,n;Nn(n=(e=this._lView)[te])&&n.destroyNode&&function(t,n,r,o,i){for(var a=e[qt].node,u=-1,s=e,l=a.child;l;){var c=null;if(3===l.type){Vn(2,r,null,me(l,s),i);var f=s[l.index];v=f,Array.isArray(v)&&v.length===se&&Vn(2,r,null,f[ue],i)}else if(0===l.type){var p=s[l.index];Vn(2,r,null,p[ue],i),p[ae].length&&(c=(s=p[ae][0])[qt].node,i=p[ue])}else if(1===l.type){var h=Te(s),d=h[Wt].projection[l.projection];Dn[++u]=l,Dn[++u]=s,d&&(c=(s=h[Gt])[qt].data[d.index])}else c=l.child;if(null===c)for(null===l.next&&2&l.flags&&(s=Dn[u--],l=Dn[u--]),c=l.next;!c;){if(null===(l=l.parent||s[qt].node)||l===a)return null;0===l.type&&(i=(s=s[Gt])[l.index][ue]),c=2===l.type&&s[Zt]?(s=s[Zt])[qt].node:l.next}l=c}var v}(0,0,n),function(t){if(-1===t[qt].childIndex)return Un(t);for(var e=Mn(t);e;){var n=null;if(e.length>=oe?e[qt].childIndex>-1&&(n=Mn(e)):e[ae].length&&(n=e[ae][0]),null==n){for(;e&&!e[Zt]&&e!==t;)Un(e),e=jn(e,t);Un(e||t),n=e&&e[Zt]}e=n}}(e),e[Bt]|=64},t.prototype.onDestroy=function(t){var e,n;n=t,function(t){return t[Kt]||(t[Kt]=[])}(e=this._lView).push(n),e[qt].firstTemplatePass&&function(t){return t[qt].cleanup||(t[qt].cleanup=[])}(e).push(e[Kt].length-1,null)},t.prototype.markForCheck=function(){!function(t){for(;t&&!(128&t[Bt]);)t[Bt]|=8,t=t[Gt];var e,n,r;t[Bt]|=8,r=0===(e=t[$t]).flags,e.flags|=1,r&&e.clean==Hn&&(e.clean=new Promise(function(t){return n=t}),e.scheduler(function(){if(1&e.flags&&(e.flags&=-2,$n(e)),2&e.flags){e.flags&=-3;var t=e.playerHandler;t&&t.flushPlayers()}e.clean=Hn,n(null)}))}(this._lView)},t.prototype.detach=function(){this._lView[Bt]&=-17},t.prototype.reattach=function(){this._lView[Bt]|=16},t.prototype.detectChanges=function(){Jn(this._lView,this.context)},t.prototype.checkNoChanges=function(){!function(t){nn(!0);try{!function(t){Jn(function(t){var e,n=we(t);if(Array.isArray(n)){var r=function(t,e){var n=t[qt].components;if(n)for(var r=0;r<n.length;r++){var o=n[r];if(be(o,t)[$t]===e)return o}else if(be(oe,t)[$t]===e)return oe;return-1}(n,t);(o=function(t,e,n){return{lView:t,nodeIndex:e,native:n,component:void 0,directives:void 0,localRefs:void 0}}(n,r,(e=be(r,n))[Qt])).component=t,Cn(t,o),Cn(o.native,o)}else{var o;e=be((o=n).nodeIndex,o.lView)}return e}(t),t)}(t)}finally{nn(!1)}}(this.context)},t.prototype.attachToViewContainerRef=function(t){if(this._appRef)throw new Error("This view is already attached directly to the ApplicationRef!");this._viewContainerRef=t},t.prototype.detachFromAppRef=function(){this._appRef=null},t.prototype.attachToAppRef=function(t){if(this._viewContainerRef)throw new Error("This view is already attached to a ViewContainer!");this._appRef=t},t.prototype._lookUpContext=function(){return this._context=this._lView[Gt][this._componentIndex]},t}()),Kr=function(){function t(t){this.nativeElement=t}return t.__NG_ELEMENT_ID__=function(){return $r(t)},t}(),$r=ar,Jr=function(){return function(){}}(),Xr=function(){return function(){}}(),to=function(t){return t[t.Important=1]="Important",t[t.DashCase=2]="DashCase",t}({}),eo=function(){function t(){}return t.__NG_ELEMENT_ID__=function(){return no()},t}(),no=ar,ro=function(t){return t[t.NONE=0]="NONE",t[t.HTML=1]="HTML",t[t.STYLE=2]="STYLE",t[t.SCRIPT=3]="SCRIPT",t[t.URL=4]="URL",t[t.RESOURCE_URL=5]="RESOURCE_URL",t}({}),oo=function(){return function(){}}(),io=new(function(){return function(t){this.full=t,this.major=t.split(".")[0],this.minor=t.split(".")[1],this.patch=t.split(".").slice(2).join(".")}}())("7.2.2"),ao=function(t){function e(e){var n=t.call(this)||this;return n.ngModule=e,n}return o(e,t),e.prototype.resolveComponentFactory=function(t){return new fo(t[mt]||null,this.ngModule)},e}(Br);function uo(t){var e=[];for(var n in t)t.hasOwnProperty(n)&&e.push({propName:t[n],templateName:n});return e}var so=new Tt("ROOT_CONTEXT_TOKEN",{providedIn:"root",factory:function(){return or(Le(lo))}}),lo=new Tt("SCHEDULER_TOKEN",{providedIn:"root",factory:function(){return xe}}),co={},fo=function(t){function e(e,n){var r=t.call(this)||this;return r.componentDef=e,r.ngModule=n,r.componentType=e.type,r.selector=e.selectors[0][0],r.ngContentSelectors=[],r}return o(e,t),Object.defineProperty(e.prototype,"inputs",{get:function(){return uo(this.componentDef.inputs)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return uo(this.componentDef.outputs)},enumerable:!0,configurable:!0}),e.prototype.create=function(t,e,n,r){var i,a,u,s,l=void 0===n,c=(r=r||this.ngModule)?function(t,e){return{get:function(n,r){var o=t.get(n,co);return o!==co||r===co?o:e.get(n,r)}}}(t,r.injector):t,f=c.get(Xr,Rn),p=c.get(oo,null),h=l?(u=this.selector,Nn(s=f.createRenderer(null,this.componentDef)||Qe()[te])?s.createElement(u,Qn):null===Qn?s.createElement(u):s.createElementNS(Qn,u)):(i=n,a=f.createRenderer(null,null),"string"==typeof i?Nn(a)?a.selectRootElement(i):a.querySelector(i):i),d=this.componentDef.onPush?136:132,v=l?or():c.get(so),g=f.createRenderer(h,this.componentDef);n&&h&&(Nn(g)?g.setAttribute(h,"ng-version",io.full):h.setAttribute("ng-version",io.full));var y,m,b=zn(null,Yn(-1,null,1,0,null,null,null),v,d,f,g,p,c),_=un(b,null);try{f.begin&&f.begin();var w=nr(h,this.componentDef,b,f,g);if(m=b[qt].data[0+oe],e)for(var C=0,S=b[qt],E=m.projection=[],x=0;x<e.length;x++){for(var T=e[x],k=null,A=null,O=0;O<T.length;O++){S.firstTemplatePass&&(S.expandoStartIndex++,S.blueprint.splice(++C+oe,0,null),S.data.splice(C+oe,0,null),b.splice(C+oe,0,null));var P=qn(C,3,T[O],null,null);A?A.next=P:k=P,A=P}E.push(k)}y=rr(w,this.componentDef,b,v,[ir]),function(t,e,n){var r=t[qt],o=on();t[14]?t[14][Zt]=n:o&&(r.childIndex=e),t[14]=n}(b,oe,w),Fn(b)}finally{sn(_),f.end&&f.end()}var I=new po(this.componentType,y,function(t,e,n){return Fr||(Fr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e}(Kr)),new Fr(me(e,n))}(0,m,b),b,m);return l&&(I.hostView._tViewNode.child=m),I},e}(Lr),po=function(t){function e(e,n,r,o,i){var a,u=t.call(this)||this;return u.location=r,u._rootLView=o,u._tNode=i,u.destroyCbs=[],u.instance=n,u.hostView=u.changeDetectorRef=new Yr(o),u.hostView._tViewNode=(-1,null==(a=o)[qt].node&&(a[qt].node=Kn(a,2,-1,null,null,null)),a[Wt]=a[qt].node),u.componentType=e,u}return o(e,t),Object.defineProperty(e.prototype,"injector",{get:function(){return new wn(this._tNode,this._rootLView)},enumerable:!0,configurable:!0}),e.prototype.destroy=function(){this.destroyCbs.forEach(function(t){return t()}),this.destroyCbs=null,this.hostView.destroy()},e.prototype.onDestroy=function(t){this.destroyCbs.push(t)},e}(Ur),ho=!0,vo=!1;function go(){return vo=!0,ho}var yo=function(){function t(t){if(this.defaultDoc=t,this.inertDocument=this.defaultDoc.implementation.createHTMLDocument("sanitization-inert"),this.inertBodyElement=this.inertDocument.body,null==this.inertBodyElement){var e=this.inertDocument.createElement("html");this.inertDocument.appendChild(e),this.inertBodyElement=this.inertDocument.createElement("body"),e.appendChild(this.inertBodyElement)}this.inertBodyElement.innerHTML='<svg><g onload="this.parentNode.remove()"></g></svg>',!this.inertBodyElement.querySelector||this.inertBodyElement.querySelector("svg")?(this.inertBodyElement.innerHTML='<svg><p><style><img src="</style><img src=x onerror=alert(1)//">',this.getInertBodyElement=this.inertBodyElement.querySelector&&this.inertBodyElement.querySelector("svg img")&&function(){try{return!!window.DOMParser}catch(t){return!1}}()?this.getInertBodyElement_DOMParser:this.getInertBodyElement_InertDocument):this.getInertBodyElement=this.getInertBodyElement_XHR}return t.prototype.getInertBodyElement_XHR=function(t){t="<body><remove></remove>"+t+"</body>";try{t=encodeURI(t)}catch(r){return null}var e=new XMLHttpRequest;e.responseType="document",e.open("GET","data:text/html;charset=utf-8,"+t,!1),e.send(void 0);var n=e.response.body;return n.removeChild(n.firstChild),n},t.prototype.getInertBodyElement_DOMParser=function(t){t="<body><remove></remove>"+t+"</body>";try{var e=(new window.DOMParser).parseFromString(t,"text/html").body;return e.removeChild(e.firstChild),e}catch(n){return null}},t.prototype.getInertBodyElement_InertDocument=function(t){var e=this.inertDocument.createElement("template");return"content"in e?(e.innerHTML=t,e):(this.inertBodyElement.innerHTML=t,this.defaultDoc.documentMode&&this.stripCustomNsAttrs(this.inertBodyElement),this.inertBodyElement)},t.prototype.stripCustomNsAttrs=function(t){for(var e=t.attributes,n=e.length-1;0<n;n--){var r=e.item(n).name;"xmlns:ns1"!==r&&0!==r.indexOf("ns1:")||t.removeAttribute(r)}for(var o=t.firstChild;o;)o.nodeType===Node.ELEMENT_NODE&&this.stripCustomNsAttrs(o),o=o.nextSibling},t}(),mo=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:\/?#]*(?:[\/?#]|$))/gi,bo=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i;function _o(t){return(t=String(t)).match(mo)||t.match(bo)?t:(go()&&console.warn("WARNING: sanitizing unsafe URL value "+t+" (see http://g.co/ng/security#xss)"),"unsafe:"+t)}function wo(t){var e,n,r={};try{for(var o=s(t.split(",")),i=o.next();!i.done;i=o.next())r[i.value]=!0}catch(a){e={error:a}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(e)throw e.error}}return r}function Co(){for(var t,e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var o={};try{for(var i=s(n),a=i.next();!a.done;a=i.next()){var u=a.value;for(var l in u)u.hasOwnProperty(l)&&(o[l]=!0)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(e=i.return)&&e.call(i)}finally{if(t)throw t.error}}return o}var So,Eo=wo("area,br,col,hr,img,wbr"),xo=wo("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),To=wo("rp,rt"),ko=Co(To,xo),Ao=Co(Eo,Co(xo,wo("address,article,aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul")),Co(To,wo("a,abbr,acronym,audio,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video")),ko),Oo=wo("background,cite,href,itemtype,longdesc,poster,src,xlink:href"),Po=wo("srcset"),Io=Co(Oo,Po,wo("abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,valign,value,vspace,width")),No=function(){function t(){this.sanitizedSomething=!1,this.buf=[]}return t.prototype.sanitizeChildren=function(t){for(var e=t.firstChild,n=!0;e;)if(e.nodeType===Node.ELEMENT_NODE?n=this.startElement(e):e.nodeType===Node.TEXT_NODE?this.chars(e.nodeValue):this.sanitizedSomething=!0,n&&e.firstChild)e=e.firstChild;else for(;e;){e.nodeType===Node.ELEMENT_NODE&&this.endElement(e);var r=this.checkClobberedElement(e,e.nextSibling);if(r){e=r;break}e=this.checkClobberedElement(e,e.parentNode)}return this.buf.join("")},t.prototype.startElement=function(t){var e,n=t.nodeName.toLowerCase();if(!Ao.hasOwnProperty(n))return this.sanitizedSomething=!0,!1;this.buf.push("<"),this.buf.push(n);for(var r=t.attributes,o=0;o<r.length;o++){var i=r.item(o),a=i.name,u=a.toLowerCase();if(Io.hasOwnProperty(u)){var s=i.value;Oo[u]&&(s=_o(s)),Po[u]&&(e=s,s=(e=String(e)).split(",").map(function(t){return _o(t.trim())}).join(", ")),this.buf.push(" ",a,'="',Vo(s),'"')}else this.sanitizedSomething=!0}return this.buf.push(">"),!0},t.prototype.endElement=function(t){var e=t.nodeName.toLowerCase();Ao.hasOwnProperty(e)&&!Eo.hasOwnProperty(e)&&(this.buf.push("</"),this.buf.push(e),this.buf.push(">"))},t.prototype.chars=function(t){this.buf.push(Vo(t))},t.prototype.checkClobberedElement=function(t,e){if(e&&(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_CONTAINED_BY)===Node.DOCUMENT_POSITION_CONTAINED_BY)throw new Error("Failed to sanitize html because the element is clobbered: "+t.outerHTML);return e},t}(),Ro=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Do=/([^\#-~ |!])/g;function Vo(t){return t.replace(/&/g,"&amp;").replace(Ro,function(t){return"&#"+(1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320)+65536)+";"}).replace(Do,function(t){return"&#"+t.charCodeAt(0)+";"}).replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Mo(t){return"content"in t&&function(t){return t.nodeType===Node.ELEMENT_NODE&&"TEMPLATE"===t.nodeName}(t)?t.content:null}var jo={provide:Br,useClass:ao,deps:[Qr]},Uo=function(t){function e(e,n){var r=t.call(this)||this;r._parent=n,r._bootstrapComponents=[],r.injector=r,r.destroyCbs=[];var o=function(t,n){var r=e[wt]||null;return r}();return r._bootstrapComponents=o.bootstrap,r._r3Injector=function(t,e,n){return void 0===e&&(e=null),void 0===n&&(n=null),e=e||Ir(),new Nr(t,n,e)}(e,n,[{provide:Qr,useValue:r},jo]),r.instance=r.get(e),r}return o(e,t),e.prototype.get=function(t,e,n){return void 0===e&&(e=pr.THROW_IF_NOT_FOUND),void 0===n&&(n=Ve.Default),t===pr||t===Qr||t===cr?this:this._r3Injector.get(t,e,n)},Object.defineProperty(e.prototype,"componentFactoryResolver",{get:function(){return this.get(Br)},enumerable:!0,configurable:!0}),e.prototype.destroy=function(){this.destroyCbs.forEach(function(t){return t()}),this.destroyCbs=null},e.prototype.onDestroy=function(t){this.destroyCbs.push(t)},e}(Qr);!function(t){function e(e){var n=t.call(this)||this;return n.moduleType=e,n}o(e,t),e.prototype.create=function(t){return new Uo(this.moduleType,t)}}(Wr);var Lo=function(t){function e(e){void 0===e&&(e=!1);var n=t.call(this)||this;return n.__isAsync=e,n}return o(e,t),e.prototype.emit=function(e){t.prototype.next.call(this,e)},e.prototype.subscribe=function(e,n,r){var o,i=function(t){return null},a=function(){return null};e&&"object"==typeof e?(o=this.__isAsync?function(t){setTimeout(function(){return e.next(t)})}:function(t){e.next(t)},e.error&&(i=this.__isAsync?function(t){setTimeout(function(){return e.error(t)})}:function(t){e.error(t)}),e.complete&&(a=this.__isAsync?function(){setTimeout(function(){return e.complete()})}:function(){e.complete()})):(o=this.__isAsync?function(t){setTimeout(function(){return e(t)})}:function(t){e(t)},n&&(i=this.__isAsync?function(t){setTimeout(function(){return n(t)})}:function(t){n(t)}),r&&(a=this.__isAsync?function(){setTimeout(function(){return r()})}:function(){r()}));var u=t.prototype.subscribe.call(this,o,i,a);return e instanceof _&&e.add(u),u},e}(L),Ho=function(){function t(){}return t.__NG_ELEMENT_ID__=function(){return Fo(t,Kr)},t}(),Fo=ar,zo=new RegExp("^([-,.\"'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?|(?:repeating-)?(?:linear|radial)-gradient|(?:calc|attr))\\([-0-9.%, #a-zA-Z]+\\))$","g"),qo=/^url\(([^)]+)\)$/,Bo=function(){return function(){}}();Function,String,String;var Go="ngDebugContext",Zo="ngOriginalError",Qo="ngErrorLogger";function Wo(t){return t[Go]}function Yo(t){return t[Zo]}function Ko(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];t.error.apply(t,c(e))}var $o=function(){function t(){this._console=console}return t.prototype.handleError=function(t){var e=this._findOriginalError(t),n=this._findContext(t),r=function(t){return t[Qo]||Ko}(t);r(this._console,"ERROR",t),e&&r(this._console,"ORIGINAL ERROR",e),n&&r(this._console,"ERROR CONTEXT",n)},t.prototype._findContext=function(t){return t?Wo(t)?Wo(t):this._findContext(Yo(t)):null},t.prototype._findOriginalError=function(t){for(var e=Yo(t);e&&Yo(e);)e=Yo(e);return e},t}();function Jo(t){return!!t&&"function"==typeof t.then}function Xo(t){return!!t&&"function"==typeof t.subscribe}var ti=new Tt("Application Initializer"),ei=function(){function t(t){var e=this;this.appInits=t,this.initialized=!1,this.done=!1,this.donePromise=new Promise(function(t,n){e.resolve=t,e.reject=n})}return t.prototype.runInitializers=function(){var t=this;if(!this.initialized){var e=[],n=function(){t.done=!0,t.resolve()};if(this.appInits)for(var r=0;r<this.appInits.length;r++){var o=this.appInits[r]();Jo(o)&&e.push(o)}Promise.all(e).then(function(){n()}).catch(function(e){t.reject(e)}),0===e.length&&n(),this.initialized=!0}},t}(),ni=new Tt("AppId");function ri(){return""+oi()+oi()+oi()}function oi(){return String.fromCharCode(97+Math.floor(25*Math.random()))}var ii=new Tt("Platform Initializer"),ai=new Tt("Platform ID"),ui=new Tt("appBootstrapListener"),si=function(){function t(){}return t.prototype.log=function(t){console.log(t)},t.prototype.warn=function(t){console.warn(t)},t}();function li(){throw new Error("Runtime compiler is not loaded")}var ci,fi,pi=li,hi=li,di=li,vi=li,gi=function(){function t(){this.compileModuleSync=pi,this.compileModuleAsync=hi,this.compileModuleAndAllComponentsSync=di,this.compileModuleAndAllComponentsAsync=vi}return t.prototype.clearCache=function(){},t.prototype.clearCacheFor=function(t){},t.prototype.getModuleId=function(t){},t}(),yi=function(){return function(){}}();function mi(){var t=Nt.wtf;return!(!t||!(ci=t.trace)||(fi=ci.events,0))}var bi=mi();function _i(t,e){return null}var wi=bi?function(t,e){return void 0===e&&(e=null),fi.createScope(t,e)}:function(t,e){return _i},Ci=bi?function(t,e){return ci.leaveScope(t,e),e}:function(t,e){return e},Si=function(){function t(t){var e,n=t.enableLongStackTrace,r=void 0!==n&&n;if(this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new Lo(!1),this.onMicrotaskEmpty=new Lo(!1),this.onStable=new Lo(!1),this.onError=new Lo(!1),"undefined"==typeof Zone)throw new Error("In this configuration Angular requires Zone.js");Zone.assertZonePatched(),this._nesting=0,this._outer=this._inner=Zone.current,Zone.wtfZoneSpec&&(this._inner=this._inner.fork(Zone.wtfZoneSpec)),Zone.TaskTrackingZoneSpec&&(this._inner=this._inner.fork(new Zone.TaskTrackingZoneSpec)),r&&Zone.longStackTraceZoneSpec&&(this._inner=this._inner.fork(Zone.longStackTraceZoneSpec)),(e=this)._inner=e._inner.fork({name:"angular",properties:{isAngularZone:!0},onInvokeTask:function(t,n,r,o,i,a){try{return ki(e),t.invokeTask(r,o,i,a)}finally{Ai(e)}},onInvoke:function(t,n,r,o,i,a,u){try{return ki(e),t.invoke(r,o,i,a,u)}finally{Ai(e)}},onHasTask:function(t,n,r,o){t.hasTask(r,o),n===r&&("microTask"==o.change?(e.hasPendingMicrotasks=o.microTask,Ti(e)):"macroTask"==o.change&&(e.hasPendingMacrotasks=o.macroTask))},onHandleError:function(t,n,r,o){return t.handleError(r,o),e.runOutsideAngular(function(){return e.onError.emit(o)}),!1}})}return t.isInAngularZone=function(){return!0===Zone.current.get("isAngularZone")},t.assertInAngularZone=function(){if(!t.isInAngularZone())throw new Error("Expected to be in Angular Zone, but it is not!")},t.assertNotInAngularZone=function(){if(t.isInAngularZone())throw new Error("Expected to not be in Angular Zone, but it is!")},t.prototype.run=function(t,e,n){return this._inner.run(t,e,n)},t.prototype.runTask=function(t,e,n,r){var o=this._inner,i=o.scheduleEventTask("NgZoneEvent: "+r,t,xi,Ei,Ei);try{return o.runTask(i,e,n)}finally{o.cancelTask(i)}},t.prototype.runGuarded=function(t,e,n){return this._inner.runGuarded(t,e,n)},t.prototype.runOutsideAngular=function(t){return this._outer.run(t)},t}();function Ei(){}var xi={};function Ti(t){if(0==t._nesting&&!t.hasPendingMicrotasks&&!t.isStable)try{t._nesting++,t.onMicrotaskEmpty.emit(null)}finally{if(t._nesting--,!t.hasPendingMicrotasks)try{t.runOutsideAngular(function(){return t.onStable.emit(null)})}finally{t.isStable=!0}}}function ki(t){t._nesting++,t.isStable&&(t.isStable=!1,t.onUnstable.emit(null))}function Ai(t){t._nesting--,Ti(t)}var Oi,Pi=function(){function t(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new Lo,this.onMicrotaskEmpty=new Lo,this.onStable=new Lo,this.onError=new Lo}return t.prototype.run=function(t){return t()},t.prototype.runGuarded=function(t){return t()},t.prototype.runOutsideAngular=function(t){return t()},t.prototype.runTask=function(t){return t()},t}(),Ii=function(){function t(t){var e=this;this._ngZone=t,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),t.run(function(){e.taskTrackingZone="undefined"==typeof Zone?null:Zone.current.get("TaskTrackingZone")})}return t.prototype._watchAngularEvents=function(){var t=this;this._ngZone.onUnstable.subscribe({next:function(){t._didWork=!0,t._isZoneStable=!1}}),this._ngZone.runOutsideAngular(function(){t._ngZone.onStable.subscribe({next:function(){Si.assertNotInAngularZone(),Mt(function(){t._isZoneStable=!0,t._runCallbacksIfReady()})}})})},t.prototype.increasePendingRequestCount=function(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount},t.prototype.decreasePendingRequestCount=function(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error("pending async requests below zero");return this._runCallbacksIfReady(),this._pendingCount},t.prototype.isStable=function(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks},t.prototype._runCallbacksIfReady=function(){var t=this;if(this.isStable())Mt(function(){for(;0!==t._callbacks.length;){var e=t._callbacks.pop();clearTimeout(e.timeoutId),e.doneCb(t._didWork)}t._didWork=!1});else{var e=this.getPendingTasks();this._callbacks=this._callbacks.filter(function(t){return!t.updateCb||!t.updateCb(e)||(clearTimeout(t.timeoutId),!1)}),this._didWork=!0}},t.prototype.getPendingTasks=function(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(function(t){return{source:t.source,creationLocation:t.creationLocation,data:t.data}}):[]},t.prototype.addCallback=function(t,e,n){var r=this,o=-1;e&&e>0&&(o=setTimeout(function(){r._callbacks=r._callbacks.filter(function(t){return t.timeoutId!==o}),t(r._didWork,r.getPendingTasks())},e)),this._callbacks.push({doneCb:t,timeoutId:o,updateCb:n})},t.prototype.whenStable=function(t,e,n){if(n&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is "zone.js/dist/task-tracking.js" loaded?');this.addCallback(t,e,n),this._runCallbacksIfReady()},t.prototype.getPendingRequestCount=function(){return this._pendingCount},t.prototype.findProviders=function(t,e,n){return[]},t}(),Ni=function(){function t(){this._applications=new Map,Ri.addToWindow(this)}return t.prototype.registerApplication=function(t,e){this._applications.set(t,e)},t.prototype.unregisterApplication=function(t){this._applications.delete(t)},t.prototype.unregisterAllApplications=function(){this._applications.clear()},t.prototype.getTestability=function(t){return this._applications.get(t)||null},t.prototype.getAllTestabilities=function(){return Array.from(this._applications.values())},t.prototype.getAllRootElements=function(){return Array.from(this._applications.keys())},t.prototype.findTestabilityInTree=function(t,e){return void 0===e&&(e=!0),Ri.findTestabilityInTree(this,t,e)},a([u("design:paramtypes",[])],t)}(),Ri=new(function(){function t(){}return t.prototype.addToWindow=function(t){},t.prototype.findTestabilityInTree=function(t,e,n){return null},t}()),Di=new Tt("AllowMultipleToken"),Vi=function(){return function(t,e){this.name=t,this.token=e}}();function Mi(t,e,n){void 0===n&&(n=[]);var r="Platform: "+e,o=new Tt(r);return function(e){void 0===e&&(e=[]);var i=ji();if(!i||i.injector.get(Di,!1))if(t)t(n.concat(e).concat({provide:o,useValue:!0}));else{var a=n.concat(e).concat({provide:o,useValue:!0});!function(t){if(Oi&&!Oi.destroyed&&!Oi.injector.get(Di,!1))throw new Error("There can be only one platform. Destroy the previous one to create a new one.");Oi=t.get(Ui);var e=t.get(ii,null);e&&e.forEach(function(t){return t()})}(pr.create({providers:a,name:r}))}return function(t){var e=ji();if(!e)throw new Error("No platform exists!");if(!e.injector.get(t,null))throw new Error("A platform with a different configuration has been created. Please destroy it first.");return e}(o)}}function ji(){return Oi&&!Oi.destroyed?Oi:null}var Ui=function(){function t(t){this._injector=t,this._modules=[],this._destroyListeners=[],this._destroyed=!1}return t.prototype.bootstrapModuleFactory=function(t,e){var n,r=this,o="noop"===(n=e?e.ngZone:void 0)?new Pi:("zone.js"===n?void 0:n)||new Si({enableLongStackTrace:go()}),i=[{provide:Si,useValue:o}];return o.run(function(){var e=pr.create({providers:i,parent:r.injector,name:t.moduleType.name}),n=t.create(e),a=n.injector.get($o,null);if(!a)throw new Error("No ErrorHandler. Is platform module (BrowserModule) included?");return n.onDestroy(function(){return Fi(r._modules,n)}),o.runOutsideAngular(function(){return o.onError.subscribe({next:function(t){a.handleError(t)}})}),function(t,e,o){try{var i=((a=n.injector.get(ei)).runInitializers(),a.donePromise.then(function(){return r._moduleDoBootstrap(n),n}));return Jo(i)?i.catch(function(n){throw e.runOutsideAngular(function(){return t.handleError(n)}),n}):i}catch(u){throw e.runOutsideAngular(function(){return t.handleError(u)}),u}var a}(a,o)})},t.prototype.bootstrapModule=function(t,e){var n=this;void 0===e&&(e=[]);var r=Li({},e);return function(t,e,n){return t.get(yi).createCompiler([e]).compileModuleAsync(n)}(this.injector,r,t).then(function(t){return n.bootstrapModuleFactory(t,r)})},t.prototype._moduleDoBootstrap=function(t){var e=t.injector.get(Hi);if(t._bootstrapComponents.length>0)t._bootstrapComponents.forEach(function(t){return e.bootstrap(t)});else{if(!t.instance.ngDoBootstrap)throw new Error("The module "+Ut(t.instance.constructor)+' was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.');t.instance.ngDoBootstrap(e)}this._modules.push(t)},t.prototype.onDestroy=function(t){this._destroyListeners.push(t)},Object.defineProperty(t.prototype,"injector",{get:function(){return this._injector},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){if(this._destroyed)throw new Error("The platform has already been destroyed!");this._modules.slice().forEach(function(t){return t.destroy()}),this._destroyListeners.forEach(function(t){return t()}),this._destroyed=!0},Object.defineProperty(t.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!0,configurable:!0}),t}();function Li(t,e){return Array.isArray(e)?e.reduce(Li,t):i({},t,e)}var Hi=function(){function t(t,e,n,r,o,i){var a=this;this._zone=t,this._console=e,this._injector=n,this._exceptionHandler=r,this._componentFactoryResolver=o,this._initStatus=i,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._enforceNoNewChanges=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._enforceNoNewChanges=go(),this._zone.onMicrotaskEmpty.subscribe({next:function(){a._zone.run(function(){a.tick()})}});var u=new R(function(t){a._stable=a._zone.isStable&&!a._zone.hasPendingMacrotasks&&!a._zone.hasPendingMicrotasks,a._zone.runOutsideAngular(function(){t.next(a._stable),t.complete()})}),s=new R(function(t){var e;a._zone.runOutsideAngular(function(){e=a._zone.onStable.subscribe(function(){Si.assertNotInAngularZone(),Mt(function(){a._stable||a._zone.hasPendingMacrotasks||a._zone.hasPendingMicrotasks||(a._stable=!0,t.next(!0))})})});var n=a._zone.onUnstable.subscribe(function(){Si.assertInAngularZone(),a._stable&&(a._stable=!1,a._zone.runOutsideAngular(function(){t.next(!1)}))});return function(){e.unsubscribe(),n.unsubscribe()}});this.isStable=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Number.POSITIVE_INFINITY,r=null,o=t[t.length-1];return F(o)?(r=t.pop(),t.length>1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof o&&(n=t.pop()),null===r&&1===t.length&&t[0]instanceof R?t[0]:lt(n)(rt(t,r))}(u,s.pipe(function(t){return ct()((e=gt,function(t){var n;n="function"==typeof e?e:function(){return e};var r=Object.create(t,dt);return r.source=t,r.subjectFactory=n,r})(t));var e}))}var e;return e=t,t.prototype.bootstrap=function(t,e){var n,r=this;if(!this._initStatus.done)throw new Error("Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.");n=t instanceof Lr?t:this._componentFactoryResolver.resolveComponentFactory(t),this.componentTypes.push(n.componentType);var o=n instanceof Zr?null:this._injector.get(Qr),i=n.create(pr.NULL,[],e||n.selector,o);i.onDestroy(function(){r._unloadComponent(i)});var a=i.injector.get(Ii,null);return a&&i.injector.get(Ni).registerApplication(i.location.nativeElement,a),this._loadComponent(i),go()&&this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode."),i},t.prototype.tick=function(){var t=this;if(this._runningTick)throw new Error("ApplicationRef.tick is called recursively");var n=e._tickScope();try{this._runningTick=!0,this._views.forEach(function(t){return t.detectChanges()}),this._enforceNoNewChanges&&this._views.forEach(function(t){return t.checkNoChanges()})}catch(r){this._zone.runOutsideAngular(function(){return t._exceptionHandler.handleError(r)})}finally{this._runningTick=!1,Ci(n)}},t.prototype.attachView=function(t){var e=t;this._views.push(e),e.attachToAppRef(this)},t.prototype.detachView=function(t){var e=t;Fi(this._views,e),e.detachFromAppRef()},t.prototype._loadComponent=function(t){this.attachView(t.hostView),this.tick(),this.components.push(t),this._injector.get(ui,[]).concat(this._bootstrapListeners).forEach(function(e){return e(t)})},t.prototype._unloadComponent=function(t){this.detachView(t.hostView),Fi(this.components,t)},t.prototype.ngOnDestroy=function(){this._views.slice().forEach(function(t){return t.destroy()})},Object.defineProperty(t.prototype,"viewCount",{get:function(){return this._views.length},enumerable:!0,configurable:!0}),t._tickScope=wi("ApplicationRef#tick()"),t}();function Fi(t,e){var n=t.indexOf(e);n>-1&&t.splice(n,1)}var zi=function(){function t(){this.dirty=!0,this._results=[],this.changes=new Lo,this.length=0}return t.prototype.map=function(t){return this._results.map(t)},t.prototype.filter=function(t){return this._results.filter(t)},t.prototype.find=function(t){return this._results.find(t)},t.prototype.reduce=function(t,e){return this._results.reduce(t,e)},t.prototype.forEach=function(t){this._results.forEach(t)},t.prototype.some=function(t){return this._results.some(t)},t.prototype.toArray=function(){return this._results.slice()},t.prototype[Vt()]=function(){return this._results[Vt()]()},t.prototype.toString=function(){return this._results.toString()},t.prototype.reset=function(t){this._results=function t(e){return e.reduce(function(e,n){var r=Array.isArray(n)?t(n):n;return e.concat(r)},[])}(t),this.dirty=!1,this.length=this._results.length,this.last=this._results[this.length-1],this.first=this._results[0]},t.prototype.notifyOnChanges=function(){this.changes.emit(this)},t.prototype.setDirty=function(){this.dirty=!0},t.prototype.destroy=function(){this.changes.complete(),this.changes.unsubscribe()},t}(),qi=function(){return function(){}}(),Bi={factoryPathPrefix:"",factoryPathSuffix:".ngfactory"},Gi=function(){function t(t,e){this._compiler=t,this._config=e||Bi}return t.prototype.load=function(t){return this._compiler instanceof gi?this.loadFactory(t):this.loadAndCompile(t)},t.prototype.loadAndCompile=function(t){var e=this,r=l(t.split("#"),2),o=r[0],i=r[1];return void 0===i&&(i="default"),n("crnd")(o).then(function(t){return t[i]}).then(function(t){return Zi(t,o,i)}).then(function(t){return e._compiler.compileModuleAsync(t)})},t.prototype.loadFactory=function(t){var e=l(t.split("#"),2),r=e[0],o=e[1],i="NgFactory";return void 0===o&&(o="default",i=""),n("crnd")(this._config.factoryPathPrefix+r+this._config.factoryPathSuffix).then(function(t){return t[o+i]}).then(function(t){return Zi(t,r,o)})},t}();function Zi(t,e,n){if(!t)throw new Error("Cannot find '"+n+"' in '"+e+"'");return t}var Qi,Wi=function(){function t(){}return t.__NG_ELEMENT_ID__=function(){return Yi(t,Kr)},t}(),Yi=ar,Ki=function(){function t(){}return t.__NG_ELEMENT_ID__=function(){return $i()},t}(),$i=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e]},Ji=(o(function(){return null!==Qi&&Qi.apply(this,arguments)||this},Qi=Ki),function(){return function(t,e){this.name=t,this.callback=e}}()),Xi=function(){function t(t,e,n){this.listeners=[],this.parent=null,this._debugContext=n,this.nativeNode=t,e&&e instanceof ta&&e.addChild(this)}return Object.defineProperty(t.prototype,"injector",{get:function(){return this._debugContext.injector},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentInstance",{get:function(){return this._debugContext.component},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._debugContext.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"references",{get:function(){return this._debugContext.references},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"providerTokens",{get:function(){return this._debugContext.providerTokens},enumerable:!0,configurable:!0}),t}(),ta=function(t){function e(e,n,r){var o=t.call(this,e,n,r)||this;return o.properties={},o.attributes={},o.classes={},o.styles={},o.childNodes=[],o.nativeElement=e,o}return o(e,t),e.prototype.addChild=function(t){t&&(this.childNodes.push(t),t.parent=this)},e.prototype.removeChild=function(t){var e=this.childNodes.indexOf(t);-1!==e&&(t.parent=null,this.childNodes.splice(e,1))},e.prototype.insertChildrenAfter=function(t,e){var n,r=this,o=this.childNodes.indexOf(t);-1!==o&&((n=this.childNodes).splice.apply(n,c([o+1,0],e)),e.forEach(function(e){e.parent&&e.parent.removeChild(e),t.parent=r}))},e.prototype.insertBefore=function(t,e){var n=this.childNodes.indexOf(t);-1===n?this.addChild(e):(e.parent&&e.parent.removeChild(e),e.parent=this,this.childNodes.splice(n,0,e))},e.prototype.query=function(t){return this.queryAll(t)[0]||null},e.prototype.queryAll=function(t){var e=[];return function t(e,n,r){e.childNodes.forEach(function(e){e instanceof ta&&(n(e)&&r.push(e),t(e,n,r))})}(this,t,e),e},e.prototype.queryAllNodes=function(t){var e=[];return function t(e,n,r){e instanceof ta&&e.childNodes.forEach(function(e){n(e)&&r.push(e),e instanceof ta&&t(e,n,r)})}(this,t,e),e},Object.defineProperty(e.prototype,"children",{get:function(){return this.childNodes.filter(function(t){return t instanceof e})},enumerable:!0,configurable:!0}),e.prototype.triggerEventHandler=function(t,e){this.listeners.forEach(function(n){n.name==t&&n.callback(e)})},e}(Xi),ea=new Map,na=function(t){return ea.get(t)||null};function ra(t){ea.set(t.nativeNode,t)}var oa=function(){function t(){}return t.prototype.supports=function(t){return An(t)},t.prototype.create=function(t){return new aa(t)},t}(),ia=function(t,e){return e},aa=function(){function t(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||ia}return t.prototype.forEachItem=function(t){var e;for(e=this._itHead;null!==e;e=e._next)t(e)},t.prototype.forEachOperation=function(t){for(var e=this._itHead,n=this._removalsHead,r=0,o=null;e||n;){var i=!n||e&&e.currentIndex<ca(n,r,o)?e:n,a=ca(i,r,o),u=i.currentIndex;if(i===n)r--,n=n._nextRemoved;else if(e=e._next,null==i.previousIndex)r++;else{o||(o=[]);var s=a-r,l=u-r;if(s!=l){for(var c=0;c<s;c++){var f=c<o.length?o[c]:o[c]=0,p=f+c;l<=p&&p<s&&(o[c]=f+1)}o[i.previousIndex]=l-s}}a!==u&&t(i,a,u)}},t.prototype.forEachPreviousItem=function(t){var e;for(e=this._previousItHead;null!==e;e=e._nextPrevious)t(e)},t.prototype.forEachAddedItem=function(t){var e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)},t.prototype.forEachMovedItem=function(t){var e;for(e=this._movesHead;null!==e;e=e._nextMoved)t(e)},t.prototype.forEachRemovedItem=function(t){var e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)},t.prototype.forEachIdentityChange=function(t){var e;for(e=this._identityChangesHead;null!==e;e=e._nextIdentityChange)t(e)},t.prototype.diff=function(t){if(null==t&&(t=[]),!An(t))throw new Error("Error trying to diff '"+Ut(t)+"'. Only arrays and iterables are allowed");return this.check(t)?this:null},t.prototype.onDestroy=function(){},t.prototype.check=function(t){var e=this;this._reset();var n,r,o,i=this._itHead,a=!1;if(Array.isArray(t)){this.length=t.length;for(var u=0;u<this.length;u++)o=this._trackByFn(u,r=t[u]),null!==i&&jt(i.trackById,o)?(a&&(i=this._verifyReinsertion(i,r,o,u)),jt(i.item,r)||this._addIdentityChange(i,r)):(i=this._mismatch(i,r,o,u),a=!0),i=i._next}else n=0,function(t,e){if(Array.isArray(t))for(var n=0;n<t.length;n++)e(t[n]);else for(var r=t[Vt()](),o=void 0;!(o=r.next()).done;)e(o.value)}(t,function(t){o=e._trackByFn(n,t),null!==i&&jt(i.trackById,o)?(a&&(i=e._verifyReinsertion(i,t,o,n)),jt(i.item,t)||e._addIdentityChange(i,t)):(i=e._mismatch(i,t,o,n),a=!0),i=i._next,n++}),this.length=n;return this._truncate(i),this.collection=t,this.isDirty},Object.defineProperty(t.prototype,"isDirty",{get:function(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead},enumerable:!0,configurable:!0}),t.prototype._reset=function(){if(this.isDirty){var t=void 0,e=void 0;for(t=this._previousItHead=this._itHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._additionsHead;null!==t;t=t._nextAdded)t.previousIndex=t.currentIndex;for(this._additionsHead=this._additionsTail=null,t=this._movesHead;null!==t;t=e)t.previousIndex=t.currentIndex,e=t._nextMoved;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}},t.prototype._mismatch=function(t,e,n,r){var o;return null===t?o=this._itTail:(o=t._prev,this._remove(t)),null!==(t=null===this._linkedRecords?null:this._linkedRecords.get(n,r))?(jt(t.item,e)||this._addIdentityChange(t,e),this._moveAfter(t,o,r)):null!==(t=null===this._unlinkedRecords?null:this._unlinkedRecords.get(n,null))?(jt(t.item,e)||this._addIdentityChange(t,e),this._reinsertAfter(t,o,r)):t=this._addAfter(new ua(e,n),o,r),t},t.prototype._verifyReinsertion=function(t,e,n,r){var o=null===this._unlinkedRecords?null:this._unlinkedRecords.get(n,null);return null!==o?t=this._reinsertAfter(o,t._prev,r):t.currentIndex!=r&&(t.currentIndex=r,this._addToMoves(t,r)),t},t.prototype._truncate=function(t){for(;null!==t;){var e=t._next;this._addToRemovals(this._unlink(t)),t=e}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)},t.prototype._reinsertAfter=function(t,e,n){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(t);var r=t._prevRemoved,o=t._nextRemoved;return null===r?this._removalsHead=o:r._nextRemoved=o,null===o?this._removalsTail=r:o._prevRemoved=r,this._insertAfter(t,e,n),this._addToMoves(t,n),t},t.prototype._moveAfter=function(t,e,n){return this._unlink(t),this._insertAfter(t,e,n),this._addToMoves(t,n),t},t.prototype._addAfter=function(t,e,n){return this._insertAfter(t,e,n),this._additionsTail=null===this._additionsTail?this._additionsHead=t:this._additionsTail._nextAdded=t,t},t.prototype._insertAfter=function(t,e,n){var r=null===e?this._itHead:e._next;return t._next=r,t._prev=e,null===r?this._itTail=t:r._prev=t,null===e?this._itHead=t:e._next=t,null===this._linkedRecords&&(this._linkedRecords=new la),this._linkedRecords.put(t),t.currentIndex=n,t},t.prototype._remove=function(t){return this._addToRemovals(this._unlink(t))},t.prototype._unlink=function(t){null!==this._linkedRecords&&this._linkedRecords.remove(t);var e=t._prev,n=t._next;return null===e?this._itHead=n:e._next=n,null===n?this._itTail=e:n._prev=e,t},t.prototype._addToMoves=function(t,e){return t.previousIndex===e?t:(this._movesTail=null===this._movesTail?this._movesHead=t:this._movesTail._nextMoved=t,t)},t.prototype._addToRemovals=function(t){return null===this._unlinkedRecords&&(this._unlinkedRecords=new la),this._unlinkedRecords.put(t),t.currentIndex=null,t._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=t,t._prevRemoved=null):(t._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=t),t},t.prototype._addIdentityChange=function(t,e){return t.item=e,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=t:this._identityChangesTail._nextIdentityChange=t,t},t}(),ua=function(){return function(t,e){this.item=t,this.trackById=e,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}(),sa=function(){function t(){this._head=null,this._tail=null}return t.prototype.add=function(t){null===this._head?(this._head=this._tail=t,t._nextDup=null,t._prevDup=null):(this._tail._nextDup=t,t._prevDup=this._tail,t._nextDup=null,this._tail=t)},t.prototype.get=function(t,e){var n;for(n=this._head;null!==n;n=n._nextDup)if((null===e||e<=n.currentIndex)&&jt(n.trackById,t))return n;return null},t.prototype.remove=function(t){var e=t._prevDup,n=t._nextDup;return null===e?this._head=n:e._nextDup=n,null===n?this._tail=e:n._prevDup=e,null===this._head},t}(),la=function(){function t(){this.map=new Map}return t.prototype.put=function(t){var e=t.trackById,n=this.map.get(e);n||(n=new sa,this.map.set(e,n)),n.add(t)},t.prototype.get=function(t,e){var n=this.map.get(t);return n?n.get(t,e):null},t.prototype.remove=function(t){var e=t.trackById;return this.map.get(e).remove(t)&&this.map.delete(e),t},Object.defineProperty(t.prototype,"isEmpty",{get:function(){return 0===this.map.size},enumerable:!0,configurable:!0}),t.prototype.clear=function(){this.map.clear()},t}();function ca(t,e,n){var r=t.previousIndex;if(null===r)return r;var o=0;return n&&r<n.length&&(o=n[r]),r+e+o}var fa=function(){function t(){}return t.prototype.supports=function(t){return t instanceof Map||On(t)},t.prototype.create=function(){return new pa},t}(),pa=function(){function t(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}return Object.defineProperty(t.prototype,"isDirty",{get:function(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead},enumerable:!0,configurable:!0}),t.prototype.forEachItem=function(t){var e;for(e=this._mapHead;null!==e;e=e._next)t(e)},t.prototype.forEachPreviousItem=function(t){var e;for(e=this._previousMapHead;null!==e;e=e._nextPrevious)t(e)},t.prototype.forEachChangedItem=function(t){var e;for(e=this._changesHead;null!==e;e=e._nextChanged)t(e)},t.prototype.forEachAddedItem=function(t){var e;for(e=this._additionsHead;null!==e;e=e._nextAdded)t(e)},t.prototype.forEachRemovedItem=function(t){var e;for(e=this._removalsHead;null!==e;e=e._nextRemoved)t(e)},t.prototype.diff=function(t){if(t){if(!(t instanceof Map||On(t)))throw new Error("Error trying to diff '"+Ut(t)+"'. Only maps and objects are allowed")}else t=new Map;return this.check(t)?this:null},t.prototype.onDestroy=function(){},t.prototype.check=function(t){var e=this;this._reset();var n=this._mapHead;if(this._appendAfter=null,this._forEach(t,function(t,r){if(n&&n.key===r)e._maybeAddToChanges(n,t),e._appendAfter=n,n=n._next;else{var o=e._getOrCreateRecordForKey(r,t);n=e._insertBeforeOrAppend(n,o)}}),n){n._prev&&(n._prev._next=null),this._removalsHead=n;for(var r=n;null!==r;r=r._nextRemoved)r===this._mapHead&&(this._mapHead=null),this._records.delete(r.key),r._nextRemoved=r._next,r.previousValue=r.currentValue,r.currentValue=null,r._prev=null,r._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty},t.prototype._insertBeforeOrAppend=function(t,e){if(t){var n=t._prev;return e._next=t,e._prev=n,t._prev=e,n&&(n._next=e),t===this._mapHead&&(this._mapHead=e),this._appendAfter=t,t}return this._appendAfter?(this._appendAfter._next=e,e._prev=this._appendAfter):this._mapHead=e,this._appendAfter=e,null},t.prototype._getOrCreateRecordForKey=function(t,e){if(this._records.has(t)){var n=this._records.get(t);this._maybeAddToChanges(n,e);var r=n._prev,o=n._next;return r&&(r._next=o),o&&(o._prev=r),n._next=null,n._prev=null,n}var i=new ha(t);return this._records.set(t,i),i.currentValue=e,this._addToAdditions(i),i},t.prototype._reset=function(){if(this.isDirty){var t=void 0;for(this._previousMapHead=this._mapHead,t=this._previousMapHead;null!==t;t=t._next)t._nextPrevious=t._next;for(t=this._changesHead;null!==t;t=t._nextChanged)t.previousValue=t.currentValue;for(t=this._additionsHead;null!=t;t=t._nextAdded)t.previousValue=t.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}},t.prototype._maybeAddToChanges=function(t,e){jt(e,t.currentValue)||(t.previousValue=t.currentValue,t.currentValue=e,this._addToChanges(t))},t.prototype._addToAdditions=function(t){null===this._additionsHead?this._additionsHead=this._additionsTail=t:(this._additionsTail._nextAdded=t,this._additionsTail=t)},t.prototype._addToChanges=function(t){null===this._changesHead?this._changesHead=this._changesTail=t:(this._changesTail._nextChanged=t,this._changesTail=t)},t.prototype._forEach=function(t,e){t instanceof Map?t.forEach(e):Object.keys(t).forEach(function(n){return e(t[n],n)})},t}(),ha=function(){return function(t){this.key=t,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}(),da=function(){function t(t){this.factories=t}return t.create=function(e,n){if(null!=n){var r=n.factories.slice();e=e.concat(r)}return new t(e)},t.extend=function(e){return{provide:t,useFactory:function(n){if(!n)throw new Error("Cannot extend IterableDiffers without a parent injector");return t.create(e,n)},deps:[[t,new De,new Ne]]}},t.prototype.find=function(t){var e,n=this.factories.find(function(e){return e.supports(t)});if(null!=n)return n;throw new Error("Cannot find a differ supporting object '"+t+"' of type '"+((e=t).name||typeof e)+"'")},t.ngInjectableDef=St({providedIn:"root",factory:function(){return new t([new oa])}}),t}(),va=function(){function t(t){this.factories=t}return t.create=function(e,n){if(n){var r=n.factories.slice();e=e.concat(r)}return new t(e)},t.extend=function(e){return{provide:t,useFactory:function(n){if(!n)throw new Error("Cannot extend KeyValueDiffers without a parent injector");return t.create(e,n)},deps:[[t,new De,new Ne]]}},t.prototype.find=function(t){var e=this.factories.find(function(e){return e.supports(t)});if(e)return e;throw new Error("Cannot find a differ supporting object '"+t+"'")},t.ngInjectableDef=St({providedIn:"root",factory:function(){return new t([new fa])}}),t}(),ga=[new fa],ya=new da([new oa]),ma=new va(ga),ba=Mi(null,"core",[{provide:ai,useValue:"unknown"},{provide:Ui,deps:[pr]},{provide:Ni,deps:[]},{provide:si,deps:[]}]),_a=new Tt("LocaleId");function wa(){return ya}function Ca(){return ma}function Sa(t){return t||"en-US"}var Ea=function(){return function(t){}}();function xa(t,e,n){var r=t.state,o=1792&r;return o===e?(t.state=-1793&r|n,t.initIndex=-1,!0):o===n}function Ta(t,e,n){return(1792&t.state)===e&&t.initIndex<=n&&(t.initIndex=n+1,!0)}function ka(t,e){return t.nodes[e]}function Aa(t,e){return t.nodes[e]}function Oa(t,e){return t.nodes[e]}function Pa(t,e){return t.nodes[e]}function Ia(t,e){return t.nodes[e]}var Na={setCurrentNode:void 0,createRootView:void 0,createEmbeddedView:void 0,createComponentView:void 0,createNgModuleRef:void 0,overrideProvider:void 0,overrideComponentView:void 0,clearOverrides:void 0,checkAndUpdateView:void 0,checkNoChangesView:void 0,destroyView:void 0,resolveDep:void 0,createDebugContext:void 0,handleEvent:void 0,updateDirectives:void 0,updateRenderer:void 0,dirtyParentQueries:void 0};function Ra(t,e,n,r){var o="ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '"+e+"'. Current value: '"+n+"'.";return r&&(o+=" It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?"),function(t,e){var n=new Error(t);return Da(n,e),n}(o,t)}function Da(t,e){t[Go]=e,t[Qo]=e.logError.bind(e)}function Va(t){return new Error("ViewDestroyedError: Attempt to use a destroyed view: "+t)}var Ma=function(){},ja=new Map;function Ua(t){var e=ja.get(t);return e||(e=Ut(t)+"_"+ja.size,ja.set(t,e)),e}function La(t,e,n,r){if(Tn.isWrapped(r)){r=Tn.unwrap(r);var o=t.def.nodes[e].bindingIndex+n,i=Tn.unwrap(t.oldValues[o]);t.oldValues[o]=new Tn(i)}return r}var Ha="$$undefined",Fa="$$empty";function za(t){return{id:Ha,styles:t.styles,encapsulation:t.encapsulation,data:t.data}}var qa=0;function Ba(t,e,n,r){return!(!(2&t.state)&&jt(t.oldValues[e.bindingIndex+n],r))}function Ga(t,e,n,r){return!!Ba(t,e,n,r)&&(t.oldValues[e.bindingIndex+n]=r,!0)}function Za(t,e,n,r){var o=t.oldValues[e.bindingIndex+n];if(1&t.state||!xn(o,r)){var i=e.bindings[n].name;throw Ra(Na.createDebugContext(t,e.nodeIndex),i+": "+o,i+": "+r,0!=(1&t.state))}}function Qa(t){for(var e=t;e;)2&e.def.flags&&(e.state|=8),e=e.viewContainerParent||e.parent}function Wa(t,e){for(var n=t;n&&n!==e;)n.state|=64,n=n.viewContainerParent||n.parent}function Ya(t,e,n,r){try{return Qa(33554432&t.def.nodes[e].flags?Aa(t,e).componentView:t),Na.handleEvent(t,e,n,r)}catch(o){t.root.errorHandler.handleError(o)}}function Ka(t){return t.parent?Aa(t.parent,t.parentNodeDef.nodeIndex):null}function $a(t){return t.parent?t.parentNodeDef.parent:null}function Ja(t,e){switch(201347067&e.flags){case 1:return Aa(t,e.nodeIndex).renderElement;case 2:return ka(t,e.nodeIndex).renderText}}function Xa(t){return!!t.parent&&!!(32768&t.parentNodeDef.flags)}function tu(t){return!(!t.parent||32768&t.parentNodeDef.flags)}function eu(t){var e={},n=0,r={};return t&&t.forEach(function(t){var o=l(t,2),i=o[0],a=o[1];"number"==typeof i?(e[i]=a,n|=function(t){return 1<<t%32}(i)):r[i]=a}),{matchedQueries:e,references:r,matchedQueryIds:n}}function nu(t,e){return t.map(function(t){var n,r,o;return Array.isArray(t)?(o=(n=l(t,2))[0],r=n[1]):(o=0,r=t),r&&("function"==typeof r||"object"==typeof r)&&e&&Object.defineProperty(r,ur,{value:e,configurable:!0}),{flags:o,token:r,tokenKey:Ua(r)}})}function ru(t,e,n){var r=n.renderParent;return r?0==(1&r.flags)||0==(33554432&r.flags)||r.element.componentRendererType&&r.element.componentRendererType.encapsulation===zt.Native?Aa(t,n.renderParent.nodeIndex).renderElement:void 0:e}var ou=new WeakMap;function iu(t){var e=ou.get(t);return e||((e=t(function(){return Ma})).factory=t,ou.set(t,e)),e}function au(t,e,n,r,o){3===e&&(n=t.renderer.parentNode(Ja(t,t.def.lastRenderRootNode))),uu(t,e,0,t.def.nodes.length-1,n,r,o)}function uu(t,e,n,r,o,i,a){for(var u=n;u<=r;u++){var s=t.def.nodes[u];11&s.flags&&lu(t,s,e,o,i,a),u+=s.childCount}}function su(t,e,n,r,o,i){for(var a=t;a&&!Xa(a);)a=a.parent;for(var u=a.parent,s=$a(a),l=s.nodeIndex+s.childCount,c=s.nodeIndex+1;c<=l;c++){var f=u.def.nodes[c];f.ngContentIndex===e&&lu(u,f,n,r,o,i),c+=f.childCount}if(!u.parent){var p=t.root.projectableNodes[e];if(p)for(c=0;c<p.length;c++)cu(t,p[c],n,r,o,i)}}function lu(t,e,n,r,o,i){if(8&e.flags)su(t,e.ngContent.index,n,r,o,i);else{var a=Ja(t,e);if(3===n&&33554432&e.flags&&48&e.bindingFlags?(16&e.bindingFlags&&cu(t,a,n,r,o,i),32&e.bindingFlags&&cu(Aa(t,e.nodeIndex).componentView,a,n,r,o,i)):cu(t,a,n,r,o,i),16777216&e.flags)for(var u=Aa(t,e.nodeIndex).viewContainer._embeddedViews,s=0;s<u.length;s++)au(u[s],n,r,o,i);1&e.flags&&!e.element.name&&uu(t,n,e.nodeIndex+1,e.nodeIndex+e.childCount,r,o,i)}}function cu(t,e,n,r,o,i){var a=t.renderer;switch(n){case 1:a.appendChild(r,e);break;case 2:a.insertBefore(r,e,o);break;case 3:a.removeChild(r,e);break;case 0:i.push(e)}}var fu=/^:([^:]+):(.+)$/;function pu(t){if(":"===t[0]){var e=t.match(fu);return[e[1],e[2]]}return["",t]}function hu(t){for(var e=0,n=0;n<t.length;n++)e|=t[n].flags;return e}function du(t,e,n,r,o,i){t|=1;var a=eu(e);return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,flags:t,checkIndex:-1,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:a.matchedQueries,matchedQueryIds:a.matchedQueryIds,references:a.references,ngContentIndex:n,childCount:r,bindings:[],bindingFlags:0,outputs:[],element:{ns:null,name:null,attrs:null,template:i?iu(i):null,componentProvider:null,componentView:null,componentRendererType:null,publicProviders:null,allProviders:null,handleEvent:o||Ma},provider:null,text:null,query:null,ngContent:null}}function vu(t,e,n,r,o,i,a,u,s,c,f,p){var h;void 0===a&&(a=[]),c||(c=Ma);var d=eu(n),v=d.matchedQueries,g=d.references,y=d.matchedQueryIds,m=null,b=null;i&&(m=(h=l(pu(i),2))[0],b=h[1]),u=u||[];for(var _=new Array(u.length),w=0;w<u.length;w++){var C=l(u[w],3),S=C[0],E=C[2],x=l(pu(C[1]),2),T=x[0],k=x[1],A=void 0,O=void 0;switch(15&S){case 4:O=E;break;case 1:case 8:A=E}_[w]={flags:S,ns:T,name:k,nonMinifiedName:k,securityContext:A,suffix:O}}s=s||[];var P=new Array(s.length);for(w=0;w<s.length;w++){var I=l(s[w],2);P[w]={type:0,target:I[0],eventName:I[1],propName:null}}var N=(a=a||[]).map(function(t){var e=l(t,2),n=e[1],r=l(pu(e[0]),2);return[r[0],r[1],n]});return p=function(t){if(t&&t.id===Ha){var e=null!=t.encapsulation&&t.encapsulation!==zt.None||t.styles.length||Object.keys(t.data).length;t.id=e?"c"+qa++:Fa}return t&&t.id===Fa&&(t=null),t||null}(p),f&&(e|=33554432),{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:t,flags:e|=1,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:v,matchedQueryIds:y,references:g,ngContentIndex:r,childCount:o,bindings:_,bindingFlags:hu(_),outputs:P,element:{ns:m,name:b,attrs:N,template:null,componentProvider:null,componentView:f||null,componentRendererType:p,publicProviders:null,allProviders:null,handleEvent:c||Ma},provider:null,text:null,query:null,ngContent:null}}function gu(t,e,n){var r,o=n.element,i=t.root.selectorOrNode,a=t.renderer;if(t.parent||!i){r=o.name?a.createElement(o.name,o.ns):a.createComment("");var u=ru(t,e,n);u&&a.appendChild(u,r)}else r=a.selectRootElement(i,!!o.componentRendererType&&o.componentRendererType.encapsulation===zt.ShadowDom);if(o.attrs)for(var s=0;s<o.attrs.length;s++){var c=l(o.attrs[s],3);a.setAttribute(r,c[1],c[2],c[0])}return r}function yu(t,e,n,r){for(var o=0;o<n.outputs.length;o++){var i=n.outputs[o],a=mu(t,n.nodeIndex,(f=i.eventName,(c=i.target)?c+":"+f:f)),u=i.target,s=t;"component"===i.target&&(u=null,s=e);var l=s.renderer.listen(u||r,i.eventName,a);t.disposables[n.outputIndex+o]=l}var c,f}function mu(t,e,n){return function(r){return Ya(t,e,n,r)}}function bu(t,e,n,r){if(!Ga(t,e,n,r))return!1;var o=e.bindings[n],i=Aa(t,e.nodeIndex),a=i.renderElement,u=o.name;switch(15&o.flags){case 1:!function(t,e,n,r,o,i){var a=e.securityContext,u=a?t.root.sanitizer.sanitize(a,i):i;u=null!=u?u.toString():null;var s=t.renderer;null!=i?s.setAttribute(n,o,u,r):s.removeAttribute(n,o,r)}(t,o,a,o.ns,u,r);break;case 2:!function(t,e,n,r){var o=t.renderer;r?o.addClass(e,n):o.removeClass(e,n)}(t,a,u,r);break;case 4:!function(t,e,n,r,o){var i=t.root.sanitizer.sanitize(ro.STYLE,o);if(null!=i){i=i.toString();var a=e.suffix;null!=a&&(i+=a)}else i=null;var u=t.renderer;null!=i?u.setStyle(n,r,i):u.removeStyle(n,r)}(t,o,a,u,r);break;case 8:!function(t,e,n,r,o){var i=e.securityContext,a=i?t.root.sanitizer.sanitize(i,o):o;t.renderer.setProperty(n,r,a)}(33554432&e.flags&&32&o.flags?i.componentView:t,o,a,u,r)}return!0}var _u=new Object,wu=Ua(pr),Cu=Ua(cr),Su=Ua(Qr);function Eu(t,e,n,r){return n=Ft(n),{index:-1,deps:nu(r,Ut(e)),flags:t,token:e,value:n}}function xu(t,e,n){void 0===n&&(n=pr.THROW_IF_NOT_FOUND);var r,o,i=je(t);try{if(8&e.flags)return e.token;if(2&e.flags&&(n=null),1&e.flags)return t._parent.get(e.token,n);var a=e.tokenKey;switch(a){case wu:case Cu:case Su:return t}var u,s=t._def.providersByKey[a];if(s){var l=t._providers[s.index];return void 0===l&&(l=t._providers[s.index]=Tu(t,s)),l===_u?void 0:l}if((u=Et(e.token))&&(r=t,null!=(o=u).providedIn&&(function(t,e){return t._def.modules.indexOf(o.providedIn)>-1}(r)||"root"===o.providedIn&&r._def.isRoot))){var c=t._providers.length;return t._def.providersByKey[e.tokenKey]={flags:5120,value:u.factory,deps:[],index:c,token:e.token},t._providers[c]=_u,t._providers[c]=Tu(t,t._def.providersByKey[e.tokenKey])}return 4&e.flags?n:t._parent.get(e.token,n)}finally{je(i)}}function Tu(t,e){var n;switch(201347067&e.flags){case 512:n=function(t,e,n){var r=n.length;switch(r){case 0:return new e;case 1:return new e(xu(t,n[0]));case 2:return new e(xu(t,n[0]),xu(t,n[1]));case 3:return new e(xu(t,n[0]),xu(t,n[1]),xu(t,n[2]));default:for(var o=new Array(r),i=0;i<r;i++)o[i]=xu(t,n[i]);return new(e.bind.apply(e,c([void 0],o)))}}(t,e.value,e.deps);break;case 1024:n=function(t,e,n){var r=n.length;switch(r){case 0:return e();case 1:return e(xu(t,n[0]));case 2:return e(xu(t,n[0]),xu(t,n[1]));case 3:return e(xu(t,n[0]),xu(t,n[1]),xu(t,n[2]));default:for(var o=Array(r),i=0;i<r;i++)o[i]=xu(t,n[i]);return e.apply(void 0,c(o))}}(t,e.value,e.deps);break;case 2048:n=xu(t,e.deps[0]);break;case 256:n=e.value}return n===_u||null==n||"object"!=typeof n||131072&e.flags||"function"!=typeof n.ngOnDestroy||(e.flags|=131072),void 0===n?_u:n}function ku(t,e){var n=t.viewContainer._embeddedViews;if((null==e||e>=n.length)&&(e=n.length-1),e<0)return null;var r=n[e];return r.viewContainerParent=null,Iu(n,e),Na.dirtyParentQueries(r),Ou(r),r}function Au(t,e,n){var r=e?Ja(e,e.def.lastRenderRootNode):t.renderElement,o=n.renderer.parentNode(r),i=n.renderer.nextSibling(r);au(n,2,o,i,void 0)}function Ou(t){au(t,3,null,null,void 0)}function Pu(t,e,n){e>=t.length?t.push(n):t.splice(e,0,n)}function Iu(t,e){e>=t.length-1?t.pop():t.splice(e,1)}var Nu=new Object;function Ru(t,e,n,r,o,i){return new Du(t,e,n,r,o,i)}var Du=function(t){function e(e,n,r,o,i,a){var u=t.call(this)||this;return u.selector=e,u.componentType=n,u._inputs=o,u._outputs=i,u.ngContentSelectors=a,u.viewDefFactory=r,u}return o(e,t),Object.defineProperty(e.prototype,"inputs",{get:function(){var t=[],e=this._inputs;for(var n in e)t.push({propName:n,templateName:e[n]});return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){var t=[];for(var e in this._outputs)t.push({propName:e,templateName:this._outputs[e]});return t},enumerable:!0,configurable:!0}),e.prototype.create=function(t,e,n,r){if(!r)throw new Error("ngModule should be provided");var o=iu(this.viewDefFactory),i=o.nodes[0].element.componentProvider.nodeIndex,a=Na.createRootView(t,e||[],n,o,r,Nu),u=Oa(a,i).instance;return n&&a.renderer.setAttribute(Aa(a,0).renderElement,"ng-version",io.full),new Vu(a,new Lu(a),u)},e}(Lr),Vu=function(t){function e(e,n,r){var o=t.call(this)||this;return o._view=e,o._viewRef=n,o._component=r,o._elDef=o._view.def.nodes[0],o.hostView=n,o.changeDetectorRef=n,o.instance=r,o}return o(e,t),Object.defineProperty(e.prototype,"location",{get:function(){return new Kr(Aa(this._view,this._elDef.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"injector",{get:function(){return new qu(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"componentType",{get:function(){return this._component.constructor},enumerable:!0,configurable:!0}),e.prototype.destroy=function(){this._viewRef.destroy()},e.prototype.onDestroy=function(t){this._viewRef.onDestroy(t)},e}(Ur);function Mu(t,e,n){return new ju(t,e,n)}var ju=function(){function t(t,e,n){this._view=t,this._elDef=e,this._data=n,this._embeddedViews=[]}return Object.defineProperty(t.prototype,"element",{get:function(){return new Kr(this._data.renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"injector",{get:function(){return new qu(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parentInjector",{get:function(){for(var t=this._view,e=this._elDef.parent;!e&&t;)e=$a(t),t=t.parent;return t?new qu(t,e):new qu(this._view,null)},enumerable:!0,configurable:!0}),t.prototype.clear=function(){for(var t=this._embeddedViews.length-1;t>=0;t--){var e=ku(this._data,t);Na.destroyView(e)}},t.prototype.get=function(t){var e=this._embeddedViews[t];if(e){var n=new Lu(e);return n.attachToViewContainerRef(this),n}return null},Object.defineProperty(t.prototype,"length",{get:function(){return this._embeddedViews.length},enumerable:!0,configurable:!0}),t.prototype.createEmbeddedView=function(t,e,n){var r=t.createEmbeddedView(e||{});return this.insert(r,n),r},t.prototype.createComponent=function(t,e,n,r,o){var i=n||this.parentInjector;o||t instanceof Zr||(o=i.get(Qr));var a=t.create(i,r,void 0,o);return this.insert(a.hostView,e),a},t.prototype.insert=function(t,e){if(t.destroyed)throw new Error("Cannot insert a destroyed View in a ViewContainer!");var n,r,o,i,a=t;return i=(n=this._data).viewContainer._embeddedViews,null==(r=e)&&(r=i.length),(o=a._view).viewContainerParent=this._view,Pu(i,r,o),function(t,e){var n=Ka(e);if(n&&n!==t&&!(16&e.state)){e.state|=16;var r=n.template._projectedViews;r||(r=n.template._projectedViews=[]),r.push(e),function(t,n){if(!(4&n.flags)){e.parent.def.nodeFlags|=4,n.flags|=4;for(var r=n.parent;r;)r.childFlags|=4,r=r.parent}}(0,e.parentNodeDef)}}(n,o),Na.dirtyParentQueries(o),Au(n,r>0?i[r-1]:null,o),a.attachToViewContainerRef(this),t},t.prototype.move=function(t,e){if(t.destroyed)throw new Error("Cannot move a destroyed View in a ViewContainer!");var n,r,o,i,a,u=this._embeddedViews.indexOf(t._view);return o=e,a=(i=(n=this._data).viewContainer._embeddedViews)[r=u],Iu(i,r),null==o&&(o=i.length),Pu(i,o,a),Na.dirtyParentQueries(a),Ou(a),Au(n,o>0?i[o-1]:null,a),t},t.prototype.indexOf=function(t){return this._embeddedViews.indexOf(t._view)},t.prototype.remove=function(t){var e=ku(this._data,t);e&&Na.destroyView(e)},t.prototype.detach=function(t){var e=ku(this._data,t);return e?new Lu(e):null},t}();function Uu(t){return new Lu(t)}var Lu=function(){function t(t){this._view=t,this._viewContainerRef=null,this._appRef=null}return Object.defineProperty(t.prototype,"rootNodes",{get:function(){return au(this._view,0,void 0,void 0,t=[]),t;var t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._view.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"destroyed",{get:function(){return 0!=(128&this._view.state)},enumerable:!0,configurable:!0}),t.prototype.markForCheck=function(){Qa(this._view)},t.prototype.detach=function(){this._view.state&=-5},t.prototype.detectChanges=function(){var t=this._view.root.rendererFactory;t.begin&&t.begin();try{Na.checkAndUpdateView(this._view)}finally{t.end&&t.end()}},t.prototype.checkNoChanges=function(){Na.checkNoChangesView(this._view)},t.prototype.reattach=function(){this._view.state|=4},t.prototype.onDestroy=function(t){this._view.disposables||(this._view.disposables=[]),this._view.disposables.push(t)},t.prototype.destroy=function(){this._appRef?this._appRef.detachView(this):this._viewContainerRef&&this._viewContainerRef.detach(this._viewContainerRef.indexOf(this)),Na.destroyView(this._view)},t.prototype.detachFromAppRef=function(){this._appRef=null,Ou(this._view),Na.dirtyParentQueries(this._view)},t.prototype.attachToAppRef=function(t){if(this._viewContainerRef)throw new Error("This view is already attached to a ViewContainer!");this._appRef=t},t.prototype.attachToViewContainerRef=function(t){if(this._appRef)throw new Error("This view is already attached directly to the ApplicationRef!");this._viewContainerRef=t},t}();function Hu(t,e){return new Fu(t,e)}var Fu=function(t){function e(e,n){var r=t.call(this)||this;return r._parentView=e,r._def=n,r}return o(e,t),e.prototype.createEmbeddedView=function(t){return new Lu(Na.createEmbeddedView(this._parentView,this._def,this._def.element.template,t))},Object.defineProperty(e.prototype,"elementRef",{get:function(){return new Kr(Aa(this._parentView,this._def.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),e}(Ho);function zu(t,e){return new qu(t,e)}var qu=function(){function t(t,e){this.view=t,this.elDef=e}return t.prototype.get=function(t,e){return void 0===e&&(e=pr.THROW_IF_NOT_FOUND),Na.resolveDep(this.view,this.elDef,!!this.elDef&&0!=(33554432&this.elDef.flags),{flags:0,token:t,tokenKey:Ua(t)},e)},t}();function Bu(t,e){var n=t.def.nodes[e];if(1&n.flags){var r=Aa(t,n.nodeIndex);return n.element.template?r.template:r.renderElement}if(2&n.flags)return ka(t,n.nodeIndex).renderText;if(20240&n.flags)return Oa(t,n.nodeIndex).instance;throw new Error("Illegal state: read nodeValue for node index "+e)}function Gu(t){return new Zu(t.renderer)}var Zu=function(){function t(t){this.delegate=t}return t.prototype.selectRootElement=function(t){return this.delegate.selectRootElement(t)},t.prototype.createElement=function(t,e){var n=l(pu(e),2),r=this.delegate.createElement(n[1],n[0]);return t&&this.delegate.appendChild(t,r),r},t.prototype.createViewRoot=function(t){return t},t.prototype.createTemplateAnchor=function(t){var e=this.delegate.createComment("");return t&&this.delegate.appendChild(t,e),e},t.prototype.createText=function(t,e){var n=this.delegate.createText(e);return t&&this.delegate.appendChild(t,n),n},t.prototype.projectNodes=function(t,e){for(var n=0;n<e.length;n++)this.delegate.appendChild(t,e[n])},t.prototype.attachViewAfter=function(t,e){for(var n=this.delegate.parentNode(t),r=this.delegate.nextSibling(t),o=0;o<e.length;o++)this.delegate.insertBefore(n,e[o],r)},t.prototype.detachView=function(t){for(var e=0;e<t.length;e++){var n=t[e],r=this.delegate.parentNode(n);this.delegate.removeChild(r,n)}},t.prototype.destroyView=function(t,e){for(var n=0;n<e.length;n++)this.delegate.destroyNode(e[n])},t.prototype.listen=function(t,e,n){return this.delegate.listen(t,e,n)},t.prototype.listenGlobal=function(t,e,n){return this.delegate.listen(t,e,n)},t.prototype.setElementProperty=function(t,e,n){this.delegate.setProperty(t,e,n)},t.prototype.setElementAttribute=function(t,e,n){var r=l(pu(e),2),o=r[0],i=r[1];null!=n?this.delegate.setAttribute(t,i,n,o):this.delegate.removeAttribute(t,i,o)},t.prototype.setBindingDebugInfo=function(t,e,n){},t.prototype.setElementClass=function(t,e,n){n?this.delegate.addClass(t,e):this.delegate.removeClass(t,e)},t.prototype.setElementStyle=function(t,e,n){null!=n?this.delegate.setStyle(t,e,n):this.delegate.removeStyle(t,e)},t.prototype.invokeElementMethod=function(t,e,n){t[e].apply(t,n)},t.prototype.setText=function(t,e){this.delegate.setValue(t,e)},t.prototype.animate=function(){throw new Error("Renderer.animate is no longer supported!")},t}();function Qu(t,e,n,r){return new Wu(t,e,n,r)}var Wu=function(){function t(t,e,n,r){this._moduleType=t,this._parent=e,this._bootstrapComponents=n,this._def=r,this._destroyListeners=[],this._destroyed=!1,this.injector=this,function(t){for(var e=t._def,n=t._providers=new Array(e.providers.length),r=0;r<e.providers.length;r++){var o=e.providers[r];4096&o.flags||void 0===n[r]&&(n[r]=Tu(t,o))}}(this)}return t.prototype.get=function(t,e,n){void 0===e&&(e=pr.THROW_IF_NOT_FOUND),void 0===n&&(n=Ve.Default);var r=0;return n&Ve.SkipSelf?r|=1:n&Ve.Self&&(r|=4),xu(this,{token:t,tokenKey:Ua(t),flags:r},e)},Object.defineProperty(t.prototype,"instance",{get:function(){return this.get(this._moduleType)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentFactoryResolver",{get:function(){return this.get(Br)},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){if(this._destroyed)throw new Error("The ng module "+Ut(this.instance.constructor)+" has already been destroyed.");this._destroyed=!0,function(t,e){for(var n=t._def,r=new Set,o=0;o<n.providers.length;o++)if(131072&n.providers[o].flags){var i=t._providers[o];if(i&&i!==_u){var a=i.ngOnDestroy;"function"!=typeof a||r.has(i)||(a.apply(i),r.add(i))}}}(this),this._destroyListeners.forEach(function(t){return t()})},t.prototype.onDestroy=function(t){this._destroyListeners.push(t)},t}(),Yu=Ua(Jr),Ku=Ua(eo),$u=Ua(Kr),Ju=Ua(Wi),Xu=Ua(Ho),ts=Ua(Ki),es=Ua(pr),ns=Ua(cr);function rs(t,e,n,r,o,i,a,u){var s=[];if(a)for(var c in a){var f=l(a[c],2);s[f[0]]={flags:8,name:c,nonMinifiedName:f[1],ns:null,securityContext:null,suffix:null}}var p=[];if(u)for(var h in u)p.push({type:1,propName:h,target:null,eventName:u[h]});return as(t,e|=16384,n,r,o,o,i,s,p)}function os(t,e,n){return as(-1,t|=16,null,0,e,e,n)}function is(t,e,n,r,o){return as(-1,t,e,0,n,r,o)}function as(t,e,n,r,o,i,a,u,s){var l=eu(n),c=l.matchedQueries,f=l.references,p=l.matchedQueryIds;s||(s=[]),u||(u=[]),i=Ft(i);var h=nu(a,Ut(o));return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:t,flags:e,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:c,matchedQueryIds:p,references:f,ngContentIndex:-1,childCount:r,bindings:u,bindingFlags:hu(u),outputs:s,element:null,provider:{token:o,value:i,deps:h},text:null,query:null,ngContent:null}}function us(t,e){return fs(t,e)}function ss(t,e){for(var n=t;n.parent&&!Xa(n);)n=n.parent;return ps(n.parent,$a(n),!0,e.provider.value,e.provider.deps)}function ls(t,e){var n=ps(t,e.parent,(32768&e.flags)>0,e.provider.value,e.provider.deps);if(e.outputs.length)for(var r=0;r<e.outputs.length;r++){var o=e.outputs[r],i=n[o.propName];if(!Xo(i))throw new Error("@Output "+o.propName+" not initialized in '"+n.constructor.name+"'.");var a=i.subscribe(cs(t,e.parent.nodeIndex,o.eventName));t.disposables[e.outputIndex+r]=a.unsubscribe.bind(a)}return n}function cs(t,e,n){return function(r){return Ya(t,e,n,r)}}function fs(t,e){var n=(8192&e.flags)>0,r=e.provider;switch(201347067&e.flags){case 512:return ps(t,e.parent,n,r.value,r.deps);case 1024:return function(t,e,n,r,o){var i=o.length;switch(i){case 0:return r();case 1:return r(ds(t,e,n,o[0]));case 2:return r(ds(t,e,n,o[0]),ds(t,e,n,o[1]));case 3:return r(ds(t,e,n,o[0]),ds(t,e,n,o[1]),ds(t,e,n,o[2]));default:for(var a=Array(i),u=0;u<i;u++)a[u]=ds(t,e,n,o[u]);return r.apply(void 0,c(a))}}(t,e.parent,n,r.value,r.deps);case 2048:return ds(t,e.parent,n,r.deps[0]);case 256:return r.value}}function ps(t,e,n,r,o){var i=o.length;switch(i){case 0:return new r;case 1:return new r(ds(t,e,n,o[0]));case 2:return new r(ds(t,e,n,o[0]),ds(t,e,n,o[1]));case 3:return new r(ds(t,e,n,o[0]),ds(t,e,n,o[1]),ds(t,e,n,o[2]));default:for(var a=new Array(i),u=0;u<i;u++)a[u]=ds(t,e,n,o[u]);return new(r.bind.apply(r,c([void 0],a)))}}var hs={};function ds(t,e,n,r,o){if(void 0===o&&(o=pr.THROW_IF_NOT_FOUND),8&r.flags)return r.token;var i=t;2&r.flags&&(o=null);var a=r.tokenKey;a===ts&&(n=!(!e||!e.element.componentView)),e&&1&r.flags&&(n=!1,e=e.parent);for(var u=t;u;){if(e)switch(a){case Yu:return Gu(vs(u,e,n));case Ku:return vs(u,e,n).renderer;case $u:return new Kr(Aa(u,e.nodeIndex).renderElement);case Ju:return Aa(u,e.nodeIndex).viewContainer;case Xu:if(e.element.template)return Aa(u,e.nodeIndex).template;break;case ts:return Uu(vs(u,e,n));case es:case ns:return zu(u,e);default:var s=(n?e.element.allProviders:e.element.publicProviders)[a];if(s){var l=Oa(u,s.nodeIndex);return l||(l={instance:fs(u,s)},u.nodes[s.nodeIndex]=l),l.instance}}n=Xa(u),e=$a(u),u=u.parent,4&r.flags&&(u=null)}var c=i.root.injector.get(r.token,hs);return c!==hs||o===hs?c:i.root.ngModule.injector.get(r.token,o)}function vs(t,e,n){var r;if(n)r=Aa(t,e.nodeIndex).componentView;else for(r=t;r.parent&&!Xa(r);)r=r.parent;return r}function gs(t,e,n,r,o,i){if(32768&n.flags){var a=Aa(t,n.parent.nodeIndex).componentView;2&a.def.flags&&(a.state|=8)}if(e.instance[n.bindings[r].name]=o,524288&n.flags){i=i||{};var u=Tn.unwrap(t.oldValues[n.bindingIndex+r]);i[n.bindings[r].nonMinifiedName]=new kn(u,o,0!=(2&t.state))}return t.oldValues[n.bindingIndex+r]=o,i}function ys(t,e){if(t.def.nodeFlags&e)for(var n=t.def.nodes,r=0,o=0;o<n.length;o++){var i=n[o],a=i.parent;for(!a&&i.flags&e&&bs(t,o,i.flags&e,r++),0==(i.childFlags&e)&&(o+=i.childCount);a&&1&a.flags&&o===a.nodeIndex+a.childCount;)a.directChildFlags&e&&(r=ms(t,a,e,r)),a=a.parent}}function ms(t,e,n,r){for(var o=e.nodeIndex+1;o<=e.nodeIndex+e.childCount;o++){var i=t.def.nodes[o];i.flags&n&&bs(t,o,i.flags&n,r++),o+=i.childCount}return r}function bs(t,e,n,r){var o=Oa(t,e);if(o){var i=o.instance;i&&(Na.setCurrentNode(t,e),1048576&n&&Ta(t,512,r)&&i.ngAfterContentInit(),2097152&n&&i.ngAfterContentChecked(),4194304&n&&Ta(t,768,r)&&i.ngAfterViewInit(),8388608&n&&i.ngAfterViewChecked(),131072&n&&i.ngOnDestroy())}}function _s(t){for(var e=t.def.nodeMatchedQueries;t.parent&&tu(t);){var n=t.parentNodeDef;t=t.parent;for(var r=n.nodeIndex+n.childCount,o=0;o<=r;o++)67108864&(i=t.def.nodes[o]).flags&&536870912&i.flags&&(i.query.filterId&e)===i.query.filterId&&Ia(t,o).setDirty(),!(1&i.flags&&o+i.childCount<n.nodeIndex)&&67108864&i.childFlags&&536870912&i.childFlags||(o+=i.childCount)}if(134217728&t.def.nodeFlags)for(o=0;o<t.def.nodes.length;o++){var i;134217728&(i=t.def.nodes[o]).flags&&536870912&i.flags&&Ia(t,o).setDirty(),o+=i.childCount}}function ws(t,e){var n=Ia(t,e.nodeIndex);if(n.dirty){var r,o=void 0;if(67108864&e.flags){var i=e.parent.parent;o=Cs(t,i.nodeIndex,i.nodeIndex+i.childCount,e.query,[]),r=Oa(t,e.parent.nodeIndex).instance}else 134217728&e.flags&&(o=Cs(t,0,t.def.nodes.length-1,e.query,[]),r=t.component);n.reset(o);for(var a=e.query.bindings,u=!1,s=0;s<a.length;s++){var l=a[s],c=void 0;switch(l.bindingType){case 0:c=n.first;break;case 1:c=n,u=!0}r[l.propName]=c}u&&n.notifyOnChanges()}}function Cs(t,e,n,r,o){for(var i=e;i<=n;i++){var a=t.def.nodes[i],u=a.matchedQueries[r.id];if(null!=u&&o.push(Ss(t,a,u)),1&a.flags&&a.element.template&&(a.element.template.nodeMatchedQueries&r.filterId)===r.filterId){var s=Aa(t,i);if((a.childMatchedQueries&r.filterId)===r.filterId&&(Cs(t,i+1,i+a.childCount,r,o),i+=a.childCount),16777216&a.flags)for(var l=s.viewContainer._embeddedViews,c=0;c<l.length;c++){var f=l[c],p=Ka(f);p&&p===s&&Cs(f,0,f.def.nodes.length-1,r,o)}var h=s.template._projectedViews;if(h)for(c=0;c<h.length;c++){var d=h[c];Cs(d,0,d.def.nodes.length-1,r,o)}}(a.childMatchedQueries&r.filterId)!==r.filterId&&(i+=a.childCount)}return o}function Ss(t,e,n){if(null!=n)switch(n){case 1:return Aa(t,e.nodeIndex).renderElement;case 0:return new Kr(Aa(t,e.nodeIndex).renderElement);case 2:return Aa(t,e.nodeIndex).template;case 3:return Aa(t,e.nodeIndex).viewContainer;case 4:return Oa(t,e.nodeIndex).instance}}function Es(t,e,n){var r=ru(t,e,n);r&&su(t,n.ngContent.index,1,r,null,void 0)}function xs(t,e){return function(t,e,n){for(var r=new Array(n.length),o=0;o<n.length;o++){var i=n[o];r[o]={flags:8,name:i,ns:null,nonMinifiedName:i,securityContext:null,suffix:null}}return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:e,flags:128,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:{},matchedQueryIds:0,references:{},ngContentIndex:-1,childCount:0,bindings:r,bindingFlags:hu(r),outputs:[],element:null,provider:null,text:null,query:null,ngContent:null}}(0,t,new Array(e+1))}function Ts(t,e,n){for(var r=new Array(n.length-1),o=1;o<n.length;o++)r[o-1]={flags:8,name:null,ns:null,nonMinifiedName:null,securityContext:null,suffix:n[o]};return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:t,flags:2,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:{},matchedQueryIds:0,references:{},ngContentIndex:e,childCount:0,bindings:r,bindingFlags:8,outputs:[],element:null,provider:null,text:{prefix:n[0]},query:null,ngContent:null}}function ks(t,e,n){var r,o=t.renderer;r=o.createText(n.text.prefix);var i=ru(t,e,n);return i&&o.appendChild(i,r),{renderText:r}}function As(t,e){return(null!=t?t.toString():"")+e.suffix}function Os(t,e,n,r){for(var o=0,i=0,a=0,u=0,s=0,l=null,c=null,f=!1,p=!1,h=null,d=0;d<e.length;d++){var v=e[d];if(v.nodeIndex=d,v.parent=l,v.bindingIndex=o,v.outputIndex=i,v.renderParent=c,a|=v.flags,s|=v.matchedQueryIds,v.element){var g=v.element;g.publicProviders=l?l.element.publicProviders:Object.create(null),g.allProviders=g.publicProviders,f=!1,p=!1,v.element.template&&(s|=v.element.template.nodeMatchedQueries)}if(Is(l,v,e.length),o+=v.bindings.length,i+=v.outputs.length,!c&&3&v.flags&&(h=v),20224&v.flags){f||(f=!0,l.element.publicProviders=Object.create(l.element.publicProviders),l.element.allProviders=l.element.publicProviders);var y=0!=(32768&v.flags);0==(8192&v.flags)||y?l.element.publicProviders[Ua(v.provider.token)]=v:(p||(p=!0,l.element.allProviders=Object.create(l.element.publicProviders)),l.element.allProviders[Ua(v.provider.token)]=v),y&&(l.element.componentProvider=v)}if(l?(l.childFlags|=v.flags,l.directChildFlags|=v.flags,l.childMatchedQueries|=v.matchedQueryIds,v.element&&v.element.template&&(l.childMatchedQueries|=v.element.template.nodeMatchedQueries)):u|=v.flags,v.childCount>0)l=v,Ps(v)||(c=v);else for(;l&&d===l.nodeIndex+l.childCount;){var m=l.parent;m&&(m.childFlags|=l.childFlags,m.childMatchedQueries|=l.childMatchedQueries),c=(l=m)&&Ps(l)?l.renderParent:l}}return{factory:null,nodeFlags:a,rootNodeFlags:u,nodeMatchedQueries:s,flags:t,nodes:e,updateDirectives:n||Ma,updateRenderer:r||Ma,handleEvent:function(t,n,r,o){return e[n].element.handleEvent(t,r,o)},bindingCount:o,outputCount:i,lastRenderRootNode:h}}function Ps(t){return 0!=(1&t.flags)&&null===t.element.name}function Is(t,e,n){var r=e.element&&e.element.template;if(r){if(!r.lastRenderRootNode)throw new Error("Illegal State: Embedded templates without nodes are not allowed!");if(r.lastRenderRootNode&&16777216&r.lastRenderRootNode.flags)throw new Error("Illegal State: Last root node of a template can't have embedded views, at index "+e.nodeIndex+"!")}if(20224&e.flags&&0==(1&(t?t.flags:0)))throw new Error("Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index "+e.nodeIndex+"!");if(e.query){if(67108864&e.flags&&(!t||0==(16384&t.flags)))throw new Error("Illegal State: Content Query nodes need to be children of directives, at index "+e.nodeIndex+"!");if(134217728&e.flags&&t)throw new Error("Illegal State: View Query nodes have to be top level nodes, at index "+e.nodeIndex+"!")}if(e.childCount){var o=t?t.nodeIndex+t.childCount:n-1;if(e.nodeIndex<=o&&e.nodeIndex+e.childCount>o)throw new Error("Illegal State: childCount of node leads outside of parent, at index "+e.nodeIndex+"!")}}function Ns(t,e,n,r){var o=Vs(t.root,t.renderer,t,e,n);return Ms(o,t.component,r),js(o),o}function Rs(t,e,n){var r=Vs(t,t.renderer,null,null,e);return Ms(r,n,n),js(r),r}function Ds(t,e,n,r){var o,i=e.element.componentRendererType;return o=i?t.root.rendererFactory.createRenderer(r,i):t.root.renderer,Vs(t.root,o,t,e.element.componentProvider,n)}function Vs(t,e,n,r,o){var i=new Array(o.nodes.length),a=o.outputCount?new Array(o.outputCount):null;return{def:o,parent:n,viewContainerParent:null,parentNodeDef:r,context:null,component:null,nodes:i,state:13,root:t,renderer:e,oldValues:new Array(o.bindingCount),disposables:a,initIndex:-1}}function Ms(t,e,n){t.component=e,t.context=n}function js(t){var e;Xa(t)&&(e=Aa(t.parent,t.parentNodeDef.parent.nodeIndex).renderElement);for(var n=t.def,r=t.nodes,o=0;o<n.nodes.length;o++){var i=n.nodes[o];Na.setCurrentNode(t,o);var a=void 0;switch(201347067&i.flags){case 1:var u=gu(t,e,i),s=void 0;if(33554432&i.flags){var l=iu(i.element.componentView);s=Na.createComponentView(t,i,l,u)}yu(t,s,i,u),a={renderElement:u,componentView:s,viewContainer:null,template:i.element.template?Hu(t,i):void 0},16777216&i.flags&&(a.viewContainer=Mu(t,i,a));break;case 2:a=ks(t,e,i);break;case 512:case 1024:case 2048:case 256:(a=r[o])||4096&i.flags||(a={instance:us(t,i)});break;case 16:a={instance:ss(t,i)};break;case 16384:(a=r[o])||(a={instance:ls(t,i)}),32768&i.flags&&Ms(Aa(t,i.parent.nodeIndex).componentView,a.instance,a.instance);break;case 32:case 64:case 128:a={value:void 0};break;case 67108864:case 134217728:a=new zi;break;case 8:Es(t,e,i),a=void 0}r[o]=a}Zs(t,Gs.CreateViewNodes),Ks(t,201326592,268435456,0)}function Us(t){Fs(t),Na.updateDirectives(t,1),Qs(t,Gs.CheckNoChanges),Na.updateRenderer(t,1),Zs(t,Gs.CheckNoChanges),t.state&=-97}function Ls(t){1&t.state?(t.state&=-2,t.state|=2):t.state&=-3,xa(t,0,256),Fs(t),Na.updateDirectives(t,0),Qs(t,Gs.CheckAndUpdate),Ks(t,67108864,536870912,0);var e=xa(t,256,512);ys(t,2097152|(e?1048576:0)),Na.updateRenderer(t,0),Zs(t,Gs.CheckAndUpdate),Ks(t,134217728,536870912,0),ys(t,8388608|((e=xa(t,512,768))?4194304:0)),2&t.def.flags&&(t.state&=-9),t.state&=-97,xa(t,768,1024)}function Hs(t,e,n,r,o,i,a,u,s,l,f,p,h){return 0===n?function(t,e,n,r,o,i,a,u,s,l,c,f){switch(201347067&e.flags){case 1:return function(t,e,n,r,o,i,a,u,s,l,c,f){var p=e.bindings.length,h=!1;return p>0&&bu(t,e,0,n)&&(h=!0),p>1&&bu(t,e,1,r)&&(h=!0),p>2&&bu(t,e,2,o)&&(h=!0),p>3&&bu(t,e,3,i)&&(h=!0),p>4&&bu(t,e,4,a)&&(h=!0),p>5&&bu(t,e,5,u)&&(h=!0),p>6&&bu(t,e,6,s)&&(h=!0),p>7&&bu(t,e,7,l)&&(h=!0),p>8&&bu(t,e,8,c)&&(h=!0),p>9&&bu(t,e,9,f)&&(h=!0),h}(t,e,n,r,o,i,a,u,s,l,c,f);case 2:return function(t,e,n,r,o,i,a,u,s,l,c,f){var p=!1,h=e.bindings,d=h.length;if(d>0&&Ga(t,e,0,n)&&(p=!0),d>1&&Ga(t,e,1,r)&&(p=!0),d>2&&Ga(t,e,2,o)&&(p=!0),d>3&&Ga(t,e,3,i)&&(p=!0),d>4&&Ga(t,e,4,a)&&(p=!0),d>5&&Ga(t,e,5,u)&&(p=!0),d>6&&Ga(t,e,6,s)&&(p=!0),d>7&&Ga(t,e,7,l)&&(p=!0),d>8&&Ga(t,e,8,c)&&(p=!0),d>9&&Ga(t,e,9,f)&&(p=!0),p){var v=e.text.prefix;d>0&&(v+=As(n,h[0])),d>1&&(v+=As(r,h[1])),d>2&&(v+=As(o,h[2])),d>3&&(v+=As(i,h[3])),d>4&&(v+=As(a,h[4])),d>5&&(v+=As(u,h[5])),d>6&&(v+=As(s,h[6])),d>7&&(v+=As(l,h[7])),d>8&&(v+=As(c,h[8])),d>9&&(v+=As(f,h[9]));var g=ka(t,e.nodeIndex).renderText;t.renderer.setValue(g,v)}return p}(t,e,n,r,o,i,a,u,s,l,c,f);case 16384:return function(t,e,n,r,o,i,a,u,s,l,c,f){var p=Oa(t,e.nodeIndex),h=p.instance,d=!1,v=void 0,g=e.bindings.length;return g>0&&Ba(t,e,0,n)&&(d=!0,v=gs(t,p,e,0,n,v)),g>1&&Ba(t,e,1,r)&&(d=!0,v=gs(t,p,e,1,r,v)),g>2&&Ba(t,e,2,o)&&(d=!0,v=gs(t,p,e,2,o,v)),g>3&&Ba(t,e,3,i)&&(d=!0,v=gs(t,p,e,3,i,v)),g>4&&Ba(t,e,4,a)&&(d=!0,v=gs(t,p,e,4,a,v)),g>5&&Ba(t,e,5,u)&&(d=!0,v=gs(t,p,e,5,u,v)),g>6&&Ba(t,e,6,s)&&(d=!0,v=gs(t,p,e,6,s,v)),g>7&&Ba(t,e,7,l)&&(d=!0,v=gs(t,p,e,7,l,v)),g>8&&Ba(t,e,8,c)&&(d=!0,v=gs(t,p,e,8,c,v)),g>9&&Ba(t,e,9,f)&&(d=!0,v=gs(t,p,e,9,f,v)),v&&h.ngOnChanges(v),65536&e.flags&&Ta(t,256,e.nodeIndex)&&h.ngOnInit(),262144&e.flags&&h.ngDoCheck(),d}(t,e,n,r,o,i,a,u,s,l,c,f);case 32:case 64:case 128:return function(t,e,n,r,o,i,a,u,s,l,c,f){var p=e.bindings,h=!1,d=p.length;if(d>0&&Ga(t,e,0,n)&&(h=!0),d>1&&Ga(t,e,1,r)&&(h=!0),d>2&&Ga(t,e,2,o)&&(h=!0),d>3&&Ga(t,e,3,i)&&(h=!0),d>4&&Ga(t,e,4,a)&&(h=!0),d>5&&Ga(t,e,5,u)&&(h=!0),d>6&&Ga(t,e,6,s)&&(h=!0),d>7&&Ga(t,e,7,l)&&(h=!0),d>8&&Ga(t,e,8,c)&&(h=!0),d>9&&Ga(t,e,9,f)&&(h=!0),h){var v=Pa(t,e.nodeIndex),g=void 0;switch(201347067&e.flags){case 32:g=new Array(p.length),d>0&&(g[0]=n),d>1&&(g[1]=r),d>2&&(g[2]=o),d>3&&(g[3]=i),d>4&&(g[4]=a),d>5&&(g[5]=u),d>6&&(g[6]=s),d>7&&(g[7]=l),d>8&&(g[8]=c),d>9&&(g[9]=f);break;case 64:g={},d>0&&(g[p[0].name]=n),d>1&&(g[p[1].name]=r),d>2&&(g[p[2].name]=o),d>3&&(g[p[3].name]=i),d>4&&(g[p[4].name]=a),d>5&&(g[p[5].name]=u),d>6&&(g[p[6].name]=s),d>7&&(g[p[7].name]=l),d>8&&(g[p[8].name]=c),d>9&&(g[p[9].name]=f);break;case 128:var y=n;switch(d){case 1:g=y.transform(n);break;case 2:g=y.transform(r);break;case 3:g=y.transform(r,o);break;case 4:g=y.transform(r,o,i);break;case 5:g=y.transform(r,o,i,a);break;case 6:g=y.transform(r,o,i,a,u);break;case 7:g=y.transform(r,o,i,a,u,s);break;case 8:g=y.transform(r,o,i,a,u,s,l);break;case 9:g=y.transform(r,o,i,a,u,s,l,c);break;case 10:g=y.transform(r,o,i,a,u,s,l,c,f)}}v.value=g}return h}(t,e,n,r,o,i,a,u,s,l,c,f);default:throw"unreachable"}}(t,e,r,o,i,a,u,s,l,f,p,h):function(t,e,n){switch(201347067&e.flags){case 1:return function(t,e,n){for(var r=!1,o=0;o<n.length;o++)bu(t,e,o,n[o])&&(r=!0);return r}(t,e,n);case 2:return function(t,e,n){for(var r=e.bindings,o=!1,i=0;i<n.length;i++)Ga(t,e,i,n[i])&&(o=!0);if(o){var a="";for(i=0;i<n.length;i++)a+=As(n[i],r[i]);a=e.text.prefix+a;var u=ka(t,e.nodeIndex).renderText;t.renderer.setValue(u,a)}return o}(t,e,n);case 16384:return function(t,e,n){for(var r=Oa(t,e.nodeIndex),o=r.instance,i=!1,a=void 0,u=0;u<n.length;u++)Ba(t,e,u,n[u])&&(i=!0,a=gs(t,r,e,u,n[u],a));return a&&o.ngOnChanges(a),65536&e.flags&&Ta(t,256,e.nodeIndex)&&o.ngOnInit(),262144&e.flags&&o.ngDoCheck(),i}(t,e,n);case 32:case 64:case 128:return function(t,e,n){for(var r=e.bindings,o=!1,i=0;i<n.length;i++)Ga(t,e,i,n[i])&&(o=!0);if(o){var a=Pa(t,e.nodeIndex),u=void 0;switch(201347067&e.flags){case 32:u=n;break;case 64:for(u={},i=0;i<n.length;i++)u[r[i].name]=n[i];break;case 128:var s=n[0],l=n.slice(1);u=s.transform.apply(s,c(l))}a.value=u}return o}(t,e,n);default:throw"unreachable"}}(t,e,r)}function Fs(t){var e=t.def;if(4&e.nodeFlags)for(var n=0;n<e.nodes.length;n++){var r=e.nodes[n];if(4&r.flags){var o=Aa(t,n).template._projectedViews;if(o)for(var i=0;i<o.length;i++){var a=o[i];a.state|=32,Wa(a,t)}}else 0==(4&r.childFlags)&&(n+=r.childCount)}}function zs(t,e,n,r,o,i,a,u,s,l,c,f,p){return 0===n?function(t,e,n,r,o,i,a,u,s,l,c,f){var p=e.bindings.length;p>0&&Za(t,e,0,n),p>1&&Za(t,e,1,r),p>2&&Za(t,e,2,o),p>3&&Za(t,e,3,i),p>4&&Za(t,e,4,a),p>5&&Za(t,e,5,u),p>6&&Za(t,e,6,s),p>7&&Za(t,e,7,l),p>8&&Za(t,e,8,c),p>9&&Za(t,e,9,f)}(t,e,r,o,i,a,u,s,l,c,f,p):function(t,e,n){for(var r=0;r<n.length;r++)Za(t,e,r,n[r])}(t,e,r),!1}function qs(t,e){if(Ia(t,e.nodeIndex).dirty)throw Ra(Na.createDebugContext(t,e.nodeIndex),"Query "+e.query.id+" not dirty","Query "+e.query.id+" dirty",0!=(1&t.state))}function Bs(t){if(!(128&t.state)){if(Qs(t,Gs.Destroy),Zs(t,Gs.Destroy),ys(t,131072),t.disposables)for(var e=0;e<t.disposables.length;e++)t.disposables[e]();!function(t){if(16&t.state){var e=Ka(t);if(e){var n=e.template._projectedViews;n&&(Iu(n,n.indexOf(t)),Na.dirtyParentQueries(t))}}}(t),t.renderer.destroyNode&&function(t){for(var e=t.def.nodes.length,n=0;n<e;n++){var r=t.def.nodes[n];1&r.flags?t.renderer.destroyNode(Aa(t,n).renderElement):2&r.flags?t.renderer.destroyNode(ka(t,n).renderText):(67108864&r.flags||134217728&r.flags)&&Ia(t,n).destroy()}}(t),Xa(t)&&t.renderer.destroy(),t.state|=128}}var Gs=function(t){return t[t.CreateViewNodes=0]="CreateViewNodes",t[t.CheckNoChanges=1]="CheckNoChanges",t[t.CheckNoChangesProjectedViews=2]="CheckNoChangesProjectedViews",t[t.CheckAndUpdate=3]="CheckAndUpdate",t[t.CheckAndUpdateProjectedViews=4]="CheckAndUpdateProjectedViews",t[t.Destroy=5]="Destroy",t}({});function Zs(t,e){var n=t.def;if(33554432&n.nodeFlags)for(var r=0;r<n.nodes.length;r++){var o=n.nodes[r];33554432&o.flags?Ws(Aa(t,r).componentView,e):0==(33554432&o.childFlags)&&(r+=o.childCount)}}function Qs(t,e){var n=t.def;if(16777216&n.nodeFlags)for(var r=0;r<n.nodes.length;r++){var o=n.nodes[r];if(16777216&o.flags)for(var i=Aa(t,r).viewContainer._embeddedViews,a=0;a<i.length;a++)Ws(i[a],e);else 0==(16777216&o.childFlags)&&(r+=o.childCount)}}function Ws(t,e){var n=t.state;switch(e){case Gs.CheckNoChanges:0==(128&n)&&(12==(12&n)?Us(t):64&n&&Ys(t,Gs.CheckNoChangesProjectedViews));break;case Gs.CheckNoChangesProjectedViews:0==(128&n)&&(32&n?Us(t):64&n&&Ys(t,e));break;case Gs.CheckAndUpdate:0==(128&n)&&(12==(12&n)?Ls(t):64&n&&Ys(t,Gs.CheckAndUpdateProjectedViews));break;case Gs.CheckAndUpdateProjectedViews:0==(128&n)&&(32&n?Ls(t):64&n&&Ys(t,e));break;case Gs.Destroy:Bs(t);break;case Gs.CreateViewNodes:js(t)}}function Ys(t,e){Qs(t,e),Zs(t,e)}function Ks(t,e,n,r){if(t.def.nodeFlags&e&&t.def.nodeFlags&n)for(var o=t.def.nodes.length,i=0;i<o;i++){var a=t.def.nodes[i];if(a.flags&e&&a.flags&n)switch(Na.setCurrentNode(t,a.nodeIndex),r){case 0:ws(t,a);break;case 1:qs(t,a)}a.childFlags&e&&a.childFlags&n||(i+=a.childCount)}}var $s=!1;function Js(t,e,n,r,o,i){var a=o.injector.get(Xr);return Rs(tl(t,o,a,e,n),r,i)}function
(t,e,n,r,o,i){var a=o.injector.get(Xr),u=tl(t,o,new Nl(a),e,n),s=cl(r);return Pl(bl.create,Rs,null,[u,s,i])}function tl(t,e,n,r,o){var i=e.injector.get(oo),a=e.injector.get($o),u=n.createRenderer(null,null);return{ngModule:e,injector:t,projectableNodes:r,selectorOrNode:o,sanitizer:i,rendererFactory:n,renderer:u,errorHandler:a}}function el(t,e,n,r){var o=cl(n);return Pl(bl.create,Ns,null,[t,e,o,r])}function nl(t,e,n,r){return n=al.get(e.element.componentProvider.provider.token)||cl(n),Pl(bl.create,Ds,null,[t,e,n,r])}function rl(t,e,n,r){return Qu(t,e,n,function(t){var e=function(t){var e=!1,n=!1;return 0===ol.size?{hasOverrides:e,hasDeprecatedOverrides:n}:(t.providers.forEach(function(t){var r=ol.get(t.token);3840&t.flags&&r&&(e=!0,n=n||r.deprecatedBehavior)}),t.modules.forEach(function(t){il.forEach(function(r,o){Et(o).providedIn===t&&(e=!0,n=n||r.deprecatedBehavior)})}),{hasOverrides:e,hasDeprecatedOverrides:n})}(t),n=e.hasDeprecatedOverrides;return e.hasOverrides?(function(t){for(var e=0;e<t.providers.length;e++){var r=t.providers[e];n&&(r.flags|=4096);var o=ol.get(r.token);o&&(r.flags=-3841&r.flags|o.flags,r.deps=nu(o.deps),r.value=o.value)}if(il.size>0){var i=new Set(t.modules);il.forEach(function(e,r){if(i.has(Et(r).providedIn)){var o={token:r,flags:e.flags|(n?4096:0),deps:nu(e.deps),value:e.value,index:t.providers.length};t.providers.push(o),t.providersByKey[Ua(r)]=o}})}}(t=t.factory(function(){return Ma})),t):t}(r))}var ol=new Map,il=new Map,al=new Map;function ul(t){var e;ol.set(t.token,t),"function"==typeof t.token&&(e=Et(t.token))&&"function"==typeof e.providedIn&&il.set(t.token,t)}function sl(t,e){var n=iu(e.viewDefFactory),r=iu(n.nodes[0].element.componentView);al.set(t,r)}function ll(){ol.clear(),il.clear(),al.clear()}function cl(t){if(0===ol.size)return t;var e=function(t){for(var e=[],n=null,r=0;r<t.nodes.length;r++){var o=t.nodes[r];1&o.flags&&(n=o),n&&3840&o.flags&&ol.has(o.provider.token)&&(e.push(n.nodeIndex),n=null)}return e}(t);if(0===e.length)return t;t=t.factory(function(){return Ma});for(var n=0;n<e.length;n++)r(t,e[n]);return t;function r(t,e){for(var n=e+1;n<t.nodes.length;n++){var r=t.nodes[n];if(1&r.flags)return;if(3840&r.flags){var o=r.provider,i=ol.get(o.token);i&&(r.flags=-3841&r.flags|i.flags,o.deps=nu(i.deps),o.value=i.value)}}}}function fl(t,e,n,r,o,i,a,u,s,l,c,f,p){var h=t.def.nodes[e];return Hs(t,h,n,r,o,i,a,u,s,l,c,f,p),224&h.flags?Pa(t,e).value:void 0}function pl(t,e,n,r,o,i,a,u,s,l,c,f,p){var h=t.def.nodes[e];return zs(t,h,n,r,o,i,a,u,s,l,c,f,p),224&h.flags?Pa(t,e).value:void 0}function hl(t){return Pl(bl.detectChanges,Ls,null,[t])}function dl(t){return Pl(bl.checkNoChanges,Us,null,[t])}function vl(t){return Pl(bl.destroy,Bs,null,[t])}var gl,yl,ml,bl=function(t){return t[t.create=0]="create",t[t.detectChanges=1]="detectChanges",t[t.checkNoChanges=2]="checkNoChanges",t[t.destroy=3]="destroy",t[t.handleEvent=4]="handleEvent",t}({});function _l(t,e){yl=t,ml=e}function wl(t,e,n,r){return _l(t,e),Pl(bl.handleEvent,t.def.handleEvent,null,[t,e,n,r])}function Cl(t,e){if(128&t.state)throw Va(bl[gl]);return _l(t,Tl(t,0)),t.def.updateDirectives(function(t,n,r){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];var a=t.def.nodes[n];return 0===e?El(t,a,r,o):xl(t,a,r,o),16384&a.flags&&_l(t,Tl(t,n)),224&a.flags?Pa(t,a.nodeIndex).value:void 0},t)}function Sl(t,e){if(128&t.state)throw Va(bl[gl]);return _l(t,kl(t,0)),t.def.updateRenderer(function(t,n,r){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];var a=t.def.nodes[n];return 0===e?El(t,a,r,o):xl(t,a,r,o),3&a.flags&&_l(t,kl(t,n)),224&a.flags?Pa(t,a.nodeIndex).value:void 0},t)}function El(t,e,n,r){if(Hs.apply(void 0,c([t,e,n],r))){var o=1===n?r[0]:r;if(16384&e.flags){for(var i={},a=0;a<e.bindings.length;a++){var u=e.bindings[a],s=o[a];8&u.flags&&(i[(h=u.nonMinifiedName,"ng-reflect-"+h.replace(/[$@]/g,"_").replace(Sn,function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return"-"+t[1].toLowerCase()}))]=En(s))}var l=e.parent,f=Aa(t,l.nodeIndex).renderElement;if(l.element.name)for(var p in i)null!=(s=i[p])?t.renderer.setAttribute(f,p,s):t.renderer.removeAttribute(f,p);else t.renderer.setValue(f,"bindings="+JSON.stringify(i,null,2))}}var h}function xl(t,e,n,r){zs.apply(void 0,c([t,e,n],r))}function Tl(t,e){for(var n=e;n<t.def.nodes.length;n++){var r=t.def.nodes[n];if(16384&r.flags&&r.bindings&&r.bindings.length)return n}return null}function kl(t,e){for(var n=e;n<t.def.nodes.length;n++){var r=t.def.nodes[n];if(3&r.flags&&r.bindings&&r.bindings.length)return n}return null}var Al=function(){function t(t,e){this.view=t,this.nodeIndex=e,null==e&&(this.nodeIndex=e=0),this.nodeDef=t.def.nodes[e];for(var n=this.nodeDef,r=t;n&&0==(1&n.flags);)n=n.parent;if(!n)for(;!n&&r;)n=$a(r),r=r.parent;this.elDef=n,this.elView=r}return Object.defineProperty(t.prototype,"elOrCompView",{get:function(){return Aa(this.elView,this.elDef.nodeIndex).componentView||this.view},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"injector",{get:function(){return zu(this.elView,this.elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"component",{get:function(){return this.elOrCompView.component},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this.elOrCompView.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"providerTokens",{get:function(){var t=[];if(this.elDef)for(var e=this.elDef.nodeIndex+1;e<=this.elDef.nodeIndex+this.elDef.childCount;e++){var n=this.elView.def.nodes[e];20224&n.flags&&t.push(n.provider.token),e+=n.childCount}return t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"references",{get:function(){var t={};if(this.elDef){Ol(this.elView,this.elDef,t);for(var e=this.elDef.nodeIndex+1;e<=this.elDef.nodeIndex+this.elDef.childCount;e++){var n=this.elView.def.nodes[e];20224&n.flags&&Ol(this.elView,n,t),e+=n.childCount}}return t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentRenderElement",{get:function(){var t=function(t){for(;t&&!Xa(t);)t=t.parent;return t.parent?Aa(t.parent,$a(t).nodeIndex):null}(this.elOrCompView);return t?t.renderElement:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"renderNode",{get:function(){return 2&this.nodeDef.flags?Ja(this.view,this.nodeDef):Ja(this.elView,this.elDef)},enumerable:!0,configurable:!0}),t.prototype.logError=function(t){for(var e,n,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];2&this.nodeDef.flags?(e=this.view.def,n=this.nodeDef.nodeIndex):(e=this.elView.def,n=this.elDef.nodeIndex);var i=function(t,e){for(var n=-1,r=0;r<=e;r++)3&t.nodes[r].flags&&n++;return n}(e,n),a=-1;e.factory(function(){var e;return++a===i?(e=t.error).bind.apply(e,c([t],r)):Ma}),a<i&&(t.error("Illegal state: the ViewDefinitionFactory did not call the logger!"),t.error.apply(t,c(r)))},t}();function Ol(t,e,n){for(var r in e.references)n[r]=Ss(t,e,e.references[r])}function Pl(t,e,n,r){var o=gl,i=yl,a=ml;try{gl=t;var u=e.apply(n,r);return yl=i,ml=a,gl=o,u}catch(s){if(Wo(s)||!yl)throw s;throw function(t,e){return t instanceof Error||(t=new Error(t.toString())),Da(t,e),t}(s,Il())}}function Il(){return yl?new Al(yl,ml):null}var Nl=function(){function t(t){this.delegate=t}return t.prototype.createRenderer=function(t,e){return new Rl(this.delegate.createRenderer(t,e))},t.prototype.begin=function(){this.delegate.begin&&this.delegate.begin()},t.prototype.end=function(){this.delegate.end&&this.delegate.end()},t.prototype.whenRenderingDone=function(){return this.delegate.whenRenderingDone?this.delegate.whenRenderingDone():Promise.resolve(null)},t}(),Rl=function(){function t(t){this.delegate=t,this.debugContextFactory=Il,this.data=this.delegate.data}return t.prototype.createDebugContext=function(t){return this.debugContextFactory(t)},t.prototype.destroyNode=function(t){!function(t){ea.delete(t.nativeNode)}(na(t)),this.delegate.destroyNode&&this.delegate.destroyNode(t)},t.prototype.destroy=function(){this.delegate.destroy()},t.prototype.createElement=function(t,e){var n=this.delegate.createElement(t,e),r=this.createDebugContext(n);if(r){var o=new ta(n,null,r);o.name=t,ra(o)}return n},t.prototype.createComment=function(t){var e=this.delegate.createComment(t),n=this.createDebugContext(e);return n&&ra(new Xi(e,null,n)),e},t.prototype.createText=function(t){var e=this.delegate.createText(t),n=this.createDebugContext(e);return n&&ra(new Xi(e,null,n)),e},t.prototype.appendChild=function(t,e){var n=na(t),r=na(e);n&&r&&n instanceof ta&&n.addChild(r),this.delegate.appendChild(t,e)},t.prototype.insertBefore=function(t,e,n){var r=na(t),o=na(e),i=na(n);r&&o&&r instanceof ta&&r.insertBefore(i,o),this.delegate.insertBefore(t,e,n)},t.prototype.removeChild=function(t,e){var n=na(t),r=na(e);n&&r&&n instanceof ta&&n.removeChild(r),this.delegate.removeChild(t,e)},t.prototype.selectRootElement=function(t,e){var n=this.delegate.selectRootElement(t,e),r=Il();return r&&ra(new ta(n,null,r)),n},t.prototype.setAttribute=function(t,e,n,r){var o=na(t);o&&o instanceof ta&&(o.attributes[r?r+":"+e:e]=n),this.delegate.setAttribute(t,e,n,r)},t.prototype.removeAttribute=function(t,e,n){var r=na(t);r&&r instanceof ta&&(r.attributes[n?n+":"+e:e]=null),this.delegate.removeAttribute(t,e,n)},t.prototype.addClass=function(t,e){var n=na(t);n&&n instanceof ta&&(n.classes[e]=!0),this.delegate.addClass(t,e)},t.prototype.removeClass=function(t,e){var n=na(t);n&&n instanceof ta&&(n.classes[e]=!1),this.delegate.removeClass(t,e)},t.prototype.setStyle=function(t,e,n,r){var o=na(t);o&&o instanceof ta&&(o.styles[e]=n),this.delegate.setStyle(t,e,n,r)},t.prototype.removeStyle=function(t,e,n){var r=na(t);r&&r instanceof ta&&(r.styles[e]=null),this.delegate.removeStyle(t,e,n)},t.prototype.setProperty=function(t,e,n){var r=na(t);r&&r instanceof ta&&(r.properties[e]=n),this.delegate.setProperty(t,e,n)},t.prototype.listen=function(t,e,n){if("string"!=typeof t){var r=na(t);r&&r.listeners.push(new Ji(e,n))}return this.delegate.listen(t,e,n)},t.prototype.parentNode=function(t){return this.delegate.parentNode(t)},t.prototype.nextSibling=function(t){return this.delegate.nextSibling(t)},t.prototype.setValue=function(t,e){return this.delegate.setValue(t,e)},t}();function Dl(t,e,n){return new Vl(t,e,n)}var Vl=function(t){function e(e,n,r){var o=t.call(this)||this;return o.moduleType=e,o._bootstrapComponents=n,o._ngModuleDefFactory=r,o}return o(e,t),e.prototype.create=function(t){!function(){if(!$s){$s=!0;var t=go()?{setCurrentNode:_l,createRootView:Xs,createEmbeddedView:el,createComponentView:nl,createNgModuleRef:rl,overrideProvider:ul,overrideComponentView:sl,clearOverrides:ll,checkAndUpdateView:hl,checkNoChangesView:dl,destroyView:vl,createDebugContext:function(t,e){return new Al(t,e)},handleEvent:wl,updateDirectives:Cl,updateRenderer:Sl}:{setCurrentNode:function(){},createRootView:Js,createEmbeddedView:Ns,createComponentView:Ds,createNgModuleRef:Qu,overrideProvider:Ma,overrideComponentView:Ma,clearOverrides:Ma,checkAndUpdateView:Ls,checkNoChangesView:Us,destroyView:Bs,createDebugContext:function(t,e){return new Al(t,e)},handleEvent:function(t,e,n,r){return t.def.handleEvent(t,e,n,r)},updateDirectives:function(t,e){return t.def.updateDirectives(0===e?fl:pl,t)},updateRenderer:function(t,e){return t.def.updateRenderer(0===e?fl:pl,t)}};Na.setCurrentNode=t.setCurrentNode,Na.createRootView=t.createRootView,Na.createEmbeddedView=t.createEmbeddedView,Na.createComponentView=t.createComponentView,Na.createNgModuleRef=t.createNgModuleRef,Na.overrideProvider=t.overrideProvider,Na.overrideComponentView=t.overrideComponentView,Na.clearOverrides=t.clearOverrides,Na.checkAndUpdateView=t.checkAndUpdateView,Na.checkNoChangesView=t.checkNoChangesView,Na.destroyView=t.destroyView,Na.resolveDep=ds,Na.createDebugContext=t.createDebugContext,Na.handleEvent=t.handleEvent,Na.updateDirectives=t.updateDirectives,Na.updateRenderer=t.updateRenderer,Na.dirtyParentQueries=_s}}();var e=function(t){var e=Array.from(t.providers),n=Array.from(t.modules),r={};for(var o in t.providersByKey)r[o]=t.providersByKey[o];return{factory:t.factory,isRoot:t.isRoot,providers:e,modules:n,providersByKey:r}}(iu(this._ngModuleDefFactory));return Na.createNgModuleRef(this.moduleType,t||pr.NULL,this._bootstrapComponents,e)},e}(Wr),Ml=function(){return function(){}}(),jl=function(){return function(){}}(),Ul=function(){return function(){}}(),Ll=new Tt("Location Initialized"),Hl=function(){return function(){}}(),Fl=new Tt("appBaseHref"),zl=function(){function t(t){var n=this;this._subject=new Lo,this._platformStrategy=t;var r=this._platformStrategy.getBaseHref();this._baseHref=e.stripTrailingSlash(ql(r)),this._platformStrategy.onPopState(function(t){n._subject.emit({url:n.path(!0),pop:!0,state:t.state,type:t.type})})}var e;return e=t,t.prototype.path=function(t){return void 0===t&&(t=!1),this.normalize(this._platformStrategy.path(t))},t.prototype.isCurrentPathEqualTo=function(t,n){return void 0===n&&(n=""),this.path()==this.normalize(t+e.normalizeQueryParams(n))},t.prototype.normalize=function(t){return e.stripTrailingSlash(function(t,e){return t&&e.startsWith(t)?e.substring(t.length):e}(this._baseHref,ql(t)))},t.prototype.prepareExternalUrl=function(t){return t&&"/"!==t[0]&&(t="/"+t),this._platformStrategy.prepareExternalUrl(t)},t.prototype.go=function(t,e,n){void 0===e&&(e=""),void 0===n&&(n=null),this._platformStrategy.pushState(n,"",t,e)},t.prototype.replaceState=function(t,e,n){void 0===e&&(e=""),void 0===n&&(n=null),this._platformStrategy.replaceState(n,"",t,e)},t.prototype.forward=function(){this._platformStrategy.forward()},t.prototype.back=function(){this._platformStrategy.back()},t.prototype.subscribe=function(t,e,n){return this._subject.subscribe({next:t,error:e,complete:n})},t.normalizeQueryParams=function(t){return t&&"?"!==t[0]?"?"+t:t},t.joinWithSlash=function(t,e){if(0==t.length)return e;if(0==e.length)return t;var n=0;return t.endsWith("/")&&n++,e.startsWith("/")&&n++,2==n?t+e.substring(1):1==n?t+e:t+"/"+e},t.stripTrailingSlash=function(t){var e=t.match(/#|\?|$/),n=e&&e.index||t.length;return t.slice(0,n-("/"===t[n-1]?1:0))+t.slice(n)},t}();function ql(t){return t.replace(/\/index.html$/,"")}var Bl=function(t){function e(e,n){var r=t.call(this)||this;return r._platformLocation=e,r._baseHref="",null!=n&&(r._baseHref=n),r}return o(e,t),e.prototype.onPopState=function(t){this._platformLocation.onPopState(t),this._platformLocation.onHashChange(t)},e.prototype.getBaseHref=function(){return this._baseHref},e.prototype.path=function(t){void 0===t&&(t=!1);var e=this._platformLocation.hash;return null==e&&(e="#"),e.length>0?e.substring(1):e},e.prototype.prepareExternalUrl=function(t){var e=zl.joinWithSlash(this._baseHref,t);return e.length>0?"#"+e:e},e.prototype.pushState=function(t,e,n,r){var o=this.prepareExternalUrl(n+zl.normalizeQueryParams(r));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.pushState(t,e,o)},e.prototype.replaceState=function(t,e,n,r){var o=this.prepareExternalUrl(n+zl.normalizeQueryParams(r));0==o.length&&(o=this._platformLocation.pathname),this._platformLocation.replaceState(t,e,o)},e.prototype.forward=function(){this._platformLocation.forward()},e.prototype.back=function(){this._platformLocation.back()},e}(Hl),Gl=function(t){function e(e,n){var r=t.call(this)||this;if(r._platformLocation=e,null==n&&(n=r._platformLocation.getBaseHrefFromDOM()),null==n)throw new Error("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.");return r._baseHref=n,r}return o(e,t),e.prototype.onPopState=function(t){this._platformLocation.onPopState(t),this._platformLocation.onHashChange(t)},e.prototype.getBaseHref=function(){return this._baseHref},e.prototype.prepareExternalUrl=function(t){return zl.joinWithSlash(this._baseHref,t)},e.prototype.path=function(t){void 0===t&&(t=!1);var e=this._platformLocation.pathname+zl.normalizeQueryParams(this._platformLocation.search),n=this._platformLocation.hash;return n&&t?""+e+n:e},e.prototype.pushState=function(t,e,n,r){var o=this.prepareExternalUrl(n+zl.normalizeQueryParams(r));this._platformLocation.pushState(t,e,o)},e.prototype.replaceState=function(t,e,n,r){var o=this.prepareExternalUrl(n+zl.normalizeQueryParams(r));this._platformLocation.replaceState(t,e,o)},e.prototype.forward=function(){this._platformLocation.forward()},e.prototype.back=function(){this._platformLocation.back()},e}(Hl),Zl=void 0,Ql=["en",[["a","p"],["AM","PM"],Zl],[["AM","PM"],Zl,Zl],[["S","M","T","W","T","F","S"],["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],["Su","Mo","Tu","We","Th","Fr","Sa"]],Zl,[["J","F","M","A","M","J","J","A","S","O","N","D"],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],["January","February","March","April","May","June","July","August","September","October","November","December"]],Zl,[["B","A"],["BC","AD"],["Before Christ","Anno Domini"]],0,[6,0],["M/d/yy","MMM d, y","MMMM d, y","EEEE, MMMM d, y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1}, {0}",Zl,"{1} 'at' {0}",Zl],[".",",",";","%","+","-","E","\xd7","\u2030","\u221e","NaN",":"],["#,##0.###","#,##0%","\xa4#,##0.00","#E0"],"$","US Dollar",{},function(t){var e=Math.floor(Math.abs(t)),n=t.toString().replace(/^[^.]*\.?/,"").length;return 1===e&&0===n?1:5}],Wl={},Yl=function(t){return t[t.Zero=0]="Zero",t[t.One=1]="One",t[t.Two=2]="Two",t[t.Few=3]="Few",t[t.Many=4]="Many",t[t.Other=5]="Other",t}({}),Kl=function(t){return t[t.Format=0]="Format",t[t.Standalone=1]="Standalone",t}({}),$l=function(t){return t[t.Narrow=0]="Narrow",t[t.Abbreviated=1]="Abbreviated",t[t.Wide=2]="Wide",t[t.Short=3]="Short",t}({}),Jl=function(t){return t[t.Short=0]="Short",t[t.Medium=1]="Medium",t[t.Long=2]="Long",t[t.Full=3]="Full",t}({}),Xl=function(t){return t[t.Decimal=0]="Decimal",t[t.Group=1]="Group",t[t.List=2]="List",t[t.PercentSign=3]="PercentSign",t[t.PlusSign=4]="PlusSign",t[t.MinusSign=5]="MinusSign",t[t.Exponential=6]="Exponential",t[t.SuperscriptingExponent=7]="SuperscriptingExponent",t[t.PerMille=8]="PerMille",t[t[1/0]=9]="Infinity",t[t.NaN=10]="NaN",t[t.TimeSeparator=11]="TimeSeparator",t[t.CurrencyDecimal=12]="CurrencyDecimal",t[t.CurrencyGroup=13]="CurrencyGroup",t}({});function tc(t,e){return ic(uc(t)[10],e)}function ec(t,e){return ic(uc(t)[11],e)}function nc(t,e){return ic(uc(t)[12],e)}function rc(t,e){var n=uc(t),r=n[13][e];if(void 0===r){if(e===Xl.CurrencyDecimal)return n[13][Xl.Decimal];if(e===Xl.CurrencyGroup)return n[13][Xl.Group]}return r}function oc(t){if(!t[19])throw new Error('Missing extra locale data for the locale "'+t[0]+'". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.')}function ic(t,e){for(var n=e;n>-1;n--)if(void 0!==t[n])return t[n];throw new Error("Locale data API: locale data undefined")}function ac(t){var e=l(t.split(":"),2);return{hours:+e[0],minutes:+e[1]}}function uc(t){var e=t.toLowerCase().replace(/_/g,"-"),n=Wl[e];if(n)return n;var r=e.split("-")[0];if(n=Wl[r])return n;if("en"===r)return Ql;throw new Error('Missing locale data for the locale "'+t+'".')}var sc=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/,lc={},cc=/((?:[^GyMLwWdEabBhHmsSzZO']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/,fc=function(t){return t[t.Short=0]="Short",t[t.ShortGMT=1]="ShortGMT",t[t.Long=2]="Long",t[t.Extended=3]="Extended",t}({}),pc=function(t){return t[t.FullYear=0]="FullYear",t[t.Month=1]="Month",t[t.Date=2]="Date",t[t.Hours=3]="Hours",t[t.Minutes=4]="Minutes",t[t.Seconds=5]="Seconds",t[t.FractionalSeconds=6]="FractionalSeconds",t[t.Day=7]="Day",t}({}),hc=function(t){return t[t.DayPeriods=0]="DayPeriods",t[t.Days=1]="Days",t[t.Months=2]="Months",t[t.Eras=3]="Eras",t}({});function dc(t,e){return e&&(t=t.replace(/\{([^}]+)}/g,function(t,n){return null!=e&&n in e?e[n]:t})),t}function vc(t,e,n,r,o){void 0===n&&(n="-");var i="";(t<0||o&&t<=0)&&(o?t=1-t:(t=-t,i=n));for(var a=String(t);a.length<e;)a="0"+a;return r&&(a=a.substr(a.length-e)),i+a}function gc(t,e,n,r,o){return void 0===n&&(n=0),void 0===r&&(r=!1),void 0===o&&(o=!1),function(i,a){var u,s=function(t,e){switch(t){case pc.FullYear:return e.getFullYear();case pc.Month:return e.getMonth();case pc.Date:return e.getDate();case pc.Hours:return e.getHours();case pc.Minutes:return e.getMinutes();case pc.Seconds:return e.getSeconds();case pc.FractionalSeconds:return e.getMilliseconds();case pc.Day:return e.getDay();default:throw new Error('Unknown DateType value "'+t+'".')}}(t,i);if((n>0||s>-n)&&(s+=n),t===pc.Hours)0===s&&-12===n&&(s=12);else if(t===pc.FractionalSeconds)return u=e,vc(s,3).substr(0,u);var l=rc(a,Xl.MinusSign);return vc(s,e,l,r,o)}}function yc(t,e,n,r){return void 0===n&&(n=Kl.Format),void 0===r&&(r=!1),function(o,i){return function(t,e,n,r,o,i){switch(n){case hc.Months:return function(t,e,n){var r=uc(t),o=ic([r[5],r[6]],e);return ic(o,n)}(e,o,r)[t.getMonth()];case hc.Days:return function(t,e,n){var r=uc(t),o=ic([r[3],r[4]],e);return ic(o,n)}(e,o,r)[t.getDay()];case hc.DayPeriods:var a=t.getHours(),u=t.getMinutes();if(i){var s,l=function(t){var e=uc(t);return oc(e),(e[19][2]||[]).map(function(t){return"string"==typeof t?ac(t):[ac(t[0]),ac(t[1])]})}(e),c=function(t,e,n){var r=uc(t);oc(r);var o=ic([r[19][0],r[19][1]],e)||[];return ic(o,n)||[]}(e,o,r);if(l.forEach(function(t,e){if(Array.isArray(t)){var n=t[0],r=t[1],o=r.hours;a>=n.hours&&u>=n.minutes&&(a<o||a===o&&u<r.minutes)&&(s=c[e])}else t.hours===a&&t.minutes===u&&(s=c[e])}),s)return s}return function(t,e,n){var r=uc(t),o=ic([r[1],r[2]],e);return ic(o,n)}(e,o,r)[a<12?0:1];case hc.Eras:return function(t,e){return ic(uc(t)[7],e)}(e,r)[t.getFullYear()<=0?0:1];default:throw new Error("unexpected translation type "+n)}}(o,i,t,e,n,r)}}function mc(t){return function(e,n,r){var o=-1*r,i=rc(n,Xl.MinusSign),a=o>0?Math.floor(o/60):Math.ceil(o/60);switch(t){case fc.Short:return(o>=0?"+":"")+vc(a,2,i)+vc(Math.abs(o%60),2,i);case fc.ShortGMT:return"GMT"+(o>=0?"+":"")+vc(a,1,i);case fc.Long:return"GMT"+(o>=0?"+":"")+vc(a,2,i)+":"+vc(Math.abs(o%60),2,i);case fc.Extended:return 0===r?"Z":(o>=0?"+":"")+vc(a,2,i)+":"+vc(Math.abs(o%60),2,i);default:throw new Error('Unknown zone width "'+t+'"')}}}var bc=0,_c=4;function wc(t,e){return void 0===e&&(e=!1),function(n,r){var o,i,a,u;if(e){var s=new Date(n.getFullYear(),n.getMonth(),1).getDay()-1,l=n.getDate();o=1+Math.floor((l+s)/7)}else{var c=(a=n.getFullYear(),u=new Date(a,bc,1).getDay(),new Date(a,0,1+(u<=_c?_c:_c+7)-u)),f=(i=n,new Date(i.getFullYear(),i.getMonth(),i.getDate()+(_c-i.getDay()))).getTime()-c.getTime();o=1+Math.round(f/6048e5)}return vc(o,t,rc(r,Xl.MinusSign))}}var Cc={};function Sc(t,e){t=t.replace(/:/g,"");var n=Date.parse("Jan 01, 1970 00:00:00 "+t)/6e4;return isNaN(n)?e:n}function Ec(t){return t instanceof Date&&!isNaN(t.valueOf())}var xc=new Tt("UseV4Plurals"),Tc=function(){return function(){}}(),kc=function(t){function e(e,n){var r=t.call(this)||this;return r.locale=e,r.deprecatedPluralFn=n,r}return o(e,t),e.prototype.getPluralCategory=function(t,e){switch(this.deprecatedPluralFn?this.deprecatedPluralFn(e||this.locale,t):function(t){return uc(t)[18]}(e||this.locale)(t)){case Yl.Zero:return"zero";case Yl.One:return"one";case Yl.Two:return"two";case Yl.Few:return"few";case Yl.Many:return"many";default:return"other"}},e}(Tc),Ac=function(){function t(t,e,n,r){this.$implicit=t,this.ngForOf=e,this.index=n,this.count=r}return Object.defineProperty(t.prototype,"first",{get:function(){return 0===this.index},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"last",{get:function(){return this.index===this.count-1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"even",{get:function(){return this.index%2==0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"odd",{get:function(){return!this.even},enumerable:!0,configurable:!0}),t}(),Oc=function(){function t(t,e,n){this._viewContainer=t,this._template=e,this._differs=n,this._ngForOfDirty=!0,this._differ=null}return Object.defineProperty(t.prototype,"ngForOf",{set:function(t){this._ngForOf=t,this._ngForOfDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngForTrackBy",{get:function(){return this._trackByFn},set:function(t){go()&&null!=t&&"function"!=typeof t&&console&&console.warn&&console.warn("trackBy must be a function, but received "+JSON.stringify(t)+". See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information."),this._trackByFn=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngForTemplate",{set:function(t){t&&(this._template=t)},enumerable:!0,configurable:!0}),t.prototype.ngDoCheck=function(){if(this._ngForOfDirty){this._ngForOfDirty=!1;var t=this._ngForOf;if(!this._differ&&t)try{this._differ=this._differs.find(t).create(this.ngForTrackBy)}catch(r){throw new Error("Cannot find a differ supporting object '"+t+"' of type '"+((e=t).name||typeof e)+"'. NgFor only supports binding to Iterables such as Arrays.")}}var e;if(this._differ){var n=this._differ.diff(this._ngForOf);n&&this._applyChanges(n)}},t.prototype._applyChanges=function(t){var e=this,n=[];t.forEachOperation(function(t,r,o){if(null==t.previousIndex){var i=e._viewContainer.createEmbeddedView(e._template,new Ac(null,e._ngForOf,-1,-1),o),a=new Pc(t,i);n.push(a)}else null==o?e._viewContainer.remove(r):(i=e._viewContainer.get(r),e._viewContainer.move(i,o),a=new Pc(t,i),n.push(a))});for(var r=0;r<n.length;r++)this._perViewChange(n[r].view,n[r].record);r=0;for(var o=this._viewContainer.length;r<o;r++){var i=this._viewContainer.get(r);i.context.index=r,i.context.count=o,i.context.ngForOf=this._ngForOf}t.forEachIdentityChange(function(t){e._viewContainer.get(t.currentIndex).context.$implicit=t.item})},t.prototype._perViewChange=function(t,e){t.context.$implicit=e.item},t.ngTemplateContextGuard=function(t,e){return!0},t}(),Pc=function(){return function(t,e){this.record=t,this.view=e}}(),Ic=function(){function t(t,e){this._viewContainer=t,this._context=new Nc,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=e}return Object.defineProperty(t.prototype,"ngIf",{set:function(t){this._context.$implicit=this._context.ngIf=t,this._updateView()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngIfThen",{set:function(t){Rc("ngIfThen",t),this._thenTemplateRef=t,this._thenViewRef=null,this._updateView()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngIfElse",{set:function(t){Rc("ngIfElse",t),this._elseTemplateRef=t,this._elseViewRef=null,this._updateView()},enumerable:!0,configurable:!0}),t.prototype._updateView=function(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))},t.ngTemplateGuard_ngIf=function(t,e){return!0},t}(),Nc=function(){return function(){this.$implicit=null,this.ngIf=null}}();function Rc(t,e){if(e&&!e.createEmbeddedView)throw new Error(t+" must be a TemplateRef, but received '"+Ut(e)+"'.")}var Dc=function(){function t(t){this.locale=t}var e;return e=t,t.prototype.transform=function(t,n,r,o){if(void 0===n&&(n="mediumDate"),null==t||""===t||t!=t)return null;try{return function(t,e,n,r){var o=function(t){if(Ec(t))return t;if("number"==typeof t&&!isNaN(t))return new Date(t);if("string"==typeof t){t=t.trim();var e,n=parseFloat(t);if(!isNaN(t-n))return new Date(n);if(/^(\d{4}-\d{1,2}-\d{1,2})$/.test(t)){var r=l(t.split("-").map(function(t){return+t}),3);return new Date(r[0],r[1]-1,r[2])}if(e=t.match(sc))return function(t){var e=new Date(0),n=0,r=0,o=t[8]?e.setUTCFullYear:e.setFullYear,i=t[8]?e.setUTCHours:e.setHours;t[9]&&(n=Number(t[9]+t[10]),r=Number(t[9]+t[11])),o.call(e,Number(t[1]),Number(t[2])-1,Number(t[3]));var a=Number(t[4]||0)-n,u=Number(t[5]||0)-r,s=Number(t[6]||0),l=Math.round(1e3*parseFloat("0."+(t[7]||0)));return i.call(e,a,u,s,l),e}(e)}var o=new Date(t);if(!Ec(o))throw new Error('Unable to convert "'+t+'" into a date');return o}(t);e=function t(e,n){var r=function(t){return uc(t)[0]}(e);if(lc[r]=lc[r]||{},lc[r][n])return lc[r][n];var o="";switch(n){case"shortDate":o=tc(e,Jl.Short);break;case"mediumDate":o=tc(e,Jl.Medium);break;case"longDate":o=tc(e,Jl.Long);break;case"fullDate":o=tc(e,Jl.Full);break;case"shortTime":o=ec(e,Jl.Short);break;case"mediumTime":o=ec(e,Jl.Medium);break;case"longTime":o=ec(e,Jl.Long);break;case"fullTime":o=ec(e,Jl.Full);break;case"short":var i=t(e,"shortTime"),a=t(e,"shortDate");o=dc(nc(e,Jl.Short),[i,a]);break;case"medium":var u=t(e,"mediumTime"),s=t(e,"mediumDate");o=dc(nc(e,Jl.Medium),[u,s]);break;case"long":var l=t(e,"longTime"),c=t(e,"longDate");o=dc(nc(e,Jl.Long),[l,c]);break;case"full":var f=t(e,"fullTime"),p=t(e,"fullDate");o=dc(nc(e,Jl.Full),[f,p])}return o&&(lc[r][n]=o),o}(n,e)||e;for(var i,a=[];e;){if(!(i=cc.exec(e))){a.push(e);break}var u=(a=a.concat(i.slice(1))).pop();if(!u)break;e=u}var s=o.getTimezoneOffset();r&&(s=Sc(r,s),o=function(t,e,n){var r=t.getTimezoneOffset();return function(t,e){return(t=new Date(t.getTime())).setMinutes(t.getMinutes()+e),t}(t,-1*(Sc(e,r)-r))}(o,r));var c="";return a.forEach(function(t){var e=function(t){if(Cc[t])return Cc[t];var e;switch(t){case"G":case"GG":case"GGG":e=yc(hc.Eras,$l.Abbreviated);break;case"GGGG":e=yc(hc.Eras,$l.Wide);break;case"GGGGG":e=yc(hc.Eras,$l.Narrow);break;case"y":e=gc(pc.FullYear,1,0,!1,!0);break;case"yy":e=gc(pc.FullYear,2,0,!0,!0);break;case"yyy":e=gc(pc.FullYear,3,0,!1,!0);break;case"yyyy":e=gc(pc.FullYear,4,0,!1,!0);break;case"M":case"L":e=gc(pc.Month,1,1);break;case"MM":case"LL":e=gc(pc.Month,2,1);break;case"MMM":e=yc(hc.Months,$l.Abbreviated);break;case"MMMM":e=yc(hc.Months,$l.Wide);break;case"MMMMM":e=yc(hc.Months,$l.Narrow);break;case"LLL":e=yc(hc.Months,$l.Abbreviated,Kl.Standalone);break;case"LLLL":e=yc(hc.Months,$l.Wide,Kl.Standalone);break;case"LLLLL":e=yc(hc.Months,$l.Narrow,Kl.Standalone);break;case"w":e=wc(1);break;case"ww":e=wc(2);break;case"W":e=wc(1,!0);break;case"d":e=gc(pc.Date,1);break;case"dd":e=gc(pc.Date,2);break;case"E":case"EE":case"EEE":e=yc(hc.Days,$l.Abbreviated);break;case"EEEE":e=yc(hc.Days,$l.Wide);break;case"EEEEE":e=yc(hc.Days,$l.Narrow);break;case"EEEEEE":e=yc(hc.Days,$l.Short);break;case"a":case"aa":case"aaa":e=yc(hc.DayPeriods,$l.Abbreviated);break;case"aaaa":e=yc(hc.DayPeriods,$l.Wide);break;case"aaaaa":e=yc(hc.DayPeriods,$l.Narrow);break;case"b":case"bb":case"bbb":e=yc(hc.DayPeriods,$l.Abbreviated,Kl.Standalone,!0);break;case"bbbb":e=yc(hc.DayPeriods,$l.Wide,Kl.Standalone,!0);break;case"bbbbb":e=yc(hc.DayPeriods,$l.Narrow,Kl.Standalone,!0);break;case"B":case"BB":case"BBB":e=yc(hc.DayPeriods,$l.Abbreviated,Kl.Format,!0);break;case"BBBB":e=yc(hc.DayPeriods,$l.Wide,Kl.Format,!0);break;case"BBBBB":e=yc(hc.DayPeriods,$l.Narrow,Kl.Format,!0);break;case"h":e=gc(pc.Hours,1,-12);break;case"hh":e=gc(pc.Hours,2,-12);break;case"H":e=gc(pc.Hours,1);break;case"HH":e=gc(pc.Hours,2);break;case"m":e=gc(pc.Minutes,1);break;case"mm":e=gc(pc.Minutes,2);break;case"s":e=gc(pc.Seconds,1);break;case"ss":e=gc(pc.Seconds,2);break;case"S":e=gc(pc.FractionalSeconds,1);break;case"SS":e=gc(pc.FractionalSeconds,2);break;case"SSS":e=gc(pc.FractionalSeconds,3);break;case"Z":case"ZZ":case"ZZZ":e=mc(fc.Short);break;case"ZZZZZ":e=mc(fc.Extended);break;case"O":case"OO":case"OOO":case"z":case"zz":case"zzz":e=mc(fc.ShortGMT);break;case"OOOO":case"ZZZZ":case"zzzz":e=mc(fc.Long);break;default:return null}return Cc[t]=e,e}(t);c+=e?e(o,n,s):"''"===t?"'":t.replace(/(^'|'$)/g,"").replace(/''/g,"'")}),c}(t,n,o||this.locale,r)}catch(i){throw Error("InvalidPipeArgument: '"+i.message+"' for pipe '"+Ut(e)+"'")}},t}(),Vc=function(){return function(){}}(),Mc=new Tt("DocumentToken"),jc="server",Uc=function(){function t(){}return t.ngInjectableDef=St({providedIn:"root",factory:function(){return new Lc(Le(Mc),window)}}),t}(),Lc=function(){function t(t,e){this.document=t,this.window=e,this.offset=function(){return[0,0]}}return t.prototype.setOffset=function(t){this.offset=Array.isArray(t)?function(){return t}:t},t.prototype.getScrollPosition=function(){return this.supportScrollRestoration()?[this.window.scrollX,this.window.scrollY]:[0,0]},t.prototype.scrollToPosition=function(t){this.supportScrollRestoration()&&this.window.scrollTo(t[0],t[1])},t.prototype.scrollToAnchor=function(t){if(this.supportScrollRestoration()){var e=this.document.querySelector("#"+t);if(e)return void this.scrollToElement(e);var n=this.document.querySelector("[name='"+t+"']");if(n)return void this.scrollToElement(n)}},t.prototype.setHistoryScrollRestoration=function(t){if(this.supportScrollRestoration()){var e=this.window.history;e&&e.scrollRestoration&&(e.scrollRestoration=t)}},t.prototype.scrollToElement=function(t){var e=t.getBoundingClientRect(),n=e.left+this.window.pageXOffset,r=e.top+this.window.pageYOffset,o=this.offset();this.window.scrollTo(n-o[0],r-o[1])},t.prototype.supportScrollRestoration=function(){try{return!!this.window&&!!this.window.scrollTo}catch(t){return!1}},t}(),Hc=new R(function(t){return t.complete()});function Fc(t){return t?function(t){return new R(function(e){return t.schedule(function(){return e.complete()})})}(t):Hc}function zc(t){var e=new R(function(e){e.next(t),e.complete()});return e._isScalar=!0,e.value=t,e}function qc(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[t.length-1];switch(F(n)?t.pop():n=void 0,t.length){case 0:return Fc(n);case 1:return n?rt(t,n):zc(t[0]);default:return rt(t,n)}}var Bc=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return o(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new M;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(L);function Gc(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}Gc.prototype=Object.create(Error.prototype);var Zc=Gc,Qc={},Wc=function(){function t(t){this.resultSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new Yc(t,this.resultSelector))},t}(),Yc=function(t){function e(e,n){var r=t.call(this,e)||this;return r.resultSelector=n,r.active=0,r.values=[],r.observables=[],r}return o(e,t),e.prototype._next=function(t){this.values.push(Qc),this.observables.push(t)},e.prototype._complete=function(){var t=this.observables,e=t.length;if(0===e)this.destination.complete();else{this.active=e,this.toRespond=e;for(var n=0;n<e;n++){var r=t[n];this.add(J(this,r,r,n))}}},e.prototype.notifyComplete=function(t){0==(this.active-=1)&&this.destination.complete()},e.prototype.notifyNext=function(t,e,n,r,o){var i=this.values,a=this.toRespond?i[n]===Qc?--this.toRespond:this.toRespond:0;i[n]=e,0===a&&(this.resultSelector?this._tryResultSelector(i):this.destination.next(i.slice()))},e.prototype._tryResultSelector=function(t){var e;try{e=this.resultSelector.apply(this,t)}catch(n){return void this.destination.error(n)}this.destination.next(e)},e}(X);function Kc(t){return new R(function(e){var n;try{n=t()}catch(r){return void e.error(r)}return(n?ot(n):Fc()).subscribe(e)})}function $c(){return lt(1)}function Jc(t,e){return function(n){return n.lift(new Xc(t,e))}}var Xc=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new tf(t,this.predicate,this.thisArg))},t}(),tf=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return o(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(n){return void this.destination.error(n)}e&&this.destination.next(t)},e}(k);function ef(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}ef.prototype=Object.create(Error.prototype);var nf=ef;function rf(t){return function(e){return 0===t?Fc():e.lift(new of(t))}}var of=function(){function t(t){if(this.total=t,this.total<0)throw new nf}return t.prototype.call=function(t,e){return e.subscribe(new af(t,this.total))},t}(),af=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return o(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length<n?e.push(t):e[r%n]=t},e.prototype._complete=function(){var t=this.destination,e=this.count;if(e>0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,o=0;o<n;o++){var i=e++%n;t.next(r[i])}t.complete()},e}(k);function uf(t,e,n){return function(r){return r.lift(new sf(t,e,n))}}var sf=function(){function t(t,e,n){this.nextOrObserver=t,this.error=e,this.complete=n}return t.prototype.call=function(t,e){return e.subscribe(new lf(t,this.nextOrObserver,this.error,this.complete))},t}(),lf=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i._tapNext=P,i._tapError=P,i._tapComplete=P,i._tapError=r||P,i._tapComplete=o||P,h(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||P,i._tapError=n.error||P,i._tapComplete=n.complete||P),i}return o(e,t),e.prototype._next=function(t){try{this._tapNext.call(this._context,t)}catch(e){return void this.destination.error(e)}this.destination.next(t)},e.prototype._error=function(t){try{this._tapError.call(this._context,t)}catch(t){return void this.destination.error(t)}this.destination.error(t)},e.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(t){return void this.destination.error(t)}return this.destination.complete()},e}(k),cf=function(t){return void 0===t&&(t=ff),uf({hasValue:!1,next:function(){this.hasValue=!0},complete:function(){if(!this.hasValue)throw t()}})};function ff(){return new Zc}function pf(t){return void 0===t&&(t=null),function(e){return e.lift(new hf(t))}}var hf=function(){function t(t){this.defaultValue=t}return t.prototype.call=function(t,e){return e.subscribe(new df(t,this.defaultValue))},t}(),df=function(t){function e(e,n){var r=t.call(this,e)||this;return r.defaultValue=n,r.isEmpty=!0,r}return o(e,t),e.prototype._next=function(t){this.isEmpty=!1,this.destination.next(t)},e.prototype._complete=function(){this.isEmpty&&this.destination.next(this.defaultValue),this.destination.complete()},e}(k);function vf(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?Jc(function(e,n){return t(e,n,r)}):st,rf(1),n?pf(e):cf(function(){return new Zc}))}}function gf(t){return function(e){var n=new yf(t),r=e.lift(n);return n.caught=r}}var yf=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new mf(t,this.selector,this.caught))},t}(),mf=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.selector=n,o.caught=r,o}return o(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(o){return void t.prototype.error.call(this,o)}this._unsubscribeAndRecycle();var r=new z(this,void 0,void 0);this.add(r),J(this,n,void 0,void 0,r)}},e}(X);function bf(t){return function(e){return 0===t?Fc():e.lift(new _f(t))}}var _f=function(){function t(t){if(this.total=t,this.total<0)throw new nf}return t.prototype.call=function(t,e){return e.subscribe(new wf(t,this.total))},t}(),wf=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return o(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(k);function Cf(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?Jc(function(e,n){return t(e,n,r)}):st,bf(1),n?pf(e):cf(function(){return new Zc}))}}var Sf=function(){function t(t,e,n){this.predicate=t,this.thisArg=e,this.source=n}return t.prototype.call=function(t,e){return e.subscribe(new Ef(t,this.predicate,this.thisArg,this.source))},t}(),Ef=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i.predicate=n,i.thisArg=r,i.source=o,i.index=0,i.thisArg=r||i,i}return o(e,t),e.prototype.notifyComplete=function(t){this.destination.next(t),this.destination.complete()},e.prototype._next=function(t){var e=!1;try{e=this.predicate.call(this.thisArg,t,this.index++,this.source)}catch(n){return void this.destination.error(n)}e||this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(k);function xf(t,e){return"function"==typeof e?function(n){return n.pipe(xf(function(n,r){return ot(t(n,r)).pipe(tt(function(t,o){return e(n,t,r,o)}))}))}:function(e){return e.lift(new Tf(t))}}var Tf=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new kf(t,this.project))},t}(),kf=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return o(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(r){return void this.destination.error(r)}this._innerSub(e,t,n)},e.prototype._innerSub=function(t,e,n){var r=this.innerSubscription;r&&r.unsubscribe();var o=new z(this,void 0,void 0);this.destination.add(o),this.innerSubscription=J(this,t,e,n,o)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=null},e.prototype.notifyComplete=function(e){this.destination.remove(e),this.innerSubscription=null,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e,n,r,o){this.destination.next(e)},e}(X);function Af(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new Of(t,e,n))}}var Of=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new Pf(t,this.accumulator,this.seed,this.hasSeed))},t}(),Pf=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i.accumulator=n,i._seed=r,i.hasSeed=o,i.index=0,i}return o(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(r){this.destination.error(r)}this.seed=e,this.destination.next(e)},e}(k);function If(t,e){return it(t,e,1)}var Nf=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Rf(t,this.callback))},t}(),Rf=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new _(n)),r}return o(e,t),e}(k),Df=null;function Vf(){return Df}var Mf,jf={class:"className",innerHtml:"innerHTML",readonly:"readOnly",tabindex:"tabIndex"},Uf={"\b":"Backspace","\t":"Tab","\x7f":"Delete","\x1b":"Escape",Del:"Delete",Esc:"Escape",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Menu:"ContextMenu",Scroll:"ScrollLock",Win:"OS"},Lf={A:"1",B:"2",C:"3",D:"4",E:"5",F:"6",G:"7",H:"8",I:"9",J:"*",K:"+",M:"-",N:".",O:"/","`":"0","\x90":"NumLock"};Nt.Node&&(Mf=Nt.Node.prototype.contains||function(t){return!!(16&this.compareDocumentPosition(t))});var Hf,Ff=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.parse=function(t){throw new Error("parse not implemented")},e.makeCurrent=function(){var t;t=new e,Df||(Df=t)},e.prototype.hasProperty=function(t,e){return e in t},e.prototype.setProperty=function(t,e,n){t[e]=n},e.prototype.getProperty=function(t,e){return t[e]},e.prototype.invoke=function(t,e,n){var r;(r=t)[e].apply(r,c(n))},e.prototype.logError=function(t){window.console&&(console.error?console.error(t):console.log(t))},e.prototype.log=function(t){window.console&&window.console.log&&window.console.log(t)},e.prototype.logGroup=function(t){window.console&&window.console.group&&window.console.group(t)},e.prototype.logGroupEnd=function(){window.console&&window.console.groupEnd&&window.console.groupEnd()},Object.defineProperty(e.prototype,"attrToPropMap",{get:function(){return jf},enumerable:!0,configurable:!0}),e.prototype.contains=function(t,e){return Mf.call(t,e)},e.prototype.querySelector=function(t,e){return t.querySelector(e)},e.prototype.querySelectorAll=function(t,e){return t.querySelectorAll(e)},e.prototype.on=function(t,e,n){t.addEventListener(e,n,!1)},e.prototype.onAndCancel=function(t,e,n){return t.addEventListener(e,n,!1),function(){t.removeEventListener(e,n,!1)}},e.prototype.dispatchEvent=function(t,e){t.dispatchEvent(e)},e.prototype.createMouseEvent=function(t){var e=this.getDefaultDocument().createEvent("MouseEvent");return e.initEvent(t,!0,!0),e},e.prototype.createEvent=function(t){var e=this.getDefaultDocument().createEvent("Event");return e.initEvent(t,!0,!0),e},e.prototype.preventDefault=function(t){t.preventDefault(),t.returnValue=!1},e.prototype.isPrevented=function(t){return t.defaultPrevented||null!=t.returnValue&&!t.returnValue},e.prototype.getInnerHTML=function(t){return t.innerHTML},e.prototype.getTemplateContent=function(t){return"content"in t&&this.isTemplateElement(t)?t.content:null},e.prototype.getOuterHTML=function(t){return t.outerHTML},e.prototype.nodeName=function(t){return t.nodeName},e.prototype.nodeValue=function(t){return t.nodeValue},e.prototype.type=function(t){return t.type},e.prototype.content=function(t){return this.hasProperty(t,"content")?t.content:t},e.prototype.firstChild=function(t){return t.firstChild},e.prototype.nextSibling=function(t){return t.nextSibling},e.prototype.parentElement=function(t){return t.parentNode},e.prototype.childNodes=function(t){return t.childNodes},e.prototype.childNodesAsList=function(t){for(var e=t.childNodes,n=new Array(e.length),r=0;r<e.length;r++)n[r]=e[r];return n},e.prototype.clearNodes=function(t){for(;t.firstChild;)t.removeChild(t.firstChild)},e.prototype.appendChild=function(t,e){t.appendChild(e)},e.prototype.removeChild=function(t,e){t.removeChild(e)},e.prototype.replaceChild=function(t,e,n){t.replaceChild(e,n)},e.prototype.remove=function(t){return t.parentNode&&t.parentNode.removeChild(t),t},e.prototype.insertBefore=function(t,e,n){t.insertBefore(n,e)},e.prototype.insertAllBefore=function(t,e,n){n.forEach(function(n){return t.insertBefore(n,e)})},e.prototype.insertAfter=function(t,e,n){t.insertBefore(n,e.nextSibling)},e.prototype.setInnerHTML=function(t,e){t.innerHTML=e},e.prototype.getText=function(t){return t.textContent},e.prototype.setText=function(t,e){t.textContent=e},e.prototype.getValue=function(t){return t.value},e.prototype.setValue=function(t,e){t.value=e},e.prototype.getChecked=function(t){return t.checked},e.prototype.setChecked=function(t,e){t.checked=e},e.prototype.createComment=function(t){return this.getDefaultDocument().createComment(t)},e.prototype.createTemplate=function(t){var e=this.getDefaultDocument().createElement("template");return e.innerHTML=t,e},e.prototype.createElement=function(t,e){return(e=e||this.getDefaultDocument()).createElement(t)},e.prototype.createElementNS=function(t,e,n){return(n=n||this.getDefaultDocument()).createElementNS(t,e)},e.prototype.createTextNode=function(t,e){return(e=e||this.getDefaultDocument()).createTextNode(t)},e.prototype.createScriptTag=function(t,e,n){var r=(n=n||this.getDefaultDocument()).createElement("SCRIPT");return r.setAttribute(t,e),r},e.prototype.createStyleElement=function(t,e){var n=(e=e||this.getDefaultDocument()).createElement("style");return this.appendChild(n,this.createTextNode(t,e)),n},e.prototype.createShadowRoot=function(t){return t.createShadowRoot()},e.prototype.getShadowRoot=function(t){return t.shadowRoot},e.prototype.getHost=function(t){return t.host},e.prototype.clone=function(t){return t.cloneNode(!0)},e.prototype.getElementsByClassName=function(t,e){return t.getElementsByClassName(e)},e.prototype.getElementsByTagName=function(t,e){return t.getElementsByTagName(e)},e.prototype.classList=function(t){return Array.prototype.slice.call(t.classList,0)},e.prototype.addClass=function(t,e){t.classList.add(e)},e.prototype.removeClass=function(t,e){t.classList.remove(e)},e.prototype.hasClass=function(t,e){return t.classList.contains(e)},e.prototype.setStyle=function(t,e,n){t.style[e]=n},e.prototype.removeStyle=function(t,e){t.style[e]=""},e.prototype.getStyle=function(t,e){return t.style[e]},e.prototype.hasStyle=function(t,e,n){var r=this.getStyle(t,e)||"";return n?r==n:r.length>0},e.prototype.tagName=function(t){return t.tagName},e.prototype.attributeMap=function(t){for(var e=new Map,n=t.attributes,r=0;r<n.length;r++){var o=n.item(r);e.set(o.name,o.value)}return e},e.prototype.hasAttribute=function(t,e){return t.hasAttribute(e)},e.prototype.hasAttributeNS=function(t,e,n){return t.hasAttributeNS(e,n)},e.prototype.getAttribute=function(t,e){return t.getAttribute(e)},e.prototype.getAttributeNS=function(t,e,n){return t.getAttributeNS(e,n)},e.prototype.setAttribute=function(t,e,n){t.setAttribute(e,n)},e.prototype.setAttributeNS=function(t,e,n,r){t.setAttributeNS(e,n,r)},e.prototype.removeAttribute=function(t,e){t.removeAttribute(e)},e.prototype.removeAttributeNS=function(t,e,n){t.removeAttributeNS(e,n)},e.prototype.templateAwareRoot=function(t){return this.isTemplateElement(t)?this.content(t):t},e.prototype.createHtmlDocument=function(){return document.implementation.createHTMLDocument("fakeTitle")},e.prototype.getDefaultDocument=function(){return document},e.prototype.getBoundingClientRect=function(t){try{return t.getBoundingClientRect()}catch(e){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}},e.prototype.getTitle=function(t){return t.title},e.prototype.setTitle=function(t,e){t.title=e||""},e.prototype.elementMatches=function(t,e){return!!this.isElementNode(t)&&(t.matches&&t.matches(e)||t.msMatchesSelector&&t.msMatchesSelector(e)||t.webkitMatchesSelector&&t.webkitMatchesSelector(e))},e.prototype.isTemplateElement=function(t){return this.isElementNode(t)&&"TEMPLATE"===t.nodeName},e.prototype.isTextNode=function(t){return t.nodeType===Node.TEXT_NODE},e.prototype.isCommentNode=function(t){return t.nodeType===Node.COMMENT_NODE},e.prototype.isElementNode=function(t){return t.nodeType===Node.ELEMENT_NODE},e.prototype.hasShadowRoot=function(t){return null!=t.shadowRoot&&t instanceof HTMLElement},e.prototype.isShadowRoot=function(t){return t instanceof DocumentFragment},e.prototype.importIntoDoc=function(t){return document.importNode(this.templateAwareRoot(t),!0)},e.prototype.adoptNode=function(t){return document.adoptNode(t)},e.prototype.getHref=function(t){return t.getAttribute("href")},e.prototype.getEventKey=function(t){var e=t.key;if(null==e){if(null==(e=t.keyIdentifier))return"Unidentified";e.startsWith("U+")&&(e=String.fromCharCode(parseInt(e.substring(2),16)),3===t.location&&Lf.hasOwnProperty(e)&&(e=Lf[e]))}return Uf[e]||e},e.prototype.getGlobalEventTarget=function(t,e){return"window"===e?window:"document"===e?t:"body"===e?t.body:null},e.prototype.getHistory=function(){return window.history},e.prototype.getLocation=function(){return window.location},e.prototype.getBaseHref=function(t){var e,n=zf||(zf=document.querySelector("base"))?zf.getAttribute("href"):null;return null==n?null:(e=n,Hf||(Hf=document.createElement("a")),Hf.setAttribute("href",e),"/"===Hf.pathname.charAt(0)?Hf.pathname:"/"+Hf.pathname)},e.prototype.resetBaseElement=function(){zf=null},e.prototype.getUserAgent=function(){return window.navigator.userAgent},e.prototype.setData=function(t,e,n){this.setAttribute(t,"data-"+e,n)},e.prototype.getData=function(t,e){return this.getAttribute(t,"data-"+e)},e.prototype.getComputedStyle=function(t){return getComputedStyle(t)},e.prototype.supportsWebAnimation=function(){return"function"==typeof Element.prototype.animate},e.prototype.performanceNow=function(){return window.performance&&window.performance.now?window.performance.now():(new Date).getTime()},e.prototype.supportsCookies=function(){return!0},e.prototype.getCookie=function(t){return function(t,e){var n,r;e=encodeURIComponent(e);try{for(var o=s(t.split(";")),i=o.next();!i.done;i=o.next()){var a=i.value,u=a.indexOf("="),c=l(-1==u?[a,""]:[a.slice(0,u),a.slice(u+1)],2),f=c[1];if(c[0].trim()===e)return decodeURIComponent(f)}}catch(p){n={error:p}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}(document.cookie,t)},e.prototype.setCookie=function(t,e){document.cookie=encodeURIComponent(t)+"="+encodeURIComponent(e)},e}(function(t){function e(){var e=t.call(this)||this;e._animationPrefix=null,e._transitionEnd=null;try{var n=e.createElement("div",document);if(null!=e.getStyle(n,"animationName"))e._animationPrefix="";else for(var r=["Webkit","Moz","O","ms"],o=0;o<r.length;o++)if(null!=e.getStyle(n,r[o]+"AnimationName")){e._animationPrefix="-"+r[o].toLowerCase()+"-";break}var i={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};Object.keys(i).forEach(function(t){null!=e.getStyle(n,t)&&(e._transitionEnd=i[t])})}catch(a){e._animationPrefix=null,e._transitionEnd=null}return e}return o(e,t),e.prototype.getDistributedNodes=function(t){return t.getDistributedNodes()},e.prototype.resolveAndSetHref=function(t,e,n){t.href=null==n?e:e+"/../"+n},e.prototype.supportsDOMEvents=function(){return!0},e.prototype.supportsNativeShadowDOM=function(){return"function"==typeof document.body.createShadowRoot},e.prototype.getAnimationPrefix=function(){return this._animationPrefix?this._animationPrefix:""},e.prototype.getTransitionEnd=function(){return this._transitionEnd?this._transitionEnd:""},e.prototype.supportsAnimation=function(){return null!=this._animationPrefix&&null!=this._transitionEnd},e}(function(){function t(){this.resourceLoaderType=null}return Object.defineProperty(t.prototype,"attrToPropMap",{get:function(){return this._attrToPropMap},set:function(t){this._attrToPropMap=t},enumerable:!0,configurable:!0}),t}())),zf=null,qf=Mc;function Bf(){return!!window.history.pushState}var Gf=function(t){function e(e){var n=t.call(this)||this;return n._doc=e,n._init(),n}var n;return o(e,t),e.prototype._init=function(){this.location=Vf().getLocation(),this._history=Vf().getHistory()},e.prototype.getBaseHrefFromDOM=function(){return Vf().getBaseHref(this._doc)},e.prototype.onPopState=function(t){Vf().getGlobalEventTarget(this._doc,"window").addEventListener("popstate",t,!1)},e.prototype.onHashChange=function(t){Vf().getGlobalEventTarget(this._doc,"window").addEventListener("hashchange",t,!1)},Object.defineProperty(e.prototype,"pathname",{get:function(){return this.location.pathname},set:function(t){this.location.pathname=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"search",{get:function(){return this.location.search},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hash",{get:function(){return this.location.hash},enumerable:!0,configurable:!0}),e.prototype.pushState=function(t,e,n){Bf()?this._history.pushState(t,e,n):this.location.hash=n},e.prototype.replaceState=function(t,e,n){Bf()?this._history.replaceState(t,e,n):this.location.hash=n},e.prototype.forward=function(){this._history.forward()},e.prototype.back=function(){this._history.back()},a([(n=Ie(qf),function(t,e){n(t,e,0)}),u("design:paramtypes",[Object])],e)}(Ul),Zf=new Tt("TRANSITION_ID"),Qf=[{provide:ti,useFactory:function(t,e,n){return function(){n.get(ei).donePromise.then(function(){var n=Vf();Array.prototype.slice.apply(n.querySelectorAll(e,"style[ng-transition]")).filter(function(e){return n.getAttribute(e,"ng-transition")===t}).forEach(function(t){return n.remove(t)})})}},deps:[Zf,qf,pr],multi:!0}],Wf=function(){function t(){}return t.init=function(){var e;e=new t,Ri=e},t.prototype.addToWindow=function(t){Nt.getAngularTestability=function(e,n){void 0===n&&(n=!0);var r=t.findTestabilityInTree(e,n);if(null==r)throw new Error("Could not find testability for element.");return r},Nt.getAllAngularTestabilities=function(){return t.getAllTestabilities()},Nt.getAllAngularRootElements=function(){return t.getAllRootElements()},Nt.frameworkStabilizers||(Nt.frameworkStabilizers=[]),Nt.frameworkStabilizers.push(function(t){var e=Nt.getAllAngularTestabilities(),n=e.length,r=!1,o=function(e){r=r||e,0==--n&&t(r)};e.forEach(function(t){t.whenStable(o)})})},t.prototype.findTestabilityInTree=function(t,e,n){if(null==e)return null;var r=t.getTestability(e);return null!=r?r:n?Vf().isShadowRoot(e)?this.findTestabilityInTree(t,Vf().getHost(e),!0):this.findTestabilityInTree(t,Vf().parentElement(e),!0):null},t}();function Yf(t,e){"undefined"!=typeof COMPILED&&COMPILED||((Nt.ng=Nt.ng||{})[t]=e)}var Kf={ApplicationRef:Hi,NgZone:Si};function $f(t){return na(t)}var Jf=new Tt("EventManagerPlugins"),Xf=function(){function t(t,e){var n=this;this._zone=e,this._eventNameToPlugin=new Map,t.forEach(function(t){return t.manager=n}),this._plugins=t.slice().reverse()}return t.prototype.addEventListener=function(t,e,n){return this._findPluginFor(e).addEventListener(t,e,n)},t.prototype.addGlobalEventListener=function(t,e,n){return this._findPluginFor(e).addGlobalEventListener(t,e,n)},t.prototype.getZone=function(){return this._zone},t.prototype._findPluginFor=function(t){var e=this._eventNameToPlugin.get(t);if(e)return e;for(var n=this._plugins,r=0;r<n.length;r++){var o=n[r];if(o.supports(t))return this._eventNameToPlugin.set(t,o),o}throw new Error("No event manager plugin found for event "+t)},t}(),tp=function(){function t(t){this._doc=t}return t.prototype.addGlobalEventListener=function(t,e,n){var r=Vf().getGlobalEventTarget(this._doc,t);if(!r)throw new Error("Unsupported event target "+r+" for event "+e);return this.addEventListener(r,e,n)},t}(),ep=function(){function t(){this._stylesSet=new Set}return t.prototype.addStyles=function(t){var e=this,n=new Set;t.forEach(function(t){e._stylesSet.has(t)||(e._stylesSet.add(t),n.add(t))}),this.onStylesAdded(n)},t.prototype.onStylesAdded=function(t){},t.prototype.getAllStyles=function(){return Array.from(this._stylesSet)},t}(),np=function(t){function e(e){var n=t.call(this)||this;return n._doc=e,n._hostNodes=new Set,n._styleNodes=new Set,n._hostNodes.add(e.head),n}return o(e,t),e.prototype._addStylesToHost=function(t,e){var n=this;t.forEach(function(t){var r=n._doc.createElement("style");r.textContent=t,n._styleNodes.add(e.appendChild(r))})},e.prototype.addHost=function(t){this._addStylesToHost(this._stylesSet,t),this._hostNodes.add(t)},e.prototype.removeHost=function(t){this._hostNodes.delete(t)},e.prototype.onStylesAdded=function(t){var e=this;this._hostNodes.forEach(function(n){return e._addStylesToHost(t,n)})},e.prototype.ngOnDestroy=function(){this._styleNodes.forEach(function(t){return Vf().remove(t)})},e}(ep),rp={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},op=/%COMP%/g,ip="_nghost-%COMP%",ap="_ngcontent-%COMP%";function up(t,e,n){for(var r=0;r<e.length;r++){var o=e[r];Array.isArray(o)?up(t,o,n):(o=o.replace(op,t),n.push(o))}return n}function sp(t){return function(e){!1===t(e)&&(e.preventDefault(),e.returnValue=!1)}}var lp=function(){function t(t,e){this.eventManager=t,this.sharedStylesHost=e,this.rendererByCompId=new Map,this.defaultRenderer=new cp(t)}return t.prototype.createRenderer=function(t,e){if(!t||!e)return this.defaultRenderer;switch(e.encapsulation){case zt.Emulated:var n=this.rendererByCompId.get(e.id);return n||(n=new dp(this.eventManager,this.sharedStylesHost,e),this.rendererByCompId.set(e.id,n)),n.applyToHost(t),n;case zt.Native:case zt.ShadowDom:return new vp(this.eventManager,this.sharedStylesHost,t,e);default:if(!this.rendererByCompId.has(e.id)){var r=up(e.id,e.styles,[]);this.sharedStylesHost.addStyles(r),this.rendererByCompId.set(e.id,this.defaultRenderer)}return this.defaultRenderer}},t.prototype.begin=function(){},t.prototype.end=function(){},t}(),cp=function(){function t(t){this.eventManager=t,this.data=Object.create(null)}return t.prototype.destroy=function(){},t.prototype.createElement=function(t,e){return e?document.createElementNS(rp[e],t):document.createElement(t)},t.prototype.createComment=function(t){return document.createComment(t)},t.prototype.createText=function(t){return document.createTextNode(t)},t.prototype.appendChild=function(t,e){t.appendChild(e)},t.prototype.insertBefore=function(t,e,n){t&&t.insertBefore(e,n)},t.prototype.removeChild=function(t,e){t&&t.removeChild(e)},t.prototype.selectRootElement=function(t,e){var n="string"==typeof t?document.querySelector(t):t;if(!n)throw new Error('The selector "'+t+'" did not match any elements');return e||(n.textContent=""),n},t.prototype.parentNode=function(t){return t.parentNode},t.prototype.nextSibling=function(t){return t.nextSibling},t.prototype.setAttribute=function(t,e,n,r){if(r){e=r+":"+e;var o=rp[r];o?t.setAttributeNS(o,e,n):t.setAttribute(e,n)}else t.setAttribute(e,n)},t.prototype.removeAttribute=function(t,e,n){if(n){var r=rp[n];r?t.removeAttributeNS(r,e):t.removeAttribute(n+":"+e)}else t.removeAttribute(e)},t.prototype.addClass=function(t,e){t.classList.add(e)},t.prototype.removeClass=function(t,e){t.classList.remove(e)},t.prototype.setStyle=function(t,e,n,r){r&to.DashCase?t.style.setProperty(e,n,r&to.Important?"important":""):t.style[e]=n},t.prototype.removeStyle=function(t,e,n){n&to.DashCase?t.style.removeProperty(e):t.style[e]=""},t.prototype.setProperty=function(t,e,n){pp(e,"property"),t[e]=n},t.prototype.setValue=function(t,e){t.nodeValue=e},t.prototype.listen=function(t,e,n){return pp(e,"listener"),"string"==typeof t?this.eventManager.addGlobalEventListener(t,e,sp(n)):this.eventManager.addEventListener(t,e,sp(n))},t}(),fp="@".charCodeAt(0);function pp(t,e){if(t.charCodeAt(0)===fp)throw new Error("Found the synthetic "+e+" "+t+'. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.')}var hp,dp=function(t){function e(e,n,r){var o=t.call(this,e)||this;o.component=r;var i=up(r.id,r.styles,[]);return n.addStyles(i),o.contentAttr=ap.replace(op,r.id),o.hostAttr=ip.replace(op,r.id),o}return o(e,t),e.prototype.applyToHost=function(e){t.prototype.setAttribute.call(this,e,this.hostAttr,"")},e.prototype.createElement=function(e,n){var r=t.prototype.createElement.call(this,e,n);return t.prototype.setAttribute.call(this,r,this.contentAttr,""),r},e}(cp),vp=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;i.sharedStylesHost=n,i.hostEl=r,i.component=o,i.shadowRoot=o.encapsulation===zt.ShadowDom?r.attachShadow({mode:"open"}):r.createShadowRoot(),i.sharedStylesHost.addHost(i.shadowRoot);for(var a=up(o.id,o.styles,[]),u=0;u<a.length;u++){var s=document.createElement("style");s.textContent=a[u],i.shadowRoot.appendChild(s)}return i}return o(e,t),e.prototype.nodeOrShadowRoot=function(t){return t===this.hostEl?this.shadowRoot:t},e.prototype.destroy=function(){this.sharedStylesHost.removeHost(this.shadowRoot)},e.prototype.appendChild=function(e,n){return t.prototype.appendChild.call(this,this.nodeOrShadowRoot(e),n)},e.prototype.insertBefore=function(e,n,r){return t.prototype.insertBefore.call(this,this.nodeOrShadowRoot(e),n,r)},e.prototype.removeChild=function(e,n){return t.prototype.removeChild.call(this,this.nodeOrShadowRoot(e),n)},e.prototype.parentNode=function(e){return this.nodeOrShadowRoot(t.prototype.parentNode.call(this,this.nodeOrShadowRoot(e)))},e}(cp),gp="undefined"!=typeof Zone&&Zone.__symbol__||function(t){return"__zone_symbol__"+t},yp=gp("addEventListener"),mp=gp("removeEventListener"),bp={},_p="__zone_symbol__propagationStopped";"undefined"!=typeof Zone&&Zone[gp("BLACK_LISTED_EVENTS")]&&(hp={});var wp=function(t){return!!hp&&hp.hasOwnProperty(t)},Cp=function(t){var e=bp[t.type];if(e){var n=this[e];if(n){var r=[t];if(1===n.length)return(a=n[0]).zone!==Zone.current?a.zone.run(a.handler,this,r):a.handler.apply(this,r);for(var o=n.slice(),i=0;i<o.length&&!0!==t[_p];i++){var a;(a=o[i]).zone!==Zone.current?a.zone.run(a.handler,this,r):a.handler.apply(this,r)}}}},Sp=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o.ngZone=n,r&&function(t){return t===jc}(r)||o.patchEvent(),o}return o(e,t),e.prototype.patchEvent=function(){if("undefined"!=typeof Event&&Event&&Event.prototype&&!Event.prototype.__zone_symbol__stopImmediatePropagation){var t=Event.prototype.__zone_symbol__stopImmediatePropagation=Event.prototype.stopImmediatePropagation;Event.prototype.stopImmediatePropagation=function(){this&&(this[_p]=!0),t&&t.apply(this,arguments)}}},e.prototype.supports=function(t){return!0},e.prototype.addEventListener=function(t,e,n){var r=this,o=n;if(!t[yp]||Si.isInAngularZone()&&!wp(e))t.addEventListener(e,o,!1);else{var i=bp[e];i||(i=bp[e]=gp("ANGULAR"+e+"FALSE"));var a=t[i],u=a&&a.length>0;a||(a=t[i]=[]);var s=wp(e)?Zone.root:Zone.current;if(0===a.length)a.push({zone:s,handler:o});else{for(var l=!1,c=0;c<a.length;c++)if(a[c].handler===o){l=!0;break}l||a.push({zone:s,handler:o})}u||t[yp](e,Cp,!1)}return function(){return r.removeEventListener(t,e,o)}},e.prototype.removeEventListener=function(t,e,n){var r=t[mp];if(!r)return t.removeEventListener.apply(t,[e,n,!1]);var o=bp[e],i=o&&t[o];if(!i)return t.removeEventListener.apply(t,[e,n,!1]);for(var a=!1,u=0;u<i.length;u++)if(i[u].handler===n){a=!0,i.splice(u,1);break}a?0===i.length&&r.apply(t,[e,Cp,!1]):t.removeEventListener.apply(t,[e,n,!1])},e}(tp),Ep={pan:!0,panstart:!0,panmove:!0,panend:!0,pancancel:!0,panleft:!0,panright:!0,panup:!0,pandown:!0,pinch:!0,pinchstart:!0,pinchmove:!0,pinchend:!0,pinchcancel:!0,pinchin:!0,pinchout:!0,press:!0,pressup:!0,rotate:!0,rotatestart:!0,rotatemove:!0,rotateend:!0,rotatecancel:!0,swipe:!0,swipeleft:!0,swiperight:!0,swipeup:!0,swipedown:!0,tap:!0},xp=new Tt("HammerGestureConfig"),Tp=new Tt("HammerLoader"),kp=function(){function t(){this.events=[],this.overrides={}}return t.prototype.buildHammer=function(t){var e=new Hammer(t,this.options);for(var n in e.get("pinch").set({enable:!0}),e.get("rotate").set({enable:!0}),this.overrides)e.get(n).set(this.overrides[n]);return e},t}(),Ap=function(t){function e(e,n,r,o){var i=t.call(this,e)||this;return i._config=n,i.console=r,i.loader=o,i}return o(e,t),e.prototype.supports=function(t){return!(!Ep.hasOwnProperty(t.toLowerCase())&&!this.isCustomEvent(t)||!window.Hammer&&!this.loader&&(this.console.warn('The "'+t+'" event cannot be bound because Hammer.JS is not loaded and no custom loader has been specified.'),1))},e.prototype.addEventListener=function(t,e,n){var r=this,o=this.manager.getZone();if(e=e.toLowerCase(),!window.Hammer&&this.loader){var i=!1,a=function(){i=!0};return this.loader().then(function(){if(!window.Hammer)return r.console.warn("The custom HAMMER_LOADER completed, but Hammer.JS is not present."),void(a=function(){});i||(a=r.addEventListener(t,e,n))}).catch(function(){r.console.warn('The "'+e+'" event cannot be bound because the custom Hammer.JS loader failed.'),a=function(){}}),function(){a()}}return o.runOutsideAngular(function(){var i=r._config.buildHammer(t),a=function(t){o.runGuarded(function(){n(t)})};return i.on(e,a),function(){i.off(e,a),"function"==typeof i.destroy&&i.destroy()}})},e.prototype.isCustomEvent=function(t){return this._config.events.indexOf(t)>-1},e}(tp),Op=["alt","control","meta","shift"],Pp={alt:function(t){return t.altKey},control:function(t){return t.ctrlKey},meta:function(t){return t.metaKey},shift:function(t){return t.shiftKey}},Ip=function(t){function e(e){return t.call(this,e)||this}var n;return o(e,t),n=e,e.prototype.supports=function(t){return null!=n.parseEventName(t)},e.prototype.addEventListener=function(t,e,r){var o=n.parseEventName(e),i=n.eventCallback(o.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(function(){return Vf().onAndCancel(t,o.domEventName,i)})},e.parseEventName=function(t){var e=t.toLowerCase().split("."),r=e.shift();if(0===e.length||"keydown"!==r&&"keyup"!==r)return null;var o=n._normalizeKey(e.pop()),i="";if(Op.forEach(function(t){var n=e.indexOf(t);n>-1&&(e.splice(n,1),i+=t+".")}),i+=o,0!=e.length||0===o.length)return null;var a={};return a.domEventName=r,a.fullKey=i,a},e.getEventFullKey=function(t){var e="",n=Vf().getEventKey(t);return" "===(n=n.toLowerCase())?n="space":"."===n&&(n="dot"),Op.forEach(function(r){r!=n&&(0,Pp[r])(t)&&(e+=r+".")}),e+=n},e.eventCallback=function(t,e,r){return function(o){n.getEventFullKey(o)===t&&r.runGuarded(function(){return e(o)})}},e._normalizeKey=function(t){switch(t){case"esc":return"escape";default:return t}},e}(tp),Np=function(){return function(){}}(),Rp=function(t){function e(e){var n=t.call(this)||this;return n._doc=e,n}return o(e,t),e.prototype.sanitize=function(t,e){if(null==e)return null;switch(t){case ro.NONE:return e;case ro.HTML:return e instanceof Vp?e.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(e,"HTML"),function(t,e){var n=null;try{So=So||new yo(t);var r=e?String(e):"";n=So.getInertBodyElement(r);var o=5,i=r;do{if(0===o)throw new Error("Failed to sanitize html because the input is unstable");o--,r=i,i=n.innerHTML,n=So.getInertBodyElement(r)}while(r!==i);var a=new No,u=a.sanitizeChildren(Mo(n)||n);return go()&&a.sanitizedSomething&&console.warn("WARNING: sanitizing HTML stripped some content, see http://g.co/ng/security#xss"),u}finally{if(n)for(var s=Mo(n)||n;s.firstChild;)s.removeChild(s.firstChild)}}(this._doc,String(e)));case ro.STYLE:return e instanceof Mp?e.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(e,"Style"),function(t){if(!(t=String(t).trim()))return"";var e=t.match(qo);return e&&_o(e[1])===e[1]||t.match(zo)&&function(t){for(var e=!0,n=!0,r=0;r<t.length;r++){var o=t.charAt(r);"'"===o&&n?e=!e:'"'===o&&e&&(n=!n)}return e&&n}(t)?t:(go()&&console.warn("WARNING: sanitizing unsafe style value "+t+" (see http://g.co/ng/security#xss)."),"unsafe")}(e));case ro.SCRIPT:if(e instanceof jp)return e.changingThisBreaksApplicationSecurity;throw this.checkNotSafeValue(e,"Script"),new Error("unsafe value used in a script context");case ro.URL:return e instanceof Lp||e instanceof Up?e.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(e,"URL"),_o(String(e)));case ro.RESOURCE_URL:if(e instanceof Lp)return e.changingThisBreaksApplicationSecurity;throw this.checkNotSafeValue(e,"ResourceURL"),new Error("unsafe value used in a resource URL context (see http://g.co/ng/security#xss)");default:throw new Error("Unexpected SecurityContext "+t+" (see http://g.co/ng/security#xss)")}},e.prototype.checkNotSafeValue=function(t,e){if(t instanceof Dp)throw new Error("Required a safe "+e+", got a "+t.getTypeName()+" (see http://g.co/ng/security#xss)")},e.prototype.bypassSecurityTrustHtml=function(t){return new Vp(t)},e.prototype.bypassSecurityTrustStyle=function(t){return new Mp(t)},e.prototype.bypassSecurityTrustScript=function(t){return new jp(t)},e.prototype.bypassSecurityTrustUrl=function(t){return new Up(t)},e.prototype.bypassSecurityTrustResourceUrl=function(t){return new Lp(t)},e}(Np),Dp=function(){function t(t){this.changingThisBreaksApplicationSecurity=t}return t.prototype.toString=function(){return"SafeValue must use [property]=binding: "+this.changingThisBreaksApplicationSecurity+" (see http://g.co/ng/security#xss)"},t}(),Vp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getTypeName=function(){return"HTML"},e}(Dp),Mp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getTypeName=function(){return"Style"},e}(Dp),jp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getTypeName=function(){return"Script"},e}(Dp),Up=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getTypeName=function(){return"URL"},e}(Dp),Lp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.getTypeName=function(){return"ResourceURL"},e}(Dp),Hp=Mi(ba,"browser",[{provide:ai,useValue:"browser"},{provide:ii,useValue:function(){Ff.makeCurrent(),Wf.init()},multi:!0},{provide:Ul,useClass:Gf,deps:[qf]},{provide:qf,useFactory:function(){return document},deps:[]}]);function Fp(){return new $o}var zp=function(){function t(t){if(t)throw new Error("BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.")}var e;return e=t,t.withServerTransition=function(t){return{ngModule:e,providers:[{provide:ni,useValue:t.appId},{provide:Zf,useExisting:ni},Qf]}},t}();"undefined"!=typeof window&&window;var qp=function(){return function(t,e){this.id=t,this.url=e}}(),Bp=function(t){function e(e,n,r,o){void 0===r&&(r="imperative"),void 0===o&&(o=null);var i=t.call(this,e,n)||this;return i.navigationTrigger=r,i.restoredState=o,i}return o(e,t),e.prototype.toString=function(){return"NavigationStart(id: "+this.id+", url: '"+this.url+"')"},e}(qp),Gp=function(t){function e(e,n,r){var o=t.call(this,e,n)||this;return o.urlAfterRedirects=r,o}return o(e,t),e.prototype.toString=function(){return"NavigationEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"')"},e}(qp),Zp=function(t){function e(e,n,r){var o=t.call(this,e,n)||this;return o.reason=r,o}return o(e,t),e.prototype.toString=function(){return"NavigationCancel(id: "+this.id+", url: '"+this.url+"')"},e}(qp),Qp=function(t){function e(e,n,r){var o=t.call(this,e,n)||this;return o.error=r,o}return o(e,t),e.prototype.toString=function(){return"NavigationError(id: "+this.id+", url: '"+this.url+"', error: "+this.error+")"},e}(qp),Wp=function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i.urlAfterRedirects=r,i.state=o,i}return o(e,t),e.prototype.toString=function(){return"RoutesRecognized(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},e}(qp),Yp=function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i.urlAfterRedirects=r,i.state=o,i}return o(e,t),e.prototype.toString=function(){return"GuardsCheckStart(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},e}(qp),Kp=function(t){function e(e,n,r,o,i){var a=t.call(this,e,n)||this;return a.urlAfterRedirects=r,a.state=o,a.shouldActivate=i,a}return o(e,t),e.prototype.toString=function(){return"GuardsCheckEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+", shouldActivate: "+this.shouldActivate+")"},e}(qp),$p=function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i.urlAfterRedirects=r,i.state=o,i}return o(e,t),e.prototype.toString=function(){return"ResolveStart(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},e}(qp),Jp=function(t){function e(e,n,r,o){var i=t.call(this,e,n)||this;return i.urlAfterRedirects=r,i.state=o,i}return o(e,t),e.prototype.toString=function(){return"ResolveEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},e}(qp),Xp=function(){function t(t){this.route=t}return t.prototype.toString=function(){return"RouteConfigLoadStart(path: "+this.route.path+")"},t}(),th=function(){function t(t){this.route=t}return t.prototype.toString=function(){return"RouteConfigLoadEnd(path: "+this.route.path+")"},t}(),eh=function(){function t(t){this.snapshot=t}return t.prototype.toString=function(){return"ChildActivationStart(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},t}(),nh=function(){function t(t){this.snapshot=t}return t.prototype.toString=function(){return"ChildActivationEnd(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},t}(),rh=function(){function t(t){this.snapshot=t}return t.prototype.toString=function(){return"ActivationStart(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},t}(),oh=function(){function t(t){this.snapshot=t}return t.prototype.toString=function(){return"ActivationEnd(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},t}(),ih=function(){function t(t,e,n){this.routerEvent=t,this.position=e,this.anchor=n}return t.prototype.toString=function(){return"Scroll(anchor: '"+this.anchor+"', position: '"+(this.position?this.position[0]+", "+this.position[1]:null)+"')"},t}(),ah=function(){return function(){}}(),uh="primary",sh=function(){function t(t){this.params=t||{}}return t.prototype.has=function(t){return this.params.hasOwnProperty(t)},t.prototype.get=function(t){if(this.has(t)){var e=this.params[t];return Array.isArray(e)?e[0]:e}return null},t.prototype.getAll=function(t){if(this.has(t)){var e=this.params[t];return Array.isArray(e)?e:[e]}return[]},Object.defineProperty(t.prototype,"keys",{get:function(){return Object.keys(this.params)},enumerable:!0,configurable:!0}),t}();function lh(t){return new sh(t)}var ch="ngNavigationCancelingError";function fh(t){var e=Error("NavigationCancelingError: "+t);return e[ch]=!0,e}function ph(t,e,n){var r=n.path.split("/");if(r.length>t.length)return null;if("full"===n.pathMatch&&(e.hasChildren()||r.length<t.length))return null;for(var o={},i=0;i<r.length;i++){var a=r[i],u=t[i];if(a.startsWith(":"))o[a.substring(1)]=u;else if(a!==u.path)return null}return{consumed:t.slice(0,r.length),posParams:o}}var hh=function(){return function(t,e){this.routes=t,this.module=e}}();function dh(t,e){void 0===e&&(e="");for(var n=0;n<t.length;n++){var r=t[n];vh(r,gh(e,r))}}function vh(t,e){if(!t)throw new Error("\n Invalid configuration of route '"+e+"': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");if(Array.isArray(t))throw new Error("Invalid configuration of route '"+e+"': Array cannot be specified");if(!t.component&&!t.children&&!t.loadChildren&&t.outlet&&t.outlet!==uh)throw new Error("Invalid configuration of route '"+e+"': a componentless route without children or loadChildren cannot have a named outlet set");if(t.redirectTo&&t.children)throw new Error("Invalid configuration of route '"+e+"': redirectTo and children cannot be used together");if(t.redirectTo&&t.loadChildren)throw new Error("Invalid configuration of route '"+e+"': redirectTo and loadChildren cannot be used together");if(t.children&&t.loadChildren)throw new Error("Invalid configuration of route '"+e+"': children and loadChildren cannot be used together");if(t.redirectTo&&t.component)throw new Error("Invalid configuration of route '"+e+"': redirectTo and component cannot be used together");if(t.path&&t.matcher)throw new Error("Invalid configuration of route '"+e+"': path and matcher cannot be used together");if(void 0===t.redirectTo&&!t.component&&!t.children&&!t.loadChildren)throw new Error("Invalid configuration of route '"+e+"'. One of the following must be provided: component, redirectTo, children or loadChildren");if(void 0===t.path&&void 0===t.matcher)throw new Error("Invalid configuration of route '"+e+"': routes must have either a path or a matcher specified");if("string"==typeof t.path&&"/"===t.path.charAt(0))throw new Error("Invalid configuration of route '"+e+"': path cannot start with a slash");if(""===t.path&&void 0!==t.redirectTo&&void 0===t.pathMatch)throw new Error("Invalid configuration of route '{path: \""+e+'", redirectTo: "'+t.redirectTo+"\"}': please provide 'pathMatch'. The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.");if(void 0!==t.pathMatch&&"full"!==t.pathMatch&&"prefix"!==t.pathMatch)throw new Error("Invalid configuration of route '"+e+"': pathMatch can only be set to 'prefix' or 'full'");t.children&&dh(t.children,e)}function gh(t,e){return e?t||e.path?t&&!e.path?t+"/":!t&&e.path?e.path:t+"/"+e.path:"":t}function yh(t){var e=t.children&&t.children.map(yh),n=e?i({},t,{children:e}):i({},t);return!n.component&&(e||n.loadChildren)&&n.outlet&&n.outlet!==uh&&(n.component=ah),n}function mh(t,e){var n,r=Object.keys(t),o=Object.keys(e);if(r.length!=o.length)return!1;for(var i=0;i<r.length;i++)if(t[n=r[i]]!==e[n])return!1;return!0}function bh(t){return Array.prototype.concat.apply([],t)}function _h(t){return t.length>0?t[t.length-1]:null}function wh(t,e){for(var n in t)t.hasOwnProperty(n)&&e(t[n],n)}function Ch(t){return Xo(t)?t:Jo(t)?ot(Promise.resolve(t)):qc(t)}function Sh(t,e,n){return n?function(t,e){return mh(t,e)}(t.queryParams,e.queryParams)&&function t(e,n){if(!kh(e.segments,n.segments))return!1;if(e.numberOfChildren!==n.numberOfChildren)return!1;for(var r in n.children){if(!e.children[r])return!1;if(!t(e.children[r],n.children[r]))return!1}return!0}(t.root,e.root):function(t,e){return Object.keys(e).length<=Object.keys(t).length&&Object.keys(e).every(function(n){return e[n]===t[n]})}(t.queryParams,e.queryParams)&&function t(e,n){return function e(n,r,o){if(n.segments.length>o.length)return!!kh(a=n.segments.slice(0,o.length),o)&&!r.hasChildren();if(n.segments.length===o.length){if(!kh(n.segments,o))return!1;for(var i in r.children){if(!n.children[i])return!1;if(!t(n.children[i],r.children[i]))return!1}return!0}var a=o.slice(0,n.segments.length),u=o.slice(n.segments.length);return!!kh(n.segments,a)&&!!n.children[uh]&&e(n.children[uh],r,u)}(e,n,n.segments)}(t.root,e.root)}var Eh=function(){function t(t,e,n){this.root=t,this.queryParams=e,this.fragment=n}return Object.defineProperty(t.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=lh(this.queryParams)),this._queryParamMap},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return Ih.serialize(this)},t}(),xh=function(){function t(t,e){var n=this;this.segments=t,this.children=e,this.parent=null,wh(e,function(t,e){return t.parent=n})}return t.prototype.hasChildren=function(){return this.numberOfChildren>0},Object.defineProperty(t.prototype,"numberOfChildren",{get:function(){return Object.keys(this.children).length},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return Nh(this)},t}(),Th=function(){function t(t,e){this.path=t,this.parameters=e}return Object.defineProperty(t.prototype,"parameterMap",{get:function(){return this._parameterMap||(this._parameterMap=lh(this.parameters)),this._parameterMap},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return Uh(this)},t}();function kh(t,e){return t.length===e.length&&t.every(function(t,n){return t.path===e[n].path})}function Ah(t,e){var n=[];return wh(t.children,function(t,r){r===uh&&(n=n.concat(e(t,r)))}),wh(t.children,function(t,r){r!==uh&&(n=n.concat(e(t,r)))}),n}var Oh=function(){return function(){}}(),Ph=function(){function t(){}return t.prototype.parse=function(t){var e=new qh(t);return new Eh(e.parseRootSegment(),e.parseQueryParams(),e.parseFragment())},t.prototype.serialize=function(t){var e,n;return"/"+function t(e,n){if(!e.hasChildren())return Nh(e);if(n){var r=e.children[uh]?t(e.children[uh],!1):"",o=[];return wh(e.children,function(e,n){n!==uh&&o.push(n+":"+t(e,!1))}),o.length>0?r+"("+o.join("//")+")":r}var i=Ah(e,function(n,r){return r===uh?[t(e.children[uh],!1)]:[r+":"+t(n,!1)]});return Nh(e)+"/("+i.join("//")+")"}(t.root,!0)+(e=t.queryParams,(n=Object.keys(e).map(function(t){var n=e[t];return Array.isArray(n)?n.map(function(e){return Dh(t)+"="+Dh(e)}).join("&"):Dh(t)+"="+Dh(n)})).length?"?"+n.join("&"):"")+("string"==typeof t.fragment?"#"+encodeURI(t.fragment):"")},t}(),Ih=new Ph;function Nh(t){return t.segments.map(function(t){return Uh(t)}).join("/")}function Rh(t){return encodeURIComponent(t).replace(/%40/g,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",")}function Dh(t){return Rh(t).replace(/%3B/gi,";")}function Vh(t){return Rh(t).replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/%26/gi,"&")}function Mh(t){return decodeURIComponent(t)}function jh(t){return Mh(t.replace(/\+/g,"%20"))}function Uh(t){return""+Vh(t.path)+(e=t.parameters,Object.keys(e).map(function(t){return";"+Vh(t)+"="+Vh(e[t])}).join(""));var e}var Lh=/^[^\/()?;=#]+/;function Hh(t){var e=t.match(Lh);return e?e[0]:""}var Fh=/^[^=?&#]+/,zh=/^[^?&#]+/,qh=function(){function t(t){this.url=t,this.remaining=t}return t.prototype.parseRootSegment=function(){return this.consumeOptional("/"),""===this.remaining||this.peekStartsWith("?")||this.peekStartsWith("#")?new xh([],{}):new xh([],this.parseChildren())},t.prototype.parseQueryParams=function(){var t={};if(this.consumeOptional("?"))do{this.parseQueryParam(t)}while(this.consumeOptional("&"));return t},t.prototype.parseFragment=function(){return this.consumeOptional("#")?decodeURIComponent(this.remaining):null},t.prototype.parseChildren=function(){if(""===this.remaining)return{};this.consumeOptional("/");var t=[];for(this.peekStartsWith("(")||t.push(this.parseSegment());this.peekStartsWith("/")&&!this.peekStartsWith("//")&&!this.peekStartsWith("/(");)this.capture("/"),t.push(this.parseSegment());var e={};this.peekStartsWith("/(")&&(this.capture("/"),e=this.parseParens(!0));var n={};return this.peekStartsWith("(")&&(n=this.parseParens(!1)),(t.length>0||Object.keys(e).length>0)&&(n[uh]=new xh(t,e)),n},t.prototype.parseSegment=function(){var t=Hh(this.remaining);if(""===t&&this.peekStartsWith(";"))throw new Error("Empty path url segment cannot have parameters: '"+this.remaining+"'.");return this.capture(t),new Th(Mh(t),this.parseMatrixParams())},t.prototype.parseMatrixParams=function(){for(var t={};this.consumeOptional(";");)this.parseParam(t);return t},t.prototype.parseParam=function(t){var e=Hh(this.remaining);if(e){this.capture(e);var n="";if(this.consumeOptional("=")){var r=Hh(this.remaining);r&&this.capture(n=r)}t[Mh(e)]=Mh(n)}},t.prototype.parseQueryParam=function(t){var e,n=(e=this.remaining.match(Fh))?e[0]:"";if(n){this.capture(n);var r="";if(this.consumeOptional("=")){var o=function(t){var e=t.match(zh);return e?e[0]:""}(this.remaining);o&&this.capture(r=o)}var i=jh(n),a=jh(r);if(t.hasOwnProperty(i)){var u=t[i];Array.isArray(u)||(t[i]=u=[u]),u.push(a)}else t[i]=a}},t.prototype.parseParens=function(t){var e={};for(this.capture("(");!this.consumeOptional(")")&&this.remaining.length>0;){var n=Hh(this.remaining),r=this.remaining[n.length];if("/"!==r&&")"!==r&&";"!==r)throw new Error("Cannot parse url '"+this.url+"'");var o=void 0;n.indexOf(":")>-1?(o=n.substr(0,n.indexOf(":")),this.capture(o),this.capture(":")):t&&(o=uh);var i=this.parseChildren();e[o]=1===Object.keys(i).length?i[uh]:new xh([],i),this.consumeOptional("//")}return e},t.prototype.peekStartsWith=function(t){return this.remaining.startsWith(t)},t.prototype.consumeOptional=function(t){return!!this.peekStartsWith(t)&&(this.remaining=this.remaining.substring(t.length),!0)},t.prototype.capture=function(t){if(!this.consumeOptional(t))throw new Error('Expected "'+t+'".')},t}(),Bh=function(){function t(t){this._root=t}return Object.defineProperty(t.prototype,"root",{get:function(){return this._root.value},enumerable:!0,configurable:!0}),t.prototype.parent=function(t){var e=this.pathFromRoot(t);return e.length>1?e[e.length-2]:null},t.prototype.children=function(t){var e=Gh(t,this._root);return e?e.children.map(function(t){return t.value}):[]},t.prototype.firstChild=function(t){var e=Gh(t,this._root);return e&&e.children.length>0?e.children[0].value:null},t.prototype.siblings=function(t){var e=Zh(t,this._root);return e.length<2?[]:e[e.length-2].children.map(function(t){return t.value}).filter(function(e){return e!==t})},t.prototype.pathFromRoot=function(t){return Zh(t,this._root).map(function(t){return t.value})},t}();function Gh(t,e){var n,r;if(t===e.value)return e;try{for(var o=s(e.children),i=o.next();!i.done;i=o.next()){var a=Gh(t,i.value);if(a)return a}}catch(u){n={error:u}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}function Zh(t,e){var n,r;if(t===e.value)return[e];try{for(var o=s(e.children),i=o.next();!i.done;i=o.next()){var a=Zh(t,i.value);if(a.length)return a.unshift(e),a}}catch(u){n={error:u}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return[]}var Qh=function(){function t(t,e){this.value=t,this.children=e}return t.prototype.toString=function(){return"TreeNode("+this.value+")"},t}();function Wh(t){var e={};return t&&t.children.forEach(function(t){return e[t.value.outlet]=t}),e}var Yh=function(t){function e(e,n){var r=t.call(this,e)||this;return r.snapshot=n,ed(r,e),r}return o(e,t),e.prototype.toString=function(){return this.snapshot.toString()},e}(Bh);function Kh(t,e){var n=function(t,e){var n=new Xh([],{},{},"",{},uh,e,null,t.root,-1,{});return new td("",new Qh(n,[]))}(t,e),r=new Bc([new Th("",{})]),o=new Bc({}),i=new Bc({}),a=new Bc({}),u=new Bc(""),s=new $h(r,o,a,u,i,uh,e,n.root);return s.snapshot=n.root,new Yh(new Qh(s,[]),n)}var $h=function(){function t(t,e,n,r,o,i,a,u){this.url=t,this.params=e,this.queryParams=n,this.fragment=r,this.data=o,this.outlet=i,this.component=a,this._futureSnapshot=u}return Object.defineProperty(t.prototype,"routeConfig",{get:function(){return this._futureSnapshot.routeConfig},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"root",{get:function(){return this._routerState.root},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this._routerState.parent(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"firstChild",{get:function(){return this._routerState.firstChild(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"children",{get:function(){return this._routerState.children(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pathFromRoot",{get:function(){return this._routerState.pathFromRoot(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paramMap",{get:function(){return this._paramMap||(this._paramMap=this.params.pipe(tt(function(t){return lh(t)}))),this._paramMap},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(tt(function(t){return lh(t)}))),this._queryParamMap},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return this.snapshot?this.snapshot.toString():"Future("+this._futureSnapshot+")"},t}();function Jh(t,e){void 0===e&&(e="emptyOnly");var n=t.pathFromRoot,r=0;if("always"!==e)for(r=n.length-1;r>=1;){var o=n[r],a=n[r-1];if(o.routeConfig&&""===o.routeConfig.path)r--;else{if(a.component)break;r--}}return function(t){return t.reduce(function(t,e){return{params:i({},t.params,e.params),data:i({},t.data,e.data),resolve:i({},t.resolve,e._resolvedData)}},{params:{},data:{},resolve:{}})}(n.slice(r))}var Xh=function(){function t(t,e,n,r,o,i,a,u,s,l,c){this.url=t,this.params=e,this.queryParams=n,this.fragment=r,this.data=o,this.outlet=i,this.component=a,this.routeConfig=u,this._urlSegment=s,this._lastPathIndex=l,this._resolve=c}return Object.defineProperty(t.prototype,"root",{get:function(){return this._routerState.root},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parent",{get:function(){return this._routerState.parent(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"firstChild",{get:function(){return this._routerState.firstChild(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"children",{get:function(){return this._routerState.children(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pathFromRoot",{get:function(){return this._routerState.pathFromRoot(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"paramMap",{get:function(){return this._paramMap||(this._paramMap=lh(this.params)),this._paramMap},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=lh(this.queryParams)),this._queryParamMap},enumerable:!0,configurable:!0}),t.prototype.toString=function(){return"Route(url:'"+this.url.map(function(t){return t.toString()}).join("/")+"', path:'"+(this.routeConfig?this.routeConfig.path:"")+"')"},t}(),td=function(t){function e(e,n){var r=t.call(this,n)||this;return r.url=e,ed(r,n),r}return o(e,t),e.prototype.toString=function(){return nd(this._root)},e}(Bh);function ed(t,e){e.value._routerState=t,e.children.forEach(function(e){return ed(t,e)})}function nd(t){var e=t.children.length>0?" { "+t.children.map(nd).join(", ")+" } ":"";return""+t.value+e}function rd(t){if(t.snapshot){var e=t.snapshot,n=t._futureSnapshot;t.snapshot=n,mh(e.queryParams,n.queryParams)||t.queryParams.next(n.queryParams),e.fragment!==n.fragment&&t.fragment.next(n.fragment),mh(e.params,n.params)||t.params.next(n.params),function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;++n)if(!mh(t[n],e[n]))return!1;return!0}(e.url,n.url)||t.url.next(n.url),mh(e.data,n.data)||t.data.next(n.data)}else t.snapshot=t._futureSnapshot,t.data.next(t._futureSnapshot.data)}function od(t,e){var n,r;return mh(t.params,e.params)&&kh(n=t.url,r=e.url)&&n.every(function(t,e){return mh(t.parameters,r[e].parameters)})&&!(!t.parent!=!e.parent)&&(!t.parent||od(t.parent,e.parent))}function id(t){return"object"==typeof t&&null!=t&&!t.outlets&&!t.segmentPath}function ad(t,e,n,r,o){var i={};return r&&wh(r,function(t,e){i[e]=Array.isArray(t)?t.map(function(t){return""+t}):""+t}),new Eh(n.root===t?e:function t(e,n,r){var o={};return wh(e.children,function(e,i){o[i]=e===n?r:t(e,n,r)}),new xh(e.segments,o)}(n.root,t,e),i,o)}var ud=function(){function t(t,e,n){if(this.isAbsolute=t,this.numberOfDoubleDots=e,this.commands=n,t&&n.length>0&&id(n[0]))throw new Error("Root segment cannot have matrix parameters");var r=n.find(function(t){return"object"==typeof t&&null!=t&&t.outlets});if(r&&r!==_h(n))throw new Error("{outlets:{}} has to be the last command")}return t.prototype.toRoot=function(){return this.isAbsolute&&1===this.commands.length&&"/"==this.commands[0]},t}(),sd=function(){return function(t,e,n){this.segmentGroup=t,this.processChildren=e,this.index=n}}();function ld(t){return"object"==typeof t&&null!=t&&t.outlets?t.outlets[uh]:""+t}function cd(t,e,n){if(t||(t=new xh([],{})),0===t.segments.length&&t.hasChildren())return fd(t,e,n);var r=function(t,e,n){for(var r=0,o=e,i={match:!1,pathIndex:0,commandIndex:0};o<t.segments.length;){if(r>=n.length)return i;var a=t.segments[o],u=ld(n[r]),s=r<n.length-1?n[r+1]:null;if(o>0&&void 0===u)break;if(u&&s&&"object"==typeof s&&void 0===s.outlets){if(!vd(u,s,a))return i;r+=2}else{if(!vd(u,{},a))return i;r++}o++}return{match:!0,pathIndex:o,commandIndex:r}}(t,e,n),o=n.slice(r.commandIndex);if(r.match&&r.pathIndex<t.segments.length){var i=new xh(t.segments.slice(0,r.pathIndex),{});return i.children[uh]=new xh(t.segments.slice(r.pathIndex),t.children),fd(i,0,o)}return r.match&&0===o.length?new xh(t.segments,{}):r.match&&!t.hasChildren()?pd(t,e,n):r.match?fd(t,0,o):pd(t,e,n)}function fd(t,e,n){if(0===n.length)return new xh(t.segments,{});var r=function(t){var e,n;return"object"!=typeof t[0]?((e={})[uh]=t,e):void 0===t[0].outlets?((n={})[uh]=t,n):t[0].outlets}(n),o={};return wh(r,function(n,r){null!==n&&(o[r]=cd(t.children[r],e,n))}),wh(t.children,function(t,e){void 0===r[e]&&(o[e]=t)}),new xh(t.segments,o)}function pd(t,e,n){for(var r=t.segments.slice(0,e),o=0;o<n.length;){if("object"==typeof n[o]&&void 0!==n[o].outlets){var i=hd(n[o].outlets);return new xh(r,i)}if(0===o&&id(n[0]))r.push(new Th(t.segments[e].path,n[0])),o++;else{var a=ld(n[o]),u=o<n.length-1?n[o+1]:null;a&&u&&id(u)?(r.push(new Th(a,dd(u))),o+=2):(r.push(new Th(a,{})),o++)}}return new xh(r,{})}function hd(t){var e={};return wh(t,function(t,n){null!==t&&(e[n]=pd(new xh([],{}),0,t))}),e}function dd(t){var e={};return wh(t,function(t,n){return e[n]=""+t}),e}function vd(t,e,n){return t==n.path&&mh(e,n.parameters)}var gd=function(){function t(t,e,n,r){this.routeReuseStrategy=t,this.futureState=e,this.currState=n,this.forwardEvent=r}return t.prototype.activate=function(t){var e=this.futureState._root,n=this.currState?this.currState._root:null;this.deactivateChildRoutes(e,n,t),rd(this.futureState.root),this.activateChildRoutes(e,n,t)},t.prototype.deactivateChildRoutes=function(t,e,n){var r=this,o=Wh(e);t.children.forEach(function(t){var e=t.value.outlet;r.deactivateRoutes(t,o[e],n),delete o[e]}),wh(o,function(t,e){r.deactivateRouteAndItsChildren(t,n)})},t.prototype.deactivateRoutes=function(t,e,n){var r=t.value,o=e?e.value:null;if(r===o)if(r.component){var i=n.getContext(r.outlet);i&&this.deactivateChildRoutes(t,e,i.children)}else this.deactivateChildRoutes(t,e,n);else o&&this.deactivateRouteAndItsChildren(e,n)},t.prototype.deactivateRouteAndItsChildren=function(t,e){this.routeReuseStrategy.shouldDetach(t.value.snapshot)?this.detachAndStoreRouteSubtree(t,e):this.deactivateRouteAndOutlet(t,e)},t.prototype.detachAndStoreRouteSubtree=function(t,e){var n=e.getContext(t.value.outlet);if(n&&n.outlet){var r=n.outlet.detach(),o=n.children.onOutletDeactivated();this.routeReuseStrategy.store(t.value.snapshot,{componentRef:r,route:t,contexts:o})}},t.prototype.deactivateRouteAndOutlet=function(t,e){var n=this,r=e.getContext(t.value.outlet);if(r){var o=Wh(t),i=t.value.component?r.children:e;wh(o,function(t,e){return n.deactivateRouteAndItsChildren(t,i)}),r.outlet&&(r.outlet.deactivate(),r.children.onOutletDeactivated())}},t.prototype.activateChildRoutes=function(t,e,n){var r=this,o=Wh(e);t.children.forEach(function(t){r.activateRoutes(t,o[t.value.outlet],n),r.forwardEvent(new oh(t.value.snapshot))}),t.children.length&&this.forwardEvent(new nh(t.value.snapshot))},t.prototype.activateRoutes=function(t,e,n){var r=t.value,o=e?e.value:null;if(rd(r),r===o)if(r.component){var i=n.getOrCreateContext(r.outlet);this.activateChildRoutes(t,e,i.children)}else this.activateChildRoutes(t,e,n);else if(r.component)if(i=n.getOrCreateContext(r.outlet),this.routeReuseStrategy.shouldAttach(r.snapshot)){var a=this.routeReuseStrategy.retrieve(r.snapshot);this.routeReuseStrategy.store(r.snapshot,null),i.children.onOutletReAttached(a.contexts),i.attachRef=a.componentRef,i.route=a.route.value,i.outlet&&i.outlet.attach(a.componentRef,a.route.value),yd(a.route)}else{var u=function(t){for(var e=r.snapshot.parent;e;e=e.parent){var n=e.routeConfig;if(n&&n._loadedConfig)return n._loadedConfig;if(n&&n.component)return null}return null}(),s=u?u.module.componentFactoryResolver:null;i.attachRef=null,i.route=r,i.resolver=s,i.outlet&&i.outlet.activateWith(r,s),this.activateChildRoutes(t,null,i.children)}else this.activateChildRoutes(t,null,n)},t}();function yd(t){rd(t.value),t.children.forEach(yd)}function md(t){return"function"==typeof t}function bd(t){return t instanceof Eh}var _d=function(){return function(t){this.segmentGroup=t||null}}(),wd=function(){return function(t){this.urlTree=t}}();function Cd(t){return new R(function(e){return e.error(new _d(t))})}function Sd(t){return new R(function(e){return e.error(new wd(t))})}function Ed(t){return new R(function(e){return e.error(new Error("Only absolute redirects can have named outlets. redirectTo: '"+t+"'"))})}var xd=function(){function t(t,e,n,r,o){this.configLoader=e,this.urlSerializer=n,this.urlTree=r,this.config=o,this.allowRedirects=!0,this.ngModule=t.get(Qr)}return t.prototype.apply=function(){var t=this;return this.expandSegmentGroup(this.ngModule,this.config,this.urlTree.root,uh).pipe(tt(function(e){return t.createUrlTree(e,t.urlTree.queryParams,t.urlTree.fragment)})).pipe(gf(function(e){if(e instanceof wd)return t.allowRedirects=!1,t.match(e.urlTree);if(e instanceof _d)throw t.noMatchError(e);throw e}))},t.prototype.match=function(t){var e=this;return this.expandSegmentGroup(this.ngModule,this.config,t.root,uh).pipe(tt(function(n){return e.createUrlTree(n,t.queryParams,t.fragment)})).pipe(gf(function(t){if(t instanceof _d)throw e.noMatchError(t);throw t}))},t.prototype.noMatchError=function(t){return new Error("Cannot match any routes. URL Segment: '"+t.segmentGroup+"'")},t.prototype.createUrlTree=function(t,e,n){var r,o=t.segments.length>0?new xh([],((r={})[uh]=t,r)):t;return new Eh(o,e,n)},t.prototype.expandSegmentGroup=function(t,e,n,r){return 0===n.segments.length&&n.hasChildren()?this.expandChildren(t,e,n).pipe(tt(function(t){return new xh([],t)})):this.expandSegment(t,n,e,n.segments,r,!0)},t.prototype.expandChildren=function(t,e,n){var r=this;return function(n,o){if(0===Object.keys(n).length)return qc({});var i=[],a=[],u={};return wh(n,function(n,o){var s,l,c=(s=o,l=n,r.expandSegmentGroup(t,e,l,s)).pipe(tt(function(t){return u[o]=t}));o===uh?i.push(c):a.push(c)}),qc.apply(null,i.concat(a)).pipe($c(),vf(),tt(function(){return u}))}(n.children)},t.prototype.expandSegment=function(t,e,n,r,o,i){var a=this;return qc.apply(void 0,c(n)).pipe(tt(function(u){return a.expandSegmentAgainstRoute(t,e,n,u,r,o,i).pipe(gf(function(t){if(t instanceof _d)return qc(null);throw t}))}),$c(),Cf(function(t){return!!t}),gf(function(t,n){if(t instanceof Zc||"EmptyError"===t.name){if(a.noLeftoversInUrl(e,r,o))return qc(new xh([],{}));throw new _d(e)}throw t}))},t.prototype.noLeftoversInUrl=function(t,e,n){return 0===e.length&&!t.children[n]},t.prototype.expandSegmentAgainstRoute=function(t,e,n,r,o,i,a){return Od(r)!==i?Cd(e):void 0===r.redirectTo?this.matchSegmentAgainstRoute(t,e,r,o):a&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(t,e,n,r,o,i):Cd(e)},t.prototype.expandSegmentAgainstRouteUsingRedirect=function(t,e,n,r,o,i){return"**"===r.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(t,n,r,i):this.expandRegularSegmentAgainstRouteUsingRedirect(t,e,n,r,o,i)},t.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect=function(t,e,n,r){var o=this,i=this.applyRedirectCommands([],n.redirectTo,{});return n.redirectTo.startsWith("/")?Sd(i):this.lineralizeSegments(n,i).pipe(it(function(n){var i=new xh(n,{});return o.expandSegment(t,i,e,n,r,!1)}))},t.prototype.expandRegularSegmentAgainstRouteUsingRedirect=function(t,e,n,r,o,i){var a=this,u=Td(e,r,o),s=u.consumedSegments,l=u.lastChild,c=u.positionalParamSegments;if(!u.matched)return Cd(e);var f=this.applyRedirectCommands(s,r.redirectTo,c);return r.redirectTo.startsWith("/")?Sd(f):this.lineralizeSegments(r,f).pipe(it(function(r){return a.expandSegment(t,e,n,r.concat(o.slice(l)),i,!1)}))},t.prototype.matchSegmentAgainstRoute=function(t,e,n,r){var o=this;if("**"===n.path)return n.loadChildren?this.configLoader.load(t.injector,n).pipe(tt(function(t){return n._loadedConfig=t,new xh(r,{})})):qc(new xh(r,{}));var a=Td(e,n,r),u=a.consumedSegments,l=a.lastChild;if(!a.matched)return Cd(e);var c=r.slice(l);return this.getChildConfig(t,n,r).pipe(it(function(t){var n=t.module,r=t.routes,a=function(t,e,n,r){return n.length>0&&function(t,e,n){return r.some(function(n){return Ad(t,e,n)&&Od(n)!==uh})}(t,n)?{segmentGroup:kd(new xh(e,function(t,e){var n,r,o={};o[uh]=e;try{for(var i=s(t),a=i.next();!a.done;a=i.next()){var u=a.value;""===u.path&&Od(u)!==uh&&(o[Od(u)]=new xh([],{}))}}catch(l){n={error:l}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return o}(r,new xh(n,t.children)))),slicedSegments:[]}:0===n.length&&function(t,e,n){return r.some(function(n){return Ad(t,e,n)})}(t,n)?{segmentGroup:kd(new xh(t.segments,function(t,e,n,r){var o,a,u={};try{for(var l=s(n),c=l.next();!c.done;c=l.next()){var f=c.value;Ad(t,e,f)&&!r[Od(f)]&&(u[Od(f)]=new xh([],{}))}}catch(p){o={error:p}}finally{try{c&&!c.done&&(a=l.return)&&a.call(l)}finally{if(o)throw o.error}}return i({},r,u)}(t,n,r,t.children))),slicedSegments:n}:{segmentGroup:t,slicedSegments:n}}(e,u,c,r),l=a.segmentGroup,f=a.slicedSegments;return 0===f.length&&l.hasChildren()?o.expandChildren(n,r,l).pipe(tt(function(t){return new xh(u,t)})):0===r.length&&0===f.length?qc(new xh(u,{})):o.expandSegment(n,l,r,f,uh,!0).pipe(tt(function(t){return new xh(u.concat(t.segments),t.children)}))}))},t.prototype.getChildConfig=function(t,e,n){var r=this;return e.children?qc(new hh(e.children,t)):e.loadChildren?void 0!==e._loadedConfig?qc(e._loadedConfig):function(t,e,n){var r,o=e.canLoad;return o&&0!==o.length?ot(o).pipe(tt(function(r){var o,i=t.get(r);if(function(t){return t&&md(t.canLoad)}(i))o=i.canLoad(e,n);else{if(!md(i))throw new Error("Invalid CanLoad guard");o=i(e,n)}return Ch(o)})).pipe($c(),(r=function(t){return!0===t},function(t){return t.lift(new Sf(r,void 0,t))})):qc(!0)}(t.injector,e,n).pipe(it(function(n){return n?r.configLoader.load(t.injector,e).pipe(tt(function(t){return e._loadedConfig=t,t})):function(t){return new R(function(e){return e.error(fh("Cannot load children because the guard of the route \"path: '"+t.path+"'\" returned false"))})}(e)})):qc(new hh([],t))},t.prototype.lineralizeSegments=function(t,e){for(var n=[],r=e.root;;){if(n=n.concat(r.segments),0===r.numberOfChildren)return qc(n);if(r.numberOfChildren>1||!r.children[uh])return Ed(t.redirectTo);r=r.children[uh]}},t.prototype.applyRedirectCommands=function(t,e,n){return this.applyRedirectCreatreUrlTree(e,this.urlSerializer.parse(e),t,n)},t.prototype.applyRedirectCreatreUrlTree=function(t,e,n,r){var o=this.createSegmentGroup(t,e.root,n,r);return new Eh(o,this.createQueryParams(e.queryParams,this.urlTree.queryParams),e.fragment)},t.prototype.createQueryParams=function(t,e){var n={};return wh(t,function(t,r){if("string"==typeof t&&t.startsWith(":")){var o=t.substring(1);n[r]=e[o]}else n[r]=t}),n},t.prototype.createSegmentGroup=function(t,e,n,r){var o=this,i=this.createSegments(t,e.segments,n,r),a={};return wh(e.children,function(e,i){a[i]=o.createSegmentGroup(t,e,n,r)}),new xh(i,a)},t.prototype.createSegments=function(t,e,n,r){var o=this;return e.map(function(e){return e.path.startsWith(":")?o.findPosParam(t,e,r):o.findOrReturn(e,n)})},t.prototype.findPosParam=function(t,e,n){var r=n[e.path.substring(1)];if(!r)throw new Error("Cannot redirect to '"+t+"'. Cannot find '"+e.path+"'.");return r},t.prototype.findOrReturn=function(t,e){var n,r,o=0;try{for(var i=s(e),a=i.next();!a.done;a=i.next()){var u=a.value;if(u.path===t.path)return e.splice(o),u;o++}}catch(l){n={error:l}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return t},t}();function Td(t,e,n){if(""===e.path)return"full"===e.pathMatch&&(t.hasChildren()||n.length>0)?{matched:!1,consumedSegments:[],lastChild:0,positionalParamSegments:{}}:{matched:!0,consumedSegments:[],lastChild:0,positionalParamSegments:{}};var r=(e.matcher||ph)(n,t,e);return r?{matched:!0,consumedSegments:r.consumed,lastChild:r.consumed.length,positionalParamSegments:r.posParams}:{matched:!1,consumedSegments:[],lastChild:0,positionalParamSegments:{}}}function kd(t){if(1===t.numberOfChildren&&t.children[uh]){var e=t.children[uh];return new xh(t.segments.concat(e.segments),e.children)}return t}function Ad(t,e,n){return(!(t.hasChildren()||e.length>0)||"full"!==n.pathMatch)&&""===n.path&&void 0!==n.redirectTo}function Od(t){return t.outlet||uh}var Pd=function(){return function(t){this.path=t,this.route=this.path[this.path.length-1]}}(),Id=function(){return function(t,e){this.component=t,this.route=e}}();function Nd(t,e,n){var r=function(t){if(!t)return null;for(var e=t.parent;e;e=e.parent){var n=e.routeConfig;if(n&&n._loadedConfig)return n._loadedConfig}return null}(e);return(r?r.module.injector:n).get(t)}function Rd(t,e,n,r,o){void 0===o&&(o={canDeactivateChecks:[],canActivateChecks:[]});var i=Wh(e);return t.children.forEach(function(t){!function(t,e,n,r,o){void 0===o&&(o={canDeactivateChecks:[],canActivateChecks:[]});var i=t.value,a=e?e.value:null,u=n?n.getContext(t.value.outlet):null;if(a&&i.routeConfig===a.routeConfig){var s=function(t,e,n){if("function"==typeof n)return n(t,e);switch(n){case"pathParamsChange":return!kh(t.url,e.url);case"pathParamsOrQueryParamsChange":return!kh(t.url,e.url)||!mh(t.queryParams,e.queryParams);case"always":return!0;case"paramsOrQueryParamsChange":return!od(t,e)||!mh(t.queryParams,e.queryParams);case"paramsChange":default:return!od(t,e)}}(a,i,i.routeConfig.runGuardsAndResolvers);s?o.canActivateChecks.push(new Pd(r)):(i.data=a.data,i._resolvedData=a._resolvedData),Rd(t,e,i.component?u?u.children:null:n,r,o),s&&o.canDeactivateChecks.push(new Id(u&&u.outlet&&u.outlet.component||null,a))}else a&&Dd(e,u,o),o.canActivateChecks.push(new Pd(r)),Rd(t,null,i.component?u?u.children:null:n,r,o)}(t,i[t.value.outlet],n,r.concat([t.value]),o),delete i[t.value.outlet]}),wh(i,function(t,e){return Dd(t,n.getContext(e),o)}),o}function Dd(t,e,n){var r=Wh(t),o=t.value;wh(r,function(t,r){Dd(t,o.component?e?e.children.getContext(r):null:e,n)}),n.canDeactivateChecks.push(new Id(o.component&&e&&e.outlet&&e.outlet.isActivated?e.outlet.component:null,o))}var Vd=Symbol("INITIAL_VALUE");function Md(){return xf(function(t){return(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=null,r=null;return F(t[t.length-1])&&(r=t.pop()),"function"==typeof t[t.length-1]&&(n=t.pop()),1===t.length&&f(t[0])&&(t=t[0]),rt(t,r).lift(new Wc(n))}).apply(void 0,c(t.map(function(t){return t.pipe(bf(1),function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){var n=t[t.length-1];F(n)?t.pop():n=null;var r=t.length;return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length||2===t.length&&F(t[1])?ot(t[0]):$c()(qc.apply(void 0,t))}(1!==r||n?r>0?rt(t,n):Fc(n):zc(t[0]),e)}}(Vd))}))).pipe(Af(function(t,e){var n=!1;return e.reduce(function(t,r,o){if(t!==Vd)return t;if(r===Vd&&(n=!0),!n){if(!1===r)return r;if(o===e.length-1||bd(r))return r}return t},t)},Vd),Jc(function(t){return t!==Vd}),tt(function(t){return bd(t)?t:!0===t}),bf(1))})}function jd(t,e){return null!==t&&e&&e(new rh(t)),qc(!0)}function Ud(t,e){return null!==t&&e&&e(new eh(t)),qc(!0)}function Ld(t,e,n){var r=e.routeConfig?e.routeConfig.canActivate:null;return r&&0!==r.length?qc(r.map(function(r){return Kc(function(){var o,i=Nd(r,e,n);if(function(t){return t&&md(t.canActivate)}(i))o=Ch(i.canActivate(e,t));else{if(!md(i))throw new Error("Invalid CanActivate guard");o=Ch(i(e,t))}return o.pipe(Cf())})})).pipe(Md()):qc(!0)}function Hd(t,e,n){var r=e[e.length-1],o=e.slice(0,e.length-1).reverse().map(function(t){return function(t){var e=t.routeConfig?t.routeConfig.canActivateChild:null;return e&&0!==e.length?{node:t,guards:e}:null}(t)}).filter(function(t){return null!==t}).map(function(e){return Kc(function(){return qc(e.guards.map(function(o){var i,a=Nd(o,e.node,n);if(function(t){return t&&md(t.canActivateChild)}(a))i=Ch(a.canActivateChild(r,t));else{if(!md(a))throw new Error("Invalid CanActivateChild guard");i=Ch(a(r,t))}return i.pipe(Cf())})).pipe(Md())})});return qc(o).pipe(Md())}var Fd=function(){return function(){}}(),zd=function(){function t(t,e,n,r,o,i){this.rootComponentType=t,this.config=e,this.urlTree=n,this.url=r,this.paramsInheritanceStrategy=o,this.relativeLinkResolution=i}return t.prototype.recognize=function(){try{var t=Gd(this.urlTree.root,[],[],this.config,this.relativeLinkResolution).segmentGroup,e=this.processSegmentGroup(this.config,t,uh),n=new Xh([],Object.freeze({}),Object.freeze(i({},this.urlTree.queryParams)),this.urlTree.fragment,{},uh,this.rootComponentType,null,this.urlTree.root,-1,{}),r=new Qh(n,e),o=new td(this.url,r);return this.inheritParamsAndData(o._root),qc(o)}catch(a){return new R(function(t){return t.error(a)})}},t.prototype.inheritParamsAndData=function(t){var e=this,n=t.value,r=Jh(n,this.paramsInheritanceStrategy);n.params=Object.freeze(r.params),n.data=Object.freeze(r.data),t.children.forEach(function(t){return e.inheritParamsAndData(t)})},t.prototype.processSegmentGroup=function(t,e,n){return 0===e.segments.length&&e.hasChildren()?this.processChildren(t,e):this.processSegment(t,e,e.segments,n)},t.prototype.processChildren=function(t,e){var n,r=this,o=Ah(e,function(e,n){return r.processSegmentGroup(t,e,n)});return n={},o.forEach(function(t){var e=n[t.value.outlet];if(e){var r=e.url.map(function(t){return t.toString()}).join("/"),o=t.value.url.map(function(t){return t.toString()}).join("/");throw new Error("Two segments cannot have the same outlet name: '"+r+"' and '"+o+"'.")}n[t.value.outlet]=t.value}),o.sort(function(t,e){return t.value.outlet===uh?-1:e.value.outlet===uh?1:t.value.outlet.localeCompare(e.value.outlet)}),o},t.prototype.processSegment=function(t,e,n,r){var o,i;try{for(var a=s(t),u=a.next();!u.done;u=a.next()){var l=u.value;try{return this.processSegmentAgainstRoute(l,e,n,r)}catch(c){if(!(c instanceof Fd))throw c}}}catch(f){o={error:f}}finally{try{u&&!u.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}if(this.noLeftoversInUrl(e,n,r))return[];throw new Fd},t.prototype.noLeftoversInUrl=function(t,e,n){return 0===e.length&&!t.children[n]},t.prototype.processSegmentAgainstRoute=function(t,e,n,r){if(t.redirectTo)throw new Fd;if((t.outlet||uh)!==r)throw new Fd;var o,a=[],u=[];if("**"===t.path){var s=n.length>0?_h(n).parameters:{};o=new Xh(n,s,Object.freeze(i({},this.urlTree.queryParams)),this.urlTree.fragment,Wd(t),r,t.component,t,qd(e),Bd(e)+n.length,Yd(t))}else{var l=function(t,e,n){if(""===e.path){if("full"===e.pathMatch&&(t.hasChildren()||n.length>0))throw new Fd;return{consumedSegments:[],lastChild:0,parameters:{}}}var r=(e.matcher||ph)(n,t,e);if(!r)throw new Fd;var o={};wh(r.posParams,function(t,e){o[e]=t.path});var a=r.consumed.length>0?i({},o,r.consumed[r.consumed.length-1].parameters):o;return{consumedSegments:r.consumed,lastChild:r.consumed.length,parameters:a}}(e,t,n);a=l.consumedSegments,u=n.slice(l.lastChild),o=new Xh(a,l.parameters,Object.freeze(i({},this.urlTree.queryParams)),this.urlTree.fragment,Wd(t),r,t.component,t,qd(e),Bd(e)+a.length,Yd(t))}var c=function(t){return t.children?t.children:t.loadChildren?t._loadedConfig.routes:[]}(t),f=Gd(e,a,u,c,this.relativeLinkResolution),p=f.segmentGroup,h=f.slicedSegments;if(0===h.length&&p.hasChildren()){var d=this.processChildren(c,p);return[new Qh(o,d)]}if(0===c.length&&0===h.length)return[new Qh(o,[])];var v=this.processSegment(c,p,h,uh);return[new Qh(o,v)]},t}();function qd(t){for(var e=t;e._sourceSegment;)e=e._sourceSegment;return e}function Bd(t){for(var e=t,n=e._segmentIndexShift?e._segmentIndexShift:0;e._sourceSegment;)n+=(e=e._sourceSegment)._segmentIndexShift?e._segmentIndexShift:0;return n-1}function Gd(t,e,n,r,o){if(n.length>0&&function(t,e,n){return r.some(function(n){return Zd(t,e,n)&&Qd(n)!==uh})}(t,n)){var a=new xh(e,function(t,e,n,r){var o,i,a={};a[uh]=r,r._sourceSegment=t,r._segmentIndexShift=e.length;try{for(var u=s(n),l=u.next();!l.done;l=u.next()){var c=l.value;if(""===c.path&&Qd(c)!==uh){var f=new xh([],{});f._sourceSegment=t,f._segmentIndexShift=e.length,a[Qd(c)]=f}}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=u.return)&&i.call(u)}finally{if(o)throw o.error}}return a}(t,e,r,new xh(n,t.children)));return a._sourceSegment=t,a._segmentIndexShift=e.length,{segmentGroup:a,slicedSegments:[]}}if(0===n.length&&function(t,e,n){return r.some(function(n){return Zd(t,e,n)})}(t,n)){var u=new xh(t.segments,function(t,e,n,r,o,a){var u,l,c={};try{for(var f=s(r),p=f.next();!p.done;p=f.next()){var h=p.value;if(Zd(t,n,h)&&!o[Qd(h)]){var d=new xh([],{});d._sourceSegment=t,d._segmentIndexShift="legacy"===a?t.segments.length:e.length,c[Qd(h)]=d}}}catch(v){u={error:v}}finally{try{p&&!p.done&&(l=f.return)&&l.call(f)}finally{if(u)throw u.error}}return i({},o,c)}(t,e,n,r,t.children,o));return u._sourceSegment=t,u._segmentIndexShift=e.length,{segmentGroup:u,slicedSegments:n}}var l=new xh(t.segments,t.children);return l._sourceSegment=t,l._segmentIndexShift=e.length,{segmentGroup:l,slicedSegments:n}}function Zd(t,e,n){return(!(t.hasChildren()||e.length>0)||"full"!==n.pathMatch)&&""===n.path&&void 0===n.redirectTo}function Qd(t){return t.outlet||uh}function Wd(t){return t.data||{}}function Yd(t){return t.resolve||{}}function Kd(t,e,n,r){var o=Nd(t,e,r);return Ch(o.resolve?o.resolve(e,n):o(e,n))}function $d(t){return function(e){return e.pipe(xf(function(e){var n=t(e);return n?ot(n).pipe(tt(function(){return e})):ot([e])}))}}var Jd=function(){return function(){}}(),Xd=function(){function t(){}return t.prototype.shouldDetach=function(t){return!1},t.prototype.store=function(t,e){},t.prototype.shouldAttach=function(t){return!1},t.prototype.retrieve=function(t){return null},t.prototype.shouldReuseRoute=function(t,e){return t.routeConfig===e.routeConfig},t}(),tv=new Tt("ROUTES"),ev=function(){function t(t,e,n,r){this.loader=t,this.compiler=e,this.onLoadStartListener=n,this.onLoadEndListener=r}return t.prototype.load=function(t,e){var n=this;return this.onLoadStartListener&&this.onLoadStartListener(e),this.loadModuleFactory(e.loadChildren).pipe(tt(function(r){n.onLoadEndListener&&n.onLoadEndListener(e);var o=r.create(t);return new hh(bh(o.injector.get(tv)).map(yh),o)}))},t.prototype.loadModuleFactory=function(t){var e=this;return"string"==typeof t?ot(this.loader.load(t)):Ch(t()).pipe(it(function(t){return t instanceof Wr?qc(t):ot(e.compiler.compileModuleAsync(t))}))},t}(),nv=function(){return function(){}}(),rv=function(){function t(){}return t.prototype.shouldProcessUrl=function(t){return!0},t.prototype.extract=function(t){return t},t.prototype.merge=function(t,e){return t},t}();function ov(t){throw t}function iv(t,e,n){return e.parse("/")}function av(t,e){return qc(null)}var uv=function(){function t(t,e,n,r,o,i,a,u){var s=this;this.rootComponentType=t,this.urlSerializer=e,this.rootContexts=n,this.location=r,this.config=u,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.navigationId=0,this.isNgZoneEnabled=!1,this.events=new L,this.errorHandler=ov,this.malformedUriErrorHandler=iv,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:av,afterPreactivation:av},this.urlHandlingStrategy=new rv,this.routeReuseStrategy=new Xd,this.onSameUrlNavigation="ignore",this.paramsInheritanceStrategy="emptyOnly",this.urlUpdateStrategy="deferred",this.relativeLinkResolution="legacy",this.ngModule=o.get(Qr),this.console=o.get(si);var l=o.get(Si);this.isNgZoneEnabled=l instanceof Si,this.resetConfig(u),this.currentUrlTree=new Eh(new xh([],{}),{},null),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.parseUrl(this.location.path()),this.configLoader=new ev(i,a,function(t){return s.triggerEvent(new Xp(t))},function(t){return s.triggerEvent(new th(t))}),this.routerState=Kh(this.currentUrlTree,this.rootComponentType),this.transitions=new Bc({id:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:"imperative",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}return t.prototype.setupNavigations=function(t){var e=this,n=this.events;return t.pipe(Jc(function(t){return 0!==t.id}),tt(function(t){return i({},t,{extractedUrl:e.urlHandlingStrategy.extract(t.rawUrl)})}),uf(function(t){e.currentNavigation={id:t.id,initialUrl:t.currentRawUrl,extractedUrl:t.extractedUrl,trigger:t.source,extras:t.extras,previousNavigation:e.lastSuccessfulNavigation?i({},e.lastSuccessfulNavigation,{previousNavigation:null}):null}}),xf(function(t){var r,o,a,u,l=!1,c=!1;return qc(t).pipe(xf(function(t){var r,o,a,u,s=!e.navigated||t.extractedUrl.toString()!==e.browserUrlTree.toString();if(("reload"===e.onSameUrlNavigation||s)&&e.urlHandlingStrategy.shouldProcessUrl(t.rawUrl))return qc(t).pipe(xf(function(t){var r=e.transitions.getValue();return n.next(new Bp(t.id,e.serializeUrl(t.extractedUrl),t.source,t.restoredState)),r!==e.transitions.getValue()?Hc:[t]}),xf(function(t){return Promise.resolve(t)}),(r=e.ngModule.injector,o=e.configLoader,a=e.urlSerializer,u=e.config,function(t){return t.pipe(xf(function(t){return function(e,n,r,o,i){return new xd(e,n,r,t.extractedUrl,i).apply()}(r,o,a,0,u).pipe(tt(function(e){return i({},t,{urlAfterRedirects:e})}))}))}),uf(function(t){e.currentNavigation=i({},e.currentNavigation,{finalUrl:t.urlAfterRedirects})}),function(t,n,r,o,a){return function(r){return r.pipe(it(function(r){return function(t,e,n,r,o,i){return void 0===o&&(o="emptyOnly"),void 0===i&&(i="legacy"),new zd(t,e,n,r,o,i).recognize()}(t,n,r.urlAfterRedirects,(u=r.urlAfterRedirects,e.serializeUrl(u)),o,a).pipe(tt(function(t){return i({},r,{targetSnapshot:t})}));var u}))}}(e.rootComponentType,e.config,0,e.paramsInheritanceStrategy,e.relativeLinkResolution),uf(function(t){"eager"===e.urlUpdateStrategy&&(t.extras.skipLocationChange||e.setBrowserUrl(t.urlAfterRedirects,!!t.extras.replaceUrl,t.id),e.browserUrlTree=t.urlAfterRedirects)}),uf(function(t){var r=new Wp(t.id,e.serializeUrl(t.extractedUrl),e.serializeUrl(t.urlAfterRedirects),t.targetSnapshot);n.next(r)}));if(s&&e.rawUrlTree&&e.urlHandlingStrategy.shouldProcessUrl(e.rawUrlTree)){var l=t.extractedUrl,c=t.source,f=t.restoredState,p=t.extras,h=new Bp(t.id,e.serializeUrl(l),c,f);n.next(h);var d=Kh(l,e.rootComponentType).snapshot;return qc(i({},t,{targetSnapshot:d,urlAfterRedirects:l,extras:i({},p,{skipLocationChange:!1,replaceUrl:!1})}))}return e.rawUrlTree=t.rawUrl,t.resolve(null),Hc}),$d(function(t){var n=t.extras;return e.hooks.beforePreactivation(t.targetSnapshot,{navigationId:t.id,appliedUrlTree:t.extractedUrl,rawUrlTree:t.rawUrl,skipLocationChange:!!n.skipLocationChange,replaceUrl:!!n.replaceUrl})}),uf(function(t){var n=new Yp(t.id,e.serializeUrl(t.extractedUrl),e.serializeUrl(t.urlAfterRedirects),t.targetSnapshot);e.triggerEvent(n)}),tt(function(t){return i({},t,{guards:(n=t.targetSnapshot,r=t.currentSnapshot,o=e.rootContexts,a=n._root,Rd(a,r?r._root:null,o,[a.value]))});var n,r,o,a}),function(t,e){return function(n){return n.pipe(it(function(n){var r=n.targetSnapshot,o=n.currentSnapshot,a=n.guards,u=a.canActivateChecks,s=a.canDeactivateChecks;return 0===s.length&&0===u.length?qc(i({},n,{guardsResult:!0})):function(t,e,n,r){return ot(s).pipe(it(function(t){return function(t,e,n,r,o){var i=e&&e.routeConfig?e.routeConfig.canDeactivate:null;return i&&0!==i.length?qc(i.map(function(i){var a,u=Nd(i,e,o);if(function(t){return t&&md(t.canDeactivate)}(u))a=Ch(u.canDeactivate(t,e,n,r));else{if(!md(u))throw new Error("Invalid CanDeactivate guard");a=Ch(u(t,e,n,r))}return a.pipe(Cf())})).pipe(Md()):qc(!0)}(t.component,t.route,n,e,r)}),Cf(function(t){return!0!==t},!0))}(0,r,o,t).pipe(it(function(n){return n&&"boolean"==typeof n?function(t,e,n,r){return ot(u).pipe(If(function(e){return ot([Ud(e.route.parent,r),jd(e.route,r),Hd(t,e.path,n),Ld(t,e.route,n)]).pipe($c(),Cf(function(t){return!0!==t},!0))}),Cf(function(t){return!0!==t},!0))}(r,0,t,e):qc(n)}),tt(function(t){return i({},n,{guardsResult:t})}))}))}}(e.ngModule.injector,function(t){return e.triggerEvent(t)}),uf(function(t){if(bd(t.guardsResult)){var n=fh('Redirecting to "'+e.serializeUrl(t.guardsResult)+'"');throw n.url=t.guardsResult,n}}),uf(function(t){var n=new Kp(t.id,e.serializeUrl(t.extractedUrl),e.serializeUrl(t.urlAfterRedirects),t.targetSnapshot,!!t.guardsResult);e.triggerEvent(n)}),Jc(function(t){if(!t.guardsResult){e.resetUrlToCurrentUrlTree();var r=new Zp(t.id,e.serializeUrl(t.extractedUrl),"");return n.next(r),t.resolve(!1),!1}return!0}),$d(function(t){if(t.guards.canActivateChecks.length)return qc(t).pipe(uf(function(t){var n=new $p(t.id,e.serializeUrl(t.extractedUrl),e.serializeUrl(t.urlAfterRedirects),t.targetSnapshot);e.triggerEvent(n)}),(n=e.paramsInheritanceStrategy,r=e.ngModule.injector,function(t){return t.pipe(it(function(t){var e=t.targetSnapshot,o=t.guards.canActivateChecks;return o.length?ot(o).pipe(If(function(t){return function(t,n,r,o){return function(t,e,n,r){var o=Object.keys(t);if(0===o.length)return qc({});if(1===o.length){var i=o[0];return Kd(t[i],e,n,r).pipe(tt(function(t){var e;return(e={})[i]=t,e}))}var a={};return ot(o).pipe(it(function(o){return Kd(t[o],e,n,r).pipe(tt(function(t){return a[o]=t,t}))})).pipe(vf(),tt(function(){return a}))}(t._resolve,t,e,o).pipe(tt(function(e){return t._resolvedData=e,t.data=i({},t.data,Jh(t,r).resolve),null}))}(t.route,0,n,r)}),function(t,e){return arguments.length>=2?function(e){return I(Af(t,void 0),rf(1),pf(void 0))(e)}:function(e){return I(Af(function(e,n,r){return t(e)}),rf(1))(e)}}(function(t,e){return t}),tt(function(e){return t})):qc(t)}))}),uf(function(t){var n=new Jp(t.id,e.serializeUrl(t.extractedUrl),e.serializeUrl(t.urlAfterRedirects),t.targetSnapshot);e.triggerEvent(n)}));var n,r}),$d(function(t){var n=t.extras;return e.hooks.afterPreactivation(t.targetSnapshot,{navigationId:t.id,appliedUrlTree:t.extractedUrl,rawUrlTree:t.rawUrl,skipLocationChange:!!n.skipLocationChange,replaceUrl:!!n.replaceUrl})}),tt(function(t){var n,r,o,a=(o=function t(e,n,r){if(r&&e.shouldReuseRoute(n.value,r.value.snapshot)){(l=r.value)._futureSnapshot=n.value;var o=function(e,n,r){return n.children.map(function(n){var o,i;try{for(var a=s(r.children),u=a.next();!u.done;u=a.next()){var l=u.value;if(e.shouldReuseRoute(l.value.snapshot,n.value))return t(e,n,l)}}catch(c){o={error:c}}finally{try{u&&!u.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t(e,n)})}(e,n,r);return new Qh(l,o)}var i=e.retrieve(n.value);if(i){var a=i.route;return function t(e,n){if(e.value.routeConfig!==n.value.routeConfig)throw new Error("Cannot reattach ActivatedRouteSnapshot created from a different route");if(e.children.length!==n.children.length)throw new Error("Cannot reattach ActivatedRouteSnapshot with a different number of children");n.value._futureSnapshot=e.value;for(var r=0;r<e.children.length;++r)t(e.children[r],n.children[r])}(n,a),a}var u,l=new $h(new Bc((u=n.value).url),new Bc(u.params),new Bc(u.queryParams),new Bc(u.fragment),new Bc(u.data),u.outlet,u.component,u);return o=n.children.map(function(n){return t(e,n)}),new Qh(l,o)}(e.routeReuseStrategy,(n=t.targetSnapshot)._root,(r=t.currentRouterState)?r._root:void 0),new Yh(o,n));return i({},t,{targetRouterState:a})}),uf(function(t){e.currentUrlTree=t.urlAfterRedirects,e.rawUrlTree=e.urlHandlingStrategy.merge(e.currentUrlTree,t.rawUrl),e.routerState=t.targetRouterState,"deferred"===e.urlUpdateStrategy&&(t.extras.skipLocationChange||e.setBrowserUrl(e.rawUrlTree,!!t.extras.replaceUrl,t.id,t.extras.state),e.browserUrlTree=t.urlAfterRedirects)}),(o=e.rootContexts,a=e.routeReuseStrategy,u=function(t){return e.triggerEvent(t)},tt(function(t){return new gd(a,t.targetRouterState,t.currentRouterState,u).activate(o),t})),uf({next:function(){l=!0},complete:function(){l=!0}}),(r=function(){if(!l&&!c){e.resetUrlToCurrentUrlTree();var r=new Zp(t.id,e.serializeUrl(t.extractedUrl),"Navigation ID "+t.id+" is not equal to the current navigation id "+e.navigationId);n.next(r),t.resolve(!1)}e.currentNavigation=null},function(t){return t.lift(new Nf(r))}),gf(function(r){if(c=!0,(u=r)&&u[ch]){e.navigated=!0;var o=bd(r.url);o||e.resetStateAndUrl(t.currentRouterState,t.currentUrlTree,t.rawUrl);var i=new Zp(t.id,e.serializeUrl(t.extractedUrl),r.message);n.next(i),t.resolve(!1),o&&e.navigateByUrl(r.url)}else{e.resetStateAndUrl(t.currentRouterState,t.currentUrlTree,t.rawUrl);var a=new Qp(t.id,e.serializeUrl(t.extractedUrl),r);n.next(a);try{t.resolve(e.errorHandler(r))}catch(s){t.reject(s)}}var u;return Hc}))}))},t.prototype.resetRootComponentType=function(t){this.rootComponentType=t,this.routerState.root.component=this.rootComponentType},t.prototype.getTransition=function(){return this.transitions.value},t.prototype.setTransition=function(t){this.transitions.next(i({},this.getTransition(),t))},t.prototype.initialNavigation=function(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})},t.prototype.setUpLocationChangeListener=function(){var t=this;this.locationSubscription||(this.locationSubscription=this.location.subscribe(function(e){var n=t.parseUrl(e.url),r="popstate"===e.type?"popstate":"hashchange",o=e.state&&e.state.navigationId?e.state:null;setTimeout(function(){t.scheduleNavigation(n,r,o,{replaceUrl:!0})},0)}))},Object.defineProperty(t.prototype,"url",{get:function(){return this.serializeUrl(this.currentUrlTree)},enumerable:!0,configurable:!0}),t.prototype.getCurrentNavigation=function(){return this.currentNavigation},t.prototype.triggerEvent=function(t){this.events.next(t)},t.prototype.resetConfig=function(t){dh(t),this.config=t.map(yh),this.navigated=!1,this.lastSuccessfulId=-1},t.prototype.ngOnDestroy=function(){this.dispose()},t.prototype.dispose=function(){this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=null)},t.prototype.createUrlTree=function(t,e){void 0===e&&(e={});var n=e.relativeTo,r=e.queryParams,o=e.fragment,a=e.preserveQueryParams,u=e.queryParamsHandling,s=e.preserveFragment;go()&&a&&console&&console.warn&&console.warn("preserveQueryParams is deprecated, use queryParamsHandling instead.");var l=n||this.routerState.root,f=s?this.currentUrlTree.fragment:o,p=null;if(u)switch(u){case"merge":p=i({},this.currentUrlTree.queryParams,r);break;case"preserve":p=this.currentUrlTree.queryParams;break;default:p=r||null}else p=a?this.currentUrlTree.queryParams:r||null;return null!==p&&(p=this.removeEmptyProps(p)),function(t,e,n,r,o){if(0===n.length)return ad(e.root,e.root,e,r,o);var i=function(t){if("string"==typeof t[0]&&1===t.length&&"/"===t[0])return new ud(!0,0,t);var e=0,n=!1,r=t.reduce(function(t,r,o){if("object"==typeof r&&null!=r){if(r.outlets){var i={};return wh(r.outlets,function(t,e){i[e]="string"==typeof t?t.split("/"):t}),c(t,[{outlets:i}])}if(r.segmentPath)return c(t,[r.segmentPath])}return"string"!=typeof r?c(t,[r]):0===o?(r.split("/").forEach(function(r,o){0==o&&"."===r||(0==o&&""===r?n=!0:".."===r?e++:""!=r&&t.push(r))}),t):c(t,[r])},[]);return new ud(n,e,r)}(n);if(i.toRoot())return ad(e.root,new xh([],{}),e,r,o);var a=function(t,n,r){if(t.isAbsolute)return new sd(e.root,!0,0);if(-1===r.snapshot._lastPathIndex)return new sd(r.snapshot._urlSegment,!0,0);var o=id(t.commands[0])?0:1;return function(e,n,i){for(var a=r.snapshot._urlSegment,u=r.snapshot._lastPathIndex+o,s=t.numberOfDoubleDots;s>u;){if(s-=u,!(a=a.parent))throw new Error("Invalid number of '../'");u=a.segments.length}return new sd(a,!1,u-s)}()}(i,0,t),u=a.processChildren?fd(a.segmentGroup,a.index,i.commands):cd(a.segmentGroup,a.index,i.commands);return ad(a.segmentGroup,u,e,r,o)}(l,this.currentUrlTree,t,p,f)},t.prototype.navigateByUrl=function(t,e){void 0===e&&(e={skipLocationChange:!1}),go()&&this.isNgZoneEnabled&&!Si.isInAngularZone()&&this.console.warn("Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?");var n=bd(t)?t:this.parseUrl(t),r=this.urlHandlingStrategy.merge(n,this.rawUrlTree);return this.scheduleNavigation(r,"imperative",null,e)},t.prototype.navigate=function(t,e){return void 0===e&&(e={skipLocationChange:!1}),function(t){for(var e=0;e<t.length;e++){var n=t[e];if(null==n)throw new Error("The requested path contains "+n+" segment at index "+e)}}(t),this.navigateByUrl(this.createUrlTree(t,e),e)},t.prototype.serializeUrl=function(t){return this.urlSerializer.serialize(t)},t.prototype.parseUrl=function(t){var e;try{e=this.urlSerializer.parse(t)}catch(n){e=this.malformedUriErrorHandler(n,this.urlSerializer,t)}return e},t.prototype.isActive=function(t,e){if(bd(t))return Sh(this.currentUrlTree,t,e);var n=this.parseUrl(t);return Sh(this.currentUrlTree,n,e)},t.prototype.removeEmptyProps=function(t){return Object.keys(t).reduce(function(e,n){var r=t[n];return null!=r&&(e[n]=r),e},{})},t.prototype.processNavigations=function(){var t=this;this.navigations.subscribe(function(e){t.navigated=!0,t.lastSuccessfulId=e.id,t.events.next(new Gp(e.id,t.serializeUrl(e.extractedUrl),t.serializeUrl(t.currentUrlTree))),t.lastSuccessfulNavigation=t.currentNavigation,t.currentNavigation=null,e.resolve(!0)},function(e){t.console.warn("Unhandled Navigation Error: ")})},t.prototype.scheduleNavigation=function(t,e,n,r){var o=this.getTransition();if(o&&"imperative"!==e&&"imperative"===o.source&&o.rawUrl.toString()===t.toString())return Promise.resolve(!0);if(o&&"hashchange"==e&&"popstate"===o.source&&o.rawUrl.toString()===t.toString())return Promise.resolve(!0);if(o&&"popstate"==e&&"hashchange"===o.source&&o.rawUrl.toString()===t.toString())return Promise.resolve(!0);var i=null,a=null,u=new Promise(function(t,e){i=t,a=e}),s=++this.navigationId;return this.setTransition({id:s,source:e,restoredState:n,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:t,extras:r,resolve:i,reject:a,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(function(t){return Promise.reject(t)})},t.prototype.setBrowserUrl=function(t,e,n,r){var o=this.urlSerializer.serialize(t);r=r||{},this.location.isCurrentPathEqualTo(o)||e?this.location.replaceState(o,"",i({},r,{navigationId:n})):this.location.go(o,"",i({},r,{navigationId:n}))},t.prototype.resetStateAndUrl=function(t,e,n){this.routerState=t,this.currentUrlTree=e,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,n),this.resetUrlToCurrentUrlTree()},t.prototype.resetUrlToCurrentUrlTree=function(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),"",{navigationId:this.lastSuccessfulId})},t}(),sv=function(){return function(){this.outlet=null,this.route=null,this.resolver=null,this.children=new lv,this.attachRef=null}}(),lv=function(){function t(){this.contexts=new Map}return t.prototype.onChildOutletCreated=function(t,e){var n=this.getOrCreateContext(t);n.outlet=e,this.contexts.set(t,n)},t.prototype.onChildOutletDestroyed=function(t){var e=this.getContext(t);e&&(e.outlet=null)},t.prototype.onOutletDeactivated=function(){var t=this.contexts;return this.contexts=new Map,t},t.prototype.onOutletReAttached=function(t){this.contexts=t},t.prototype.getOrCreateContext=function(t){var e=this.getContext(t);return e||(e=new sv,this.contexts.set(t,e)),e},t.prototype.getContext=function(t){return this.contexts.get(t)||null},t}(),cv=function(){function t(t,e,n,r,o){this.parentContexts=t,this.location=e,this.resolver=n,this.changeDetector=o,this.activated=null,this._activatedRoute=null,this.activateEvents=new Lo,this.deactivateEvents=new Lo,this.name=r||uh,t.onChildOutletCreated(this.name,this)}return t.prototype.ngOnDestroy=function(){this.parentContexts.onChildOutletDestroyed(this.name)},t.prototype.ngOnInit=function(){if(!this.activated){var t=this.parentContexts.getContext(this.name);t&&t.route&&(t.attachRef?this.attach(t.attachRef,t.route):this.activateWith(t.route,t.resolver||null))}},Object.defineProperty(t.prototype,"isActivated",{get:function(){return!!this.activated},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"component",{get:function(){if(!this.activated)throw new Error("Outlet is not activated");return this.activated.instance},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activatedRoute",{get:function(){if(!this.activated)throw new Error("Outlet is not activated");return this._activatedRoute},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activatedRouteData",{get:function(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}},enumerable:!0,configurable:!0}),t.prototype.detach=function(){if(!this.activated)throw new Error("Outlet is not activated");this.location.detach();var t=this.activated;return this.activated=null,this._activatedRoute=null,t},t.prototype.attach=function(t,e){this.activated=t,this._activatedRoute=e,this.location.insert(t.hostView)},t.prototype.deactivate=function(){if(this.activated){var t=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(t)}},t.prototype.activateWith=function(t,e){if(this.isActivated)throw new Error("Cannot activate an already activated outlet");this._activatedRoute=t;var n=(e=e||this.resolver).resolveComponentFactory(t._futureSnapshot.routeConfig.component),r=this.parentContexts.getOrCreateContext(this.name).children,o=new fv(t,r,this.location.injector);this.activated=this.location.createComponent(n,this.location.length,o),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)},t}(),fv=function(){function t(t,e,n){this.route=t,this.childContexts=e,this.parent=n}return t.prototype.get=function(t,e){return t===$h?this.route:t===lv?this.childContexts:this.parent.get(t,e)},t}(),pv=function(){return function(){}}(),hv=function(){function t(){}return t.prototype.preload=function(t,e){return e().pipe(gf(function(){return qc(null)}))},t}(),dv=function(){function t(){}return t.prototype.preload=function(t,e){return qc(null)},t}(),vv=function(){function t(t,e,n,r,o){this.router=t,this.injector=r,this.preloadingStrategy=o,this.loader=new ev(e,n,function(e){return t.triggerEvent(new Xp(e))},function(e){return t.triggerEvent(new th(e))})}return t.prototype.setUpPreloading=function(){var t=this;this.subscription=this.router.events.pipe(Jc(function(t){return t instanceof Gp}),If(function(){return t.preload()})).subscribe(function(){})},t.prototype.preload=function(){var t=this.injector.get(Qr);return this.processRoutes(t,this.router.config)},t.prototype.ngOnDestroy=function(){this.subscription.unsubscribe()},t.prototype.processRoutes=function(t,e){var n,r,o=[];try{for(var i=s(e),a=i.next();!a.done;a=i.next()){var u=a.value;if(u.loadChildren&&!u.canLoad&&u._loadedConfig){var l=u._loadedConfig;o.push(this.processRoutes(l.module,l.routes))}else u.loadChildren&&!u.canLoad?o.push(this.preloadConfig(t,u)):u.children&&o.push(this.processRoutes(t,u.children))}}catch(c){n={error:c}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return ot(o).pipe(lt(),tt(function(t){}))},t.prototype.preloadConfig=function(t,e){var n=this;return this.preloadingStrategy.preload(e,function(){return n.loader.load(t.injector,e).pipe(it(function(t){return e._loadedConfig=t,n.processRoutes(t.module,t.routes)}))})},t}(),gv=function(){function t(t,e,n){void 0===n&&(n={}),this.router=t,this.viewportScroller=e,this.options=n,this.lastId=0,this.lastSource="imperative",this.restoredId=0,this.store={},n.scrollPositionRestoration=n.scrollPositionRestoration||"disabled",n.anchorScrolling=n.anchorScrolling||"disabled"}return t.prototype.init=function(){"disabled"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration("manual"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()},t.prototype.createScrollEvents=function(){var t=this;return this.router.events.subscribe(function(e){e instanceof Bp?(t.store[t.lastId]=t.viewportScroller.getScrollPosition(),t.lastSource=e.navigationTrigger,t.restoredId=e.restoredState?e.restoredState.navigationId:0):e instanceof Gp&&(t.lastId=e.id,t.scheduleScrollEvent(e,t.router.parseUrl(e.urlAfterRedirects).fragment))})},t.prototype.consumeScrollEvents=function(){var t=this;return this.router.events.subscribe(function(e){e instanceof ih&&(e.position?"top"===t.options.scrollPositionRestoration?t.viewportScroller.scrollToPosition([0,0]):"enabled"===t.options.scrollPositionRestoration&&t.viewportScroller.scrollToPosition(e.position):e.anchor&&"enabled"===t.options.anchorScrolling?t.viewportScroller.scrollToAnchor(e.anchor):"disabled"!==t.options.scrollPositionRestoration&&t.viewportScroller.scrollToPosition([0,0]))})},t.prototype.scheduleScrollEvent=function(t,e){this.router.triggerEvent(new ih(t,"popstate"===this.lastSource?this.store[this.restoredId]:null,e))},t.prototype.ngOnDestroy=function(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()},t}(),yv=new Tt("ROUTER_CONFIGURATION"),mv=new Tt("ROUTER_FORROOT_GUARD"),bv=[zl,{provide:Oh,useClass:Ph},{provide:uv,useFactory:Tv,deps:[Hi,Oh,lv,zl,pr,Bo,gi,tv,yv,[nv,new Ne],[Jd,new Ne]]},lv,{provide:$h,useFactory:kv,deps:[uv]},{provide:Bo,useClass:Gi},vv,dv,hv,{provide:yv,useValue:{enableTracing:!1}}];function _v(){return new Vi("Router",uv)}var wv=function(){function t(t,e){}var e;return e=t,t.forRoot=function(t,n){return{ngModule:e,providers:[bv,xv(t),{provide:mv,useFactory:Ev,deps:[[uv,new Ne,new De]]},{provide:yv,useValue:n||{}},{provide:Hl,useFactory:Sv,deps:[Ul,[new Ie(Fl),new Ne],yv]},{provide:gv,useFactory:Cv,deps:[uv,Uc,yv]},{provide:pv,useExisting:n&&n.preloadingStrategy?n.preloadingStrategy:dv},{provide:Vi,multi:!0,useFactory:_v},[Av,{provide:ti,multi:!0,useFactory:Ov,deps:[Av]},{provide:Iv,useFactory:Pv,deps:[Av]},{provide:ui,multi:!0,useExisting:Iv}]]}},t.forChild=function(t){return{ngModule:e,providers:[xv(t)]}},t}();function Cv(t,e,n){return n.scrollOffset&&e.setOffset(n.scrollOffset),new gv(t,e,n)}function Sv(t,e,n){return void 0===n&&(n={}),n.useHash?new Bl(t,e):new Gl(t,e)}function Ev(t){if(t)throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");return"guarded"}function xv(t){return[{provide:Ot,multi:!0,useValue:t},{provide:tv,multi:!0,useValue:t}]}function Tv(t,e,n,r,o,i,a,u,s,l,c){void 0===s&&(s={});var f=new uv(null,e,n,r,o,i,a,bh(u));if(l&&(f.urlHandlingStrategy=l),c&&(f.routeReuseStrategy=c),s.errorHandler&&(f.errorHandler=s.errorHandler),s.malformedUriErrorHandler&&(f.malformedUriErrorHandler=s.malformedUriErrorHandler),s.enableTracing){var p=Vf();f.events.subscribe(function(t){p.logGroup("Router Event: "+t.constructor.name),p.log(t.toString()),p.log(t),p.logGroupEnd()})}return s.onSameUrlNavigation&&(f.onSameUrlNavigation=s.onSameUrlNavigation),s.paramsInheritanceStrategy&&(f.paramsInheritanceStrategy=s.paramsInheritanceStrategy),s.urlUpdateStrategy&&(f.urlUpdateStrategy=s.urlUpdateStrategy),s.relativeLinkResolution&&(f.relativeLinkResolution=s.relativeLinkResolution),f}function kv(t){return t.routerState.root}var Av=function(){function t(t){this.injector=t,this.initNavigation=!1,this.resultOfPreactivationDone=new L}return t.prototype.appInitializer=function(){var t=this;return this.injector.get(Ll,Promise.resolve(null)).then(function(){var e=null,n=new Promise(function(t){return e=t}),r=t.injector.get(uv),o=t.injector.get(yv);if(t.isLegacyDisabled(o)||t.isLegacyEnabled(o))e(!0);else if("disabled"===o.initialNavigation)r.setUpLocationChangeListener(),e(!0);else{if("enabled"!==o.initialNavigation)throw new Error("Invalid initialNavigation options: '"+o.initialNavigation+"'");r.hooks.afterPreactivation=function(){return t.initNavigation?qc(null):(t.initNavigation=!0,e(!0),t.resultOfPreactivationDone)},r.initialNavigation()}return n})},t.prototype.bootstrapListener=function(t){var e=this.injector.get(yv),n=this.injector.get(vv),r=this.injector.get(gv),o=this.injector.get(uv),i=this.injector.get(Hi);t===i.components[0]&&(this.isLegacyEnabled(e)?o.initialNavigation():this.isLegacyDisabled(e)&&o.setUpLocationChangeListener(),n.setUpPreloading(),r.init(),o.resetRootComponentType(i.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())},t.prototype.isLegacyEnabled=function(t){return"legacy_enabled"===t.initialNavigation||!0===t.initialNavigation||void 0===t.initialNavigation},t.prototype.isLegacyDisabled=function(t){return"legacy_disabled"===t.initialNavigation||!1===t.initialNavigation},t}();function Ov(t){return t.appInitializer.bind(t)}function Pv(t){return t.bootstrapListener.bind(t)}var Iv=new Tt("Router Initializer"),Nv=za({encapsulation:2,styles:[],data:{}});function Rv(t){return Os(0,[(t()(),vu(0,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),rs(1,212992,null,0,cv,[lv,Wi,Br,[8,null],Ki],null,null)],function(t,e){t(e,1,0)},null)}function Dv(t){return Os(0,[(t()(),vu(0,0,null,null,1,"ng-component",[],null,null,null,Rv,Nv)),rs(1,49152,null,0,ah,[],null,null)],null,null)}var Vv=Ru("ng-component",ah,Dv,{},{},[]),Mv=function(){return function(t,e,n,r,o,i){this.quoteName=t,this.authorName=e,this.upvote=n,this.downvote=r,this.voteSender=o,this.completeDate=i,this.showDescription=!1}}(),jv=function(){function t(){this.isComplete=new Lo}return t.prototype.quoteComplete=function(t){this.isComplete.emit(t)},t.prototype.ngOnInit=function(){},t}(),Uv=za({encapsulation:0,styles:[[""]],data:{}});function Lv(t){return Os(0,[(t()(),vu(0,0,null,null,1,"p",[],null,null,null,null,null)),(t()(),Ts(1,null,["",""])),(t()(),vu(2,0,null,null,1,"p",[],null,null,null,null,null)),(t()(),Ts(3,null,["",""])),(t()(),vu(4,0,null,null,1,"p",[],null,null,null,null,null)),(t()(),Ts(5,null,["",""])),(t()(),vu(6,0,null,null,1,"p",[],null,null,null,null,null)),(t()(),Ts(7,null,["",""])),(t()(),vu(8,0,null,null,1,"button",[],null,[[null,"click"]],function(t,e,n){var r=!0,o=t.component;return"click"===e&&(r=!1!==(o.quote.upvote=o.quote.upvote+1)&&r),r},null,null)),(t()(),Ts(-1,null,["Upvote "])),(t()(),vu(10,0,null,null,1,"button",[],null,[[null,"click"]],function(t,e,n){var r=!0,o=t.component;return"click"===e&&(r=!1!==(o.quote.downvote=o.quote.downvote+1)&&r),r},null,null)),(t()(),Ts(-1,null,["Downvote "])),(t()(),vu(12,0,null,null,1,"button",[],null,[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.quoteComplete(!0)&&r),r},null,null)),(t()(),Ts(-1,null,[" Delete"]))],null,function(t,e){var n=e.component;t(e,1,0,n.quote.voteSender),t(e,3,0,n.quote.authorName),t(e,5,0,n.quote.upvote),t(e,7,0,n.quote.downvote)})}var Hv=function(){function t(t){this.elem=t,this.elem.nativeElement.style.backgroundColor=""}return t.prototype.onClicks=function(){this.textDeco("yellow")},t.prototype.onDoubleClicks=function(){this.textDeco("None")},t.prototype.textDeco=function(t){this.elem.nativeElement.style.textDecoration=t},t}(),Fv=function(){function t(){}return t.prototype.transform=function(t){var e=new Date,n=new Date(e.getFullYear(),e.getMonth(),e.getDate()),r=.001*Math.abs(t-n)/86400;return r>=1&&t>n?r:0},t}(),zv=function(t){function e(e,n){var r=t.call(this,e)||this;r.sources=n,r.completed=0,r.haveValues=0;var o=n.length;r.values=new Array(o);for(var i=0;i<o;i++){var a=J(r,n[i],null,i);a&&r.add(a)}return r}return o(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.values[n]=e,o._hasValue||(o._hasValue=!0,this.haveValues++)},e.prototype.notifyComplete=function(t){var e=this.destination,n=this.haveValues,r=this.values,o=r.length;t._hasValue?(this.completed++,this.completed===o&&(n===o&&e.next(r),e.complete())):e.complete()},e}(X),qv=function(){function t(){}return Object.defineProperty(t.prototype,"value",{get:function(){return this.control?this.control.value:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valid",{get:function(){return this.control?this.control.valid:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invalid",{get:function(){return this.control?this.control.invalid:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pending",{get:function(){return this.control?this.control.pending:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disabled",{get:function(){return this.control?this.control.disabled:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"enabled",{get:function(){return this.control?this.control.enabled:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"errors",{get:function(){return this.control?this.control.errors:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pristine",{get:function(){return this.control?this.control.pristine:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dirty",{get:function(){return this.control?this.control.dirty:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touched",{get:function(){return this.control?this.control.touched:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return this.control?this.control.status:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"untouched",{get:function(){return this.control?this.control.untouched:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"statusChanges",{get:function(){return this.control?this.control.statusChanges:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valueChanges",{get:function(){return this.control?this.control.valueChanges:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return null},enumerable:!0,configurable:!0}),t.prototype.reset=function(t){void 0===t&&(t=void 0),this.control&&this.control.reset(t)},t.prototype.hasError=function(t,e){return!!this.control&&this.control.hasError(t,e)},t.prototype.getError=function(t,e){return this.control?this.control.getError(t,e):null},t}(),Bv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),Object.defineProperty(e.prototype,"formDirective",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return null},enumerable:!0,configurable:!0}),e}(qv);function Gv(t){return null==t||0===t.length}var Zv=new Tt("NgValidators"),Qv=/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/,Wv=function(){function t(){}return t.min=function(t){return function(e){if(Gv(e.value)||Gv(t))return null;var n=parseFloat(e.value);return!isNaN(n)&&n<t?{min:{min:t,actual:e.value}}:null}},t.max=function(t){return function(e){if(Gv(e.value)||Gv(t))return null;var n=parseFloat(e.value);return!isNaN(n)&&n>t?{max:{max:t,actual:e.value}}:null}},t.required=function(t){return Gv(t.value)?{required:!0}:null},t.requiredTrue=function(t){return!0===t.value?null:{required:!0}},t.email=function(t){return Gv(t.value)?null:Qv.test(t.value)?null:{email:!0}},t.minLength=function(t){return function(e){if(Gv(e.value))return null;var n=e.value?e.value.length:0;return n<t?{minlength:{requiredLength:t,actualLength:n}}:null}},t.maxLength=function(t){return function(e){var n=e.value?e.value.length:0;return n>t?{maxlength:{requiredLength:t,actualLength:n}}:null}},t.pattern=function(e){return e?("string"==typeof e?(r="","^"!==e.charAt(0)&&(r+="^"),r+=e,"$"!==e.charAt(e.length-1)&&(r+="$"),n=new RegExp(r)):(r=e.toString(),n=e),function(t){if(Gv(t.value))return null;var e=t.value;return n.test(e)?null:{pattern:{requiredPattern:r,actualValue:e}}}):t.nullValidator;var n,r},t.nullValidator=function(t){return null},t.compose=function(t){if(!t)return null;var e=t.filter(Yv);return 0==e.length?null:function(t){return $v(function(t,n){return e.map(function(e){return e(t)})}(t))}},t.composeAsync=function(t){if(!t)return null;var e=t.filter(Yv);return 0==e.length?null:function(t){return function t(){for(var e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return"function"==typeof n[n.length-1]&&(e=n.pop()),1===n.length&&f(n[0])&&(n=n[0]),0===n.length?Hc:e?t(n).pipe(tt(function(t){return e.apply(void 0,t)})):new R(function(t){return new zv(t,n)})}(function(t,n){return e.map(function(e){return e(t)})}(t).map(Kv)).pipe(tt($v))}},t}();function Yv(t){return null!=t}function Kv(t){var e=Jo(t)?ot(t):t;if(!Xo(e))throw new Error("Expected validator to return Promise or Observable.");return e}function $v(t){var e=t.reduce(function(t,e){return null!=e?i({},t,e):t},{});return 0===Object.keys(e).length?null:e}var Jv=new Tt("NgValueAccessor"),Xv=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"checked",t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),tg=new Tt("CompositionEventMode"),eg=function(){function t(t,e,n){var r;this._renderer=t,this._elementRef=e,this._compositionMode=n,this.onChange=function(t){},this.onTouched=function(){},this._composing=!1,null==this._compositionMode&&(this._compositionMode=(r=Vf()?Vf().getUserAgent():"",!/android (\d+)/.test(r.toLowerCase())))}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._handleInput=function(t){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(t)},t.prototype._compositionStart=function(){this._composing=!0},t.prototype._compositionEnd=function(t){this._composing=!1,this._compositionMode&&this.onChange(t)},t}();function ng(t){return t.validate?function(e){return t.validate(e)}:t}function rg(t){return t.validate?function(e){return t.validate(e)}:t}var og=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}();function ig(){throw new Error("unimplemented")}var ag=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._parent=null,e.name=null,e.valueAccessor=null,e._rawValidators=[],e._rawAsyncValidators=[],e}return o(e,t),Object.defineProperty(e.prototype,"validator",{get:function(){return ig()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return ig()},enumerable:!0,configurable:!0}),e}(qv),ug=function(){function t(){this._accessors=[]}return t.prototype.add=function(t,e){this._accessors.push([t,e])},t.prototype.remove=function(t){for(var e=this._accessors.length-1;e>=0;--e)if(this._accessors[e][1]===t)return void this._accessors.splice(e,1)},t.prototype.select=function(t){var e=this;this._accessors.forEach(function(n){e._isSameGroup(n,t)&&n[1]!==t&&n[1].fireUncheck(t.value)})},t.prototype._isSameGroup=function(t,e){return!!t[0].control&&t[0]._parent===e._control._parent&&t[1].name===e.name},t}(),sg=function(){function t(t,e,n,r){this._renderer=t,this._elementRef=e,this._registry=n,this._injector=r,this.onChange=function(){},this.onTouched=function(){}}return t.prototype.ngOnInit=function(){this._control=this._injector.get(ag),this._checkName(),this._registry.add(this._control,this)},t.prototype.ngOnDestroy=function(){this._registry.remove(this)},t.prototype.writeValue=function(t){this._state=t===this.value,this._renderer.setProperty(this._elementRef.nativeElement,"checked",this._state)},t.prototype.registerOnChange=function(t){var e=this;this._fn=t,this.onChange=function(){t(e.value),e._registry.select(e)}},t.prototype.fireUncheck=function(t){this.writeValue(t)},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._checkName=function(){this.name&&this.formControlName&&this.name!==this.formControlName&&this._throwNameError(),!this.name&&this.formControlName&&(this.name=this.formControlName)},t.prototype._throwNameError=function(){throw new Error('\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type="radio" formControlName="food" name="food">\n ')},t}(),lg='\n <div [formGroup]="myGroup">\n <div formGroupName="person">\n <input formControlName="firstName">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });',cg='\n <form>\n <div ngModelGroup="person">\n <input [(ngModel)]="person.name" name="firstName">\n </div>\n </form>';function fg(t,e){return c(e.path,[t])}function pg(t,e){t||dg(e,"Cannot find control with"),e.valueAccessor||dg(e,"No value accessor for form control with"),t.validator=Wv.compose([t.validator,e.validator]),t.asyncValidator=Wv.composeAsync([t.asyncValidator,e.asyncValidator]),e.valueAccessor.writeValue(t.value),function(t,e){e.valueAccessor.registerOnChange(function(n){t._pendingValue=n,t._pendingChange=!0,t._pendingDirty=!0,"change"===t.updateOn&&hg(t,e)})}(t,e),function(t,e){t.registerOnChange(function(t,n){e.valueAccessor.writeValue(t),n&&e.viewToModelUpdate(t)})}(t,e),function(t,e){e.valueAccessor.registerOnTouched(function(){t._pendingTouched=!0,"blur"===t.updateOn&&t._pendingChange&&hg(t,e),"submit"!==t.updateOn&&t.markAsTouched()})}(t,e),e.valueAccessor.setDisabledState&&t.registerOnDisabledChange(function(t){e.valueAccessor.setDisabledState(t)}),e._rawValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})}),e._rawAsyncValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})})}function hg(t,e){t._pendingDirty&&t.markAsDirty(),t.setValue(t._pendingValue,{emitModelToViewChange:!1}),e.viewToModelUpdate(t._pendingValue),t._pendingChange=!1}function dg(t,e){var n;throw n=t.path.length>1?"path: '"+t.path.join(" -> ")+"'":t.path[0]?"name: '"+t.path+"'":"unspecified name attribute",new Error(e+" "+n)}function vg(t){return null!=t?Wv.compose(t.map(ng)):null}function gg(t){return null!=t?Wv.composeAsync(t.map(rg)):null}var yg=[Xv,function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",parseFloat(t))},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),og,function(){function t(t,e){this._renderer=t,this._elementRef=e,this._optionMap=new Map,this._idCounter=0,this.onChange=function(t){},this.onTouched=function(){},this._compareWith=jt}return Object.defineProperty(t.prototype,"compareWith",{set:function(t){if("function"!=typeof t)throw new Error("compareWith must be a function, but received "+JSON.stringify(t));this._compareWith=t},enumerable:!0,configurable:!0}),t.prototype.writeValue=function(t){this.value=t;var e=this._getOptionId(t);null==e&&this._renderer.setProperty(this._elementRef.nativeElement,"selectedIndex",-1);var n=function(t,e){return null==t?""+e:(e&&"object"==typeof e&&(e="Object"),(t+": "+e).slice(0,50))}(e,t);this._renderer.setProperty(this._elementRef.nativeElement,"value",n)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){e.value=e._getOptionValue(n),t(e.value)}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._registerOption=function(){return(this._idCounter++).toString()},t.prototype._getOptionId=function(t){var e,n;try{for(var r=s(Array.from(this._optionMap.keys())),o=r.next();!o.done;o=r.next()){var i=o.value;if(this._compareWith(this._optionMap.get(i),t))return i}}catch(a){e={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}return null},t.prototype._getOptionValue=function(t){var e=function(t){return t.split(":")[0]}(t);return this._optionMap.has(e)?this._optionMap.get(e):t},t}(),function(){function t(t,e){this._renderer=t,this._elementRef=e,this._optionMap=new Map,this._idCounter=0,this.onChange=function(t){},this.onTouched=function(){},this._compareWith=jt}return Object.defineProperty(t.prototype,"compareWith",{set:function(t){if("function"!=typeof t)throw new Error("compareWith must be a function, but received "+JSON.stringify(t));this._compareWith=t},enumerable:!0,configurable:!0}),t.prototype.writeValue=function(t){var e,n=this;if(this.value=t,Array.isArray(t)){var r=t.map(function(t){return n._getOptionId(t)});e=function(t,e){t._setSelected(r.indexOf(e.toString())>-1)}}else e=function(t,e){t._setSelected(!1)};this._optionMap.forEach(e)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){var r=[];if(n.hasOwnProperty("selectedOptions"))for(var o=n.selectedOptions,i=0;i<o.length;i++){var a=o.item(i),u=e._getOptionValue(a.value);r.push(u)}else for(o=n.options,i=0;i<o.length;i++)(a=o.item(i)).selected&&(u=e._getOptionValue(a.value),r.push(u));e.value=r,t(r)}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._registerOption=function(t){var e=(this._idCounter++).toString();return this._optionMap.set(e,t),e},t.prototype._getOptionId=function(t){var e,n;try{for(var r=s(Array.from(this._optionMap.keys())),o=r.next();!o.done;o=r.next()){var i=o.value;if(this._compareWith(this._optionMap.get(i)._value,t))return i}}catch(a){e={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}return null},t.prototype._getOptionValue=function(t){var e=function(t){return t.split(":")[0]}(t);return this._optionMap.has(e)?this._optionMap.get(e)._value:t},t}(),sg],mg=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.ngOnInit=function(){this._checkParentType(),this.formDirective.addFormGroup(this)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeFormGroup(this)},Object.defineProperty(e.prototype,"control",{get:function(){return this.formDirective.getFormGroup(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return fg(this.name,this._parent)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return vg(this._validators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return gg(this._asyncValidators)},enumerable:!0,configurable:!0}),e.prototype._checkParentType=function(){},e}(Bv),bg=function(){function t(t){this._cd=t}return Object.defineProperty(t.prototype,"ngClassUntouched",{get:function(){return!!this._cd.control&&this._cd.control.untouched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassTouched",{get:function(){return!!this._cd.control&&this._cd.control.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPristine",{get:function(){return!!this._cd.control&&this._cd.control.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassDirty",{get:function(){return!!this._cd.control&&this._cd.control.dirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassValid",{get:function(){return!!this._cd.control&&this._cd.control.valid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassInvalid",{get:function(){return!!this._cd.control&&this._cd.control.invalid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPending",{get:function(){return!!this._cd.control&&this._cd.control.pending},enumerable:!0,configurable:!0}),t}(),_g=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e}(bg),wg=function(t){function e(e){return t.call(this,e)||this}return o(e,t),e}(bg);function Cg(t){var e=Eg(t)?t.validators:t;return Array.isArray(e)?vg(e):e||null}function Sg(t,e){var n=Eg(e)?e.asyncValidators:t;return Array.isArray(n)?gg(n):n||null}function Eg(t){return null!=t&&!Array.isArray(t)&&"object"==typeof t}var xg=function(){function t(t,e){this.validator=t,this.asyncValidator=e,this._onCollectionChange=function(){},this.pristine=!0,this.touched=!1,this._onDisabledChange=[]}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valid",{get:function(){return"VALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invalid",{get:function(){return"INVALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pending",{get:function(){return"PENDING"==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disabled",{get:function(){return"DISABLED"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"enabled",{get:function(){return"DISABLED"!==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dirty",{get:function(){return!this.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"untouched",{get:function(){return!this.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateOn",{get:function(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"},enumerable:!0,configurable:!0}),t.prototype.setValidators=function(t){this.validator=Cg(t)},t.prototype.setAsyncValidators=function(t){this.asyncValidator=Sg(t)},t.prototype.clearValidators=function(){this.validator=null},t.prototype.clearAsyncValidators=function(){this.asyncValidator=null},t.prototype.markAsTouched=function(t){void 0===t&&(t={}),this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)},t.prototype.markAsUntouched=function(t){void 0===t&&(t={}),this.touched=!1,this._pendingTouched=!1,this._forEachChild(function(t){t.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype.markAsDirty=function(t){void 0===t&&(t={}),this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)},t.prototype.markAsPristine=function(t){void 0===t&&(t={}),this.pristine=!0,this._pendingDirty=!1,this._forEachChild(function(t){t.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype.markAsPending=function(t){void 0===t&&(t={}),this.status="PENDING",!1!==t.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!t.onlySelf&&this._parent.markAsPending(t)},t.prototype.disable=function(t){void 0===t&&(t={}),this.status="DISABLED",this.errors=null,this._forEachChild(function(e){e.disable(i({},t,{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!0)})},t.prototype.enable=function(t){void 0===t&&(t={}),this.status="VALID",this._forEachChild(function(e){e.enable(i({},t,{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!1)})},t.prototype._updateAncestors=function(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),this._parent._updatePristine(),this._parent._updateTouched())},t.prototype.setParent=function(t){this._parent=t},t.prototype.updateValueAndValidity=function(t){void 0===t&&(t={}),this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),"VALID"!==this.status&&"PENDING"!==this.status||this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)},t.prototype._updateTreeValidity=function(t){void 0===t&&(t={emitEvent:!0}),this._forEachChild(function(e){return e._updateTreeValidity(t)}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})},t.prototype._setInitialStatus=function(){this.status=this._allControlsDisabled()?"DISABLED":"VALID"},t.prototype._runValidator=function(){return this.validator?this.validator(this):null},t.prototype._runAsyncValidator=function(t){var e=this;if(this.asyncValidator){this.status="PENDING";var n=Kv(this.asyncValidator(this));this._asyncValidationSubscription=n.subscribe(function(n){return e.setErrors(n,{emitEvent:t})})}},t.prototype._cancelExistingSubscription=function(){this._asyncValidationSubscription&&this._asyncValidationSubscription.unsubscribe()},t.prototype.setErrors=function(t,e){void 0===e&&(e={}),this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)},t.prototype.get=function(t){return function(t,e,n){return null==e?null:(e instanceof Array||(e=e.split(".")),e instanceof Array&&0===e.length?null:e.reduce(function(t,e){return t instanceof kg?t.controls.hasOwnProperty(e)?t.controls[e]:null:t instanceof Ag&&t.at(e)||null},t))}(this,t)},t.prototype.getError=function(t,e){var n=e?this.get(e):this;return n&&n.errors?n.errors[t]:null},t.prototype.hasError=function(t,e){return!!this.getError(t,e)},Object.defineProperty(t.prototype,"root",{get:function(){for(var t=this;t._parent;)t=t._parent;return t},enumerable:!0,configurable:!0}),t.prototype._updateControlsErrors=function(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)},t.prototype._initObservables=function(){this.valueChanges=new Lo,this.statusChanges=new Lo},t.prototype._calculateStatus=function(){return this._allControlsDisabled()?"DISABLED":this.errors?"INVALID":this._anyControlsHaveStatus("PENDING")?"PENDING":this._anyControlsHaveStatus("INVALID")?"INVALID":"VALID"},t.prototype._anyControlsHaveStatus=function(t){return this._anyControls(function(e){return e.status===t})},t.prototype._anyControlsDirty=function(){return this._anyControls(function(t){return t.dirty})},t.prototype._anyControlsTouched=function(){return this._anyControls(function(t){return t.touched})},t.prototype._updatePristine=function(t){void 0===t&&(t={}),this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype._updateTouched=function(t){void 0===t&&(t={}),this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype._isBoxedValue=function(t){return"object"==typeof t&&null!==t&&2===Object.keys(t).length&&"value"in t&&"disabled"in t},t.prototype._registerOnCollectionChange=function(t){this._onCollectionChange=t},t.prototype._setUpdateStrategy=function(t){Eg(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)},t}(),Tg=function(t){function e(e,n,r){void 0===e&&(e=null);var o=t.call(this,Cg(n),Sg(r,n))||this;return o._onChange=[],o._applyFormState(e),o._setUpdateStrategy(n),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o._initObservables(),o}return o(e,t),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(function(t){return t(n.value,!1!==e.emitViewToModelChange)}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){void 0===e&&(e={}),this.setValue(t,e)},e.prototype.reset=function(t,e){void 0===t&&(t=null),void 0===e&&(e={}),this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1},e.prototype._updateValue=function(){},e.prototype._anyControls=function(t){return!1},e.prototype._allControlsDisabled=function(){return this.disabled},e.prototype.registerOnChange=function(t){this._onChange.push(t)},e.prototype._clearChangeFns=function(){this._onChange=[],this._onDisabledChange=[],this._onCollectionChange=function(){}},e.prototype.registerOnDisabledChange=function(t){this._onDisabledChange.push(t)},e.prototype._forEachChild=function(t){},e.prototype._syncPendingControls=function(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))},e.prototype._applyFormState=function(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t},e}(xg),kg=function(t){function e(e,n,r){var o=t.call(this,Cg(n),Sg(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return o(e,t),e.prototype.registerControl=function(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)},e.prototype.addControl=function(t,e){this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.removeControl=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.contains=function(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled},e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),Object.keys(t).forEach(function(r){n._throwIfControlMissing(r),n.controls[r].setValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),Object.keys(t).forEach(function(r){n.controls[r]&&n.controls[r].patchValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this._reduceChildren({},function(t,e,n){return t[n]=e instanceof Tg?e.value:e.getRawValue(),t})},e.prototype._syncPendingControls=function(){var t=this._reduceChildren(!1,function(t,e){return!!e._syncPendingControls()||t});return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!Object.keys(this.controls).length)throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.controls[t])throw new Error("Cannot find form control with name: "+t+".")},e.prototype._forEachChild=function(t){var e=this;Object.keys(this.controls).forEach(function(n){return t(e.controls[n],n)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){e.setParent(t),e._registerOnCollectionChange(t._onCollectionChange)})},e.prototype._updateValue=function(){this.value=this._reduceValue()},e.prototype._anyControls=function(t){var e=this,n=!1;return this._forEachChild(function(r,o){n=n||e.contains(o)&&t(r)}),n},e.prototype._reduceValue=function(){var t=this;return this._reduceChildren({},function(e,n,r){return(n.enabled||t.disabled)&&(e[r]=n.value),e})},e.prototype._reduceChildren=function(t,e){var n=t;return this._forEachChild(function(t,r){n=e(n,t,r)}),n},e.prototype._allControlsDisabled=function(){var t,e;try{for(var n=s(Object.keys(this.controls)),r=n.next();!r.done;r=n.next())if(this.controls[r.value].enabled)return!1}catch(o){t={error:o}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}return Object.keys(this.controls).length>0||this.disabled},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control with name: '"+n+"'.")})},e}(xg),Ag=function(t){function e(e,n,r){var o=t.call(this,Cg(n),Sg(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return o(e,t),e.prototype.at=function(t){return this.controls[t]},e.prototype.push=function(t){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.insert=function(t,e){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity()},e.prototype.removeAt=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),this.updateValueAndValidity()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity(),this._onCollectionChange()},Object.defineProperty(e.prototype,"length",{get:function(){return this.controls.length},enumerable:!0,configurable:!0}),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),t.forEach(function(t,r){n._throwIfControlMissing(r),n.at(r).setValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),t.forEach(function(t,r){n.at(r)&&n.at(r).patchValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t=[]),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this.controls.map(function(t){return t instanceof Tg?t.value:t.getRawValue()})},e.prototype._syncPendingControls=function(){var t=this.controls.reduce(function(t,e){return!!e._syncPendingControls()||t},!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!this.controls.length)throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.at(t))throw new Error("Cannot find form control at index "+t)},e.prototype._forEachChild=function(t){this.controls.forEach(function(e,n){t(e,n)})},e.prototype._updateValue=function(){var t=this;this.value=this.controls.filter(function(e){return e.enabled||t.disabled}).map(function(t){return t.value})},e.prototype._anyControls=function(t){return this.controls.some(function(e){return e.enabled&&t(e)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){return t._registerControl(e)})},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control at index: "+n+".")})},e.prototype._allControlsDisabled=function(){var t,e;try{for(var n=s(this.controls),r=n.next();!r.done;r=n.next())if(r.value.enabled)return!1}catch(o){t={error:o}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(t)throw t.error}}return this.controls.length>0||this.disabled},e.prototype._registerControl=function(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)},e}(xg),Og=Promise.resolve(null),Pg=function(t){function e(e,n){var r=t.call(this)||this;return r.submitted=!1,r._directives=[],r.ngSubmit=new Lo,r.form=new kg({},vg(e),gg(n)),r}return o(e,t),e.prototype.ngAfterViewInit=function(){this._setUpdateStrategy()},Object.defineProperty(e.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"controls",{get:function(){return this.form.controls},enumerable:!0,configurable:!0}),e.prototype.addControl=function(t){var e=this;Og.then(function(){var n=e._findContainer(t.path);t.control=n.registerControl(t.name,t.control),pg(t.control,t),t.control.updateValueAndValidity({emitEvent:!1}),e._directives.push(t)})},e.prototype.getControl=function(t){return this.form.get(t.path)},e.prototype.removeControl=function(t){var e=this;Og.then(function(){var n,r,o=e._findContainer(t.path);o&&o.removeControl(t.name),(r=(n=e._directives).indexOf(t))>-1&&n.splice(r,1)})},e.prototype.addFormGroup=function(t){var e=this;Og.then(function(){var n=e._findContainer(t.path),r=new kg({});(function(t,e){null==t&&dg(e,"Cannot find control with"),t.validator=Wv.compose([t.validator,e.validator]),t.asyncValidator=Wv.composeAsync([t.asyncValidator,e.asyncValidator])})(r,t),n.registerControl(t.name,r),r.updateValueAndValidity({emitEvent:!1})})},e.prototype.removeFormGroup=function(t){var e=this;Og.then(function(){var n=e._findContainer(t.path);n&&n.removeControl(t.name)})},e.prototype.getFormGroup=function(t){return this.form.get(t.path)},e.prototype.updateModel=function(t,e){var n=this;Og.then(function(){n.form.get(t.path).setValue(e)})},e.prototype.setValue=function(t){this.control.setValue(t)},e.prototype.onSubmit=function(t){return this.submitted=!0,e=this._directives,this.form._syncPendingControls(),e.forEach(function(t){var e=t.control;"submit"===e.updateOn&&e._pendingChange&&(t.viewToModelUpdate(e._pendingValue),e._pendingChange=!1)}),this.ngSubmit.emit(t),!1;var e},e.prototype.onReset=function(){this.resetForm()},e.prototype.resetForm=function(t){void 0===t&&(t=void 0),this.form.reset(t),this.submitted=!1},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)},e.prototype._findContainer=function(t){return t.pop(),t.length?this.form.get(t):this.form},e}(Bv),Ig=function(){function t(){}return t.modelParentException=function(){throw new Error('\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup\'s partner directive "formControlName" instead. Example:\n\n \n <div [formGroup]="myGroup">\n <input formControlName="firstName">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });\n\n Or, if you\'d like to avoid registering this form control, indicate that it\'s standalone in ngModelOptions:\n\n Example:\n\n \n <div [formGroup]="myGroup">\n <input formControlName="firstName">\n <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">\n </div>\n ')},t.formGroupNameException=function(){throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n "+lg+"\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n "+cg)},t.missingNameException=function(){throw new Error('If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as \'standalone\' in ngModelOptions.\n\n Example 1: <input [(ngModel)]="person.firstName" name="first">\n Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">')},t.modelGroupParentException=function(){throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n "+lg+"\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n "+cg)},t.ngFormWarning=function(){console.warn("\n It looks like you're using 'ngForm'.\n\n Support for using the 'ngForm' element selector has been deprecated in Angular v6 and will be removed\n in Angular v9.\n\n Use 'ng-form' instead.\n\n Before:\n <ngForm #myForm=\"ngForm\">\n\n After:\n <ng-form #myForm=\"ngForm\">\n ")},t}(),Ng=new Tt("NgFormSelectorWarning"),Rg=function(t){function e(e,n,r){var o=t.call(this)||this;return o._parent=e,o._validators=n,o._asyncValidators=r,o}var n;return o(e,t),n=e,e.prototype._checkParentType=function(){this._parent instanceof n||this._parent instanceof Pg||Ig.modelGroupParentException()},e}(mg),Dg=Promise.resolve(null),Vg=function(t){function e(e,n,r,o){var i=t.call(this)||this;return i.control=new Tg,i._registered=!1,i.update=new Lo,i._parent=e,i._rawValidators=n||[],i._rawAsyncValidators=r||[],i.valueAccessor=function(t,e){if(!e)return null;Array.isArray(e)||dg(t,"Value accessor was not provided as an array for form control with");var n=void 0,r=void 0,o=void 0;return e.forEach(function(e){var i;e.constructor===eg?n=e:(i=e,yg.some(function(t){return i.constructor===t})?(r&&dg(t,"More than one built-in value accessor matches form control with"),r=e):(o&&dg(t,"More than one custom value accessor matches form control with"),o=e))}),o||r||n||(dg(t,"No valid value accessor for form control with"),null)}(i,o),i}return o(e,t),e.prototype.ngOnChanges=function(t){this._checkForErrors(),this._registered||this._setUpControl(),"isDisabled"in t&&this._updateDisabled(t),function(t,e){if(!t.hasOwnProperty("model"))return!1;var n=t.model;return!!n.isFirstChange()||!jt(e,n.currentValue)}(t,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeControl(this)},Object.defineProperty(e.prototype,"path",{get:function(){return this._parent?fg(this.name,this._parent):[this.name]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return vg(this._rawValidators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return gg(this._rawAsyncValidators)},enumerable:!0,configurable:!0}),e.prototype.viewToModelUpdate=function(t){this.viewModel=t,this.update.emit(t)},e.prototype._setUpControl=function(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)},e.prototype._isStandalone=function(){return!this._parent||!(!this.options||!this.options.standalone)},e.prototype._setUpStandalone=function(){pg(this.control,this),this.control.updateValueAndValidity({emitEvent:!1})},e.prototype._checkForErrors=function(){this._isStandalone()||this._checkParentType(),this._checkName()},e.prototype._checkParentType=function(){!(this._parent instanceof Rg)&&this._parent instanceof mg?Ig.formGroupNameException():this._parent instanceof Rg||this._parent instanceof Pg||Ig.modelParentException()},e.prototype._checkName=function(){this.options&&this.options.name&&(this.name=this.options.name),this._isStandalone()||this.name||Ig.missingNameException()},e.prototype._updateValue=function(t){var e=this;Dg.then(function(){e.control.setValue(t,{emitViewToModelChange:!1})})},e.prototype._updateDisabled=function(t){var e=this,n=t.isDisabled.currentValue,r=""===n||n&&"false"!==n;Dg.then(function(){r&&!e.control.disabled?e.control.disable():!r&&e.control.disabled&&e.control.enable()})},e}(ag),Mg=function(){function t(){}return Object.defineProperty(t.prototype,"required",{get:function(){return this._required},set:function(t){this._required=null!=t&&!1!==t&&""+t!="false",this._onChange&&this._onChange()},enumerable:!0,configurable:!0}),t.prototype.validate=function(t){return this.required?Wv.required(t):null},t.prototype.registerOnValidatorChange=function(t){this._onChange=t},t}(),jg=function(){return function(){}}(),Ug=function(){return function(){}}(),Lg=function(){function t(){}var e;return e=t,t.withConfig=function(t){return{ngModule:e,providers:[{provide:Ng,useValue:t.warnOnDeprecatedNgFormSelector}]}},t}(),Hg=function(){function t(){this.newQuote=new Mv("","",0,0,"",new Date),this.addQuote=new Lo}return t.prototype.submitQuote=function(){this.addQuote.emit(this.newQuote)},t.prototype.ngOnInit=function(){},t}(),Fg=za({encapsulation:0,styles:[["form[_ngcontent-%COMP%]{background-color:green;color:#fff}"]],data:{}});function zg(t){return Os(0,[(t()(),vu(0,0,null,null,42,"div",[["class","container-fluid"]],null,null,null,null,null)),(t()(),vu(1,0,null,null,41,"div",[["class","row"]],null,null,null,null,null)),(t()(),vu(2,0,null,null,40,"form",[["novalidate",""]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngSubmit"],[null,"submit"],[null,"reset"]],function(t,e,n){var r=!0,o=t.component;return"submit"===e&&(r=!1!==Bu(t,4).onSubmit(n)&&r),"reset"===e&&(r=!1!==Bu(t,4).onReset()&&r),"ngSubmit"===e&&(r=!1!==o.submitQuote()&&r),r},null,null)),rs(3,16384,null,0,jg,[],null,null),rs(4,4210688,[["quoteForm",4]],0,Pg,[[8,null],[8,null]],null,{ngSubmit:"ngSubmit"}),is(2048,null,Bv,null,[Pg]),rs(6,16384,null,0,wg,[[4,Bv]],null,null),(t()(),vu(7,0,null,null,10,"div",[["class","form-group"]],null,null,null,null,null)),(t()(),vu(8,0,null,null,1,"label",[["for","authorName"]],null,null,null,null,null)),(t()(),Ts(-1,null,["authorName"])),(t()(),vu(10,0,null,null,7,"input",[["class","form-control"],["id","authorName"],["name","authorName"],["required",""],["type","text"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(t,e,n){var r=!0,o=t.component;return"input"===e&&(r=!1!==Bu(t,11)._handleInput(n.target.value)&&r),"blur"===e&&(r=!1!==Bu(t,11).onTouched()&&r),"compositionstart"===e&&(r=!1!==Bu(t,11)._compositionStart()&&r),"compositionend"===e&&(r=!1!==Bu(t,11)._compositionEnd(n.target.value)&&r),"ngModelChange"===e&&(r=!1!==(o.newQuote.authorName=n)&&r),r},null,null)),rs(11,16384,null,0,eg,[eo,Kr,[2,tg]],null,null),rs(12,16384,null,0,Mg,[],{required:[0,"required"]},null),is(1024,null,Zv,function(t){return[t]},[Mg]),is(1024,null,Jv,function(t){return[t]},[eg]),rs(15,671744,null,0,Vg,[[2,Bv],[6,Zv],[8,null],[6,Jv]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),is(2048,null,ag,null,[Vg]),rs(17,16384,null,0,_g,[[4,ag]],null,null),(t()(),vu(18,0,null,null,10,"div",[["class","form-group"]],null,null,null,null,null)),(t()(),vu(19,0,null,null,1,"label",[["for","SenderName"]],null,null,null,null,null)),(t()(),Ts(-1,null,["voteSender"])),(t()(),vu(21,0,null,null,7,"input",[["class","form-control"],["id","SenderName"],["name","voteSender"],["required",""],["type","text"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(t,e,n){var r=!0,o=t.component;return"input"===e&&(r=!1!==Bu(t,22)._handleInput(n.target.value)&&r),"blur"===e&&(r=!1!==Bu(t,22).onTouched()&&r),"compositionstart"===e&&(r=!1!==Bu(t,22)._compositionStart()&&r),"compositionend"===e&&(r=!1!==Bu(t,22)._compositionEnd(n.target.value)&&r),"ngModelChange"===e&&(r=!1!==(o.newQuote.voteSender=n)&&r),r},null,null)),rs(22,16384,null,0,eg,[eo,Kr,[2,tg]],null,null),rs(23,16384,null,0,Mg,[],{required:[0,"required"]},null),is(1024,null,Zv,function(t){return[t]},[Mg]),is(1024,null,Jv,function(t){return[t]},[eg]),rs(26,671744,null,0,Vg,[[2,Bv],[6,Zv],[8,null],[6,Jv]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),is(2048,null,ag,null,[Vg]),rs(28,16384,null,0,_g,[[4,ag]],null,null),(t()(),vu(29,0,null,null,11,"div",[["class","form-group"]],null,null,null,null,null)),(t()(),vu(30,0,null,null,1,"label",[["for","quoteName"]],null,null,null,null,null)),(t()(),Ts(-1,null,["quoteName"])),(t()(),vu(32,0,null,null,8,"textarea",[["class","form-control"],["id","description"],["name","quoteName"],["required",""],["rows","4"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(t,e,n){var r=!0,o=t.component;return"input"===e&&(r=!1!==Bu(t,33)._handleInput(n.target.value)&&r),"blur"===e&&(r=!1!==Bu(t,33).onTouched()&&r),"compositionstart"===e&&(r=!1!==Bu(t,33)._compositionStart()&&r),"compositionend"===e&&(r=!1!==Bu(t,33)._compositionEnd(n.target.value)&&r),"ngModelChange"===e&&(r=!1!==(o.newQuote.quoteName=n)&&r),r},null,null)),rs(33,16384,null,0,eg,[eo,Kr,[2,tg]],null,null),rs(34,16384,null,0,Mg,[],{required:[0,"required"]},null),is(1024,null,Zv,function(t){return[t]},[Mg]),is(1024,null,Jv,function(t){return[t]},[eg]),rs(37,671744,null,0,Vg,[[2,Bv],[6,Zv],[8,null],[6,Jv]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),is(2048,null,ag,null,[Vg]),rs(39,16384,null,0,_g,[[4,ag]],null,null),(t()(),Ts(-1,null,[" "])),(t()(),vu(41,0,null,null,1,"button",[["class","btn btn-success btn-lg"],["type","submit"]],null,null,null,null,null)),(t()(),Ts(-1,null,["Add Quote"]))],function(t,e){var n=e.component;t(e,12,0,""),t(e,15,0,"authorName",n.newQuote.authorName),t(e,23,0,""),t(e,26,0,"voteSender",n.newQuote.voteSender),t(e,34,0,""),t(e,37,0,"quoteName",n.newQuote.quoteName)},function(t,e){t(e,2,0,Bu(e,6).ngClassUntouched,Bu(e,6).ngClassTouched,Bu(e,6).ngClassPristine,Bu(e,6).ngClassDirty,Bu(e,6).ngClassValid,Bu(e,6).ngClassInvalid,Bu(e,6).ngClassPending),t(e,10,0,Bu(e,12).required?"":null,Bu(e,17).ngClassUntouched,Bu(e,17).ngClassTouched,Bu(e,17).ngClassPristine,Bu(e,17).ngClassDirty,Bu(e,17).ngClassValid,Bu(e,17).ngClassInvalid,Bu(e,17).ngClassPending),t(e,21,0,Bu(e,23).required?"":null,Bu(e,28).ngClassUntouched,Bu(e,28).ngClassTouched,Bu(e,28).ngClassPristine,Bu(e,28).ngClassDirty,Bu(e,28).ngClassValid,Bu(e,28).ngClassInvalid,Bu(e,28).ngClassPending),t(e,32,0,Bu(e,34).required?"":null,Bu(e,39).ngClassUntouched,Bu(e,39).ngClassTouched,Bu(e,39).ngClassPristine,Bu(e,39).ngClassDirty,Bu(e,39).ngClassValid,Bu(e,39).ngClassInvalid,Bu(e,39).ngClassPending)})}var qg=function(){function t(){this.quotes=[new Mv("Life is a journey not a destination","christine",0,0,"Ralph Waldo Emerson",new Date(2019,3,14)),new Mv("Do not cry because it is over.Smile because it happened","chantal",0,0,"by Dr.Seuss",new Date(2019,0,18)),new Mv("And now that you do not have to be perfect you can be GroupedObservable.","alice",0,0,"by John steinbeck",new Date(2019,2,14)),new Mv("Every thing is hard before it is is","maranatha",0,0,"by Johnn wolfgang von goethe",new Date(2019,6,9)),new Mv("Anyone who has never made a mistake has never tried anything new","bayizere",0,0,"Albert Einstein",new Date(2019,1,12)),new Mv("Do not let your happiness depend on something you may lose","claudine",0,0,"C.S Lewis",new Date(2019,3,14))]}return t.prototype.completequote=function(t,e){t&&this.quotes.splice(e,1)},t.prototype.toogleDetails=function(t){this.quotes[t].showDescription=!this.quotes[t].showDescription},t.prototype.addNewQuote=function(t){t.completeDate=new Date(t.completeDate),this.quotes.push(t)},t.prototype.ngOnInit=function(){},t}(),Bg=za({encapsulation:0,styles:[["*[_ngcontent-%COMP%]{background-color:#f5f5fc;text-align:center;padding-top:20px}img[_ngcontent-%COMP%]{padding-bottom:30px}#par[_ngcontent-%COMP%]{margin-left:200px;padding-bottom:80px}"]],data:{}});function Gg(t){return Os(0,[(t()(),vu(0,0,null,null,1,"app-quote-details",[],null,[[null,"isComplete"]],function(t,e,n){var r=!0;return"isComplete"===e&&(r=!1!==t.component.completequote(n,t.parent.context.index)&&r),r},Lv,Uv)),rs(1,114688,null,0,jv,[],{quote:[0,"quote"]},{isComplete:"isComplete"})],function(t,e){t(e,1,0,e.parent.context.$implicit)},null)}function Zg(t){return Os(0,[(t()(),vu(0,0,null,null,11,"div",[],null,null,null,null,null)),(t()(),vu(1,0,null,null,3,"li",[["appHighlight",""]],[[8,"id",0]],[[null,"click"],[null,"dblclick"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==Bu(t,2).onClicks()&&r),"dblclick"===e&&(r=!1!==Bu(t,2).onDoubleClicks()&&r),r},null,null)),rs(2,16384,null,0,Hv,[Kr],null,null),(t()(),Ts(3,null,[""," due on ",""])),xs(4,1),(t()(),vu(5,0,null,null,2,"p",[],null,null,null,null,null)),(t()(),Ts(6,null,["This quote will be completed in "," days"])),xs(7,1),(t()(),vu(8,0,null,null,1,"button",[],null,[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.toogleDetails(t.context.index)&&r),r},null,null)),(t()(),Ts(-1,null,["Show Details"])),(t()(),du(16777216,null,null,1,null,Gg)),rs(11,16384,null,0,Ic,[Wi,Ho],{ngIf:[0,"ngIf"]},null)],function(t,e){t(e,11,0,e.context.$implicit.showDescription)},function(t,e){var n;t(e,1,0,""+(null!=(n=e.context.index)?n.toString():""));var r=e.context.$implicit.quoteName,o=La(e,3,1,t(e,4,0,Bu(e.parent,0),e.context.$implicit.completeDate));t(e,3,0,r,o);var i=La(e,6,0,t(e,7,0,Bu(e.parent,1),e.context.$implicit.completeDate));t(e,6,0,i)})}function Qg(t){return Os(0,[os(0,Dc,[_a]),os(0,Fv,[]),(t()(),vu(2,0,null,null,10,"div",[["class","container"]],null,null,null,null,null)),(t()(),vu(3,0,null,null,1,"h1",[],null,null,null,null,null)),(t()(),Ts(-1,null,["Welcome to Quotes Votes application!"])),(t()(),vu(5,0,null,null,0,"img",[["height","400px"],["src","https://marketplace.canva.com/MAB5U3d02AA/2/0/thumbnail_large/canva-black-and-white-striped-quote-poster-MAB5U3d02AA.jpg"],["width","600px"]],null,null,null,null,null)),(t()(),vu(6,0,null,null,1,"div",[["id","par"]],null,null,null,null,null)),(t()(),Ts(-1,null,[" This application help you choose quote read it and understand it,if you like it upvote it,if you do not like it downvote it. Do you have quote to add? add it below on the form. You are Welcome again.\n"])),(t()(),vu(8,0,null,null,4,"ul",[],null,null,null,null,null)),(t()(),du(16777216,null,null,1,null,Zg)),rs(10,278528,null,0,Oc,[Wi,Ho,da],{ngForOf:[0,"ngForOf"]},null),(t()(),vu(11,0,null,null,1,"app-quote-form",[],null,[[null,"addQuote"]],function(t,e,n){var r=!0;return"addQuote"===e&&(r=!1!==t.component.addNewQuote(n)&&r),r},zg,Fg)),rs(12,114688,null,0,Hg,[],null,{addQuote:"addQuote"})],function(t,e){t(e,10,0,e.component.quotes),t(e,12,0)},null)}var Wg=za({encapsulation:2,styles:[],data:{}});function Yg(t){return Os(0,[(t()(),vu(0,0,null,null,1,"app-votes",[],null,null,null,Qg,Bg)),rs(1,114688,null,0,qg,[],null,null)],function(t,e){t(e,1,0)},null)}function Kg(t){return Os(0,[(t()(),vu(0,0,null,null,1,"app-root",[],null,null,null,Yg,Wg)),rs(1,49152,null,0,jl,[],null,null)],null,null)}var $g=Ru("app-root",jl,Kg,{},{},[]),Jg=function(){return function(){}}(),Xg=Dl(Ml,[jl],function(t){return function(t){for(var e={},n=[],r=!1,o=0;o<t.length;o++){var i=t[o];i.token===Tr&&!0===i.value&&(r=!0),1073741824&i.flags&&n.push(i.token),i.index=o,e[Ua(i.token)]=i}return{factory:null,providersByKey:e,providers:t,modules:n,isRoot:r}}([Eu(512,Br,Gr,[[8,[Vv,$g]],[3,Br],Qr]),Eu(5120,_a,Sa,[[3,_a]]),Eu(4608,Tc,kc,[_a,[2,xc]]),Eu(5120,ni,ri,[]),Eu(5120,da,wa,[]),Eu(5120,va,Ca,[]),Eu(4608,Np,Rp,[Mc]),Eu(6144,oo,null,[Np]),Eu(4608,xp,kp,[]),Eu(5120,Jf,function(t,e,n,r,o,i,a,u){return[new Sp(t,e,n),new Ip(r),new Ap(o,i,a,u)]},[Mc,Si,ai,Mc,Mc,xp,si,[2,Tp]]),Eu(4608,Xf,Xf,[Jf,Si]),Eu(135680,np,np,[Mc]),Eu(4608,lp,lp,[Xf,np]),Eu(6144,Xr,null,[lp]),Eu(6144,ep,null,[np]),Eu(4608,Ii,Ii,[Si]),Eu(5120,$h,kv,[uv]),Eu(4608,dv,dv,[]),Eu(6144,pv,null,[dv]),Eu(135680,vv,vv,[uv,Bo,gi,pr,pv]),Eu(4608,hv,hv,[]),Eu(5120,gv,Cv,[uv,Uc,yv]),Eu(5120,Iv,Pv,[Av]),Eu(5120,ui,function(t){return[t]},[Iv]),Eu(4608,ug,ug,[]),Eu(1073742336,Vc,Vc,[]),Eu(1024,$o,Fp,[]),Eu(1024,Vi,function(){return[_v()]},[]),Eu(512,Av,Av,[pr]),Eu(1024,ti,function(t,e){return[(n=t,Yf("probe",$f),Yf("coreTokens",i({},Kf,(n||[]).reduce(function(t,e){return t[e.name]=e.token,t},{}))),function(){return $f}),Ov(e)];var n},[[2,Vi],Av]),Eu(512,ei,ei,[[2,ti]]),Eu(131584,Hi,Hi,[Si,si,pr,$o,Br,ei]),Eu(1073742336,Ea,Ea,[Hi]),Eu(1073742336,zp,zp,[[3,zp]]),Eu(1024,mv,Ev,[[3,uv]]),Eu(512,Oh,Ph,[]),Eu(512,lv,lv,[]),Eu(256,yv,{},[]),Eu(1024,Hl,Sv,[Ul,[2,Fl],yv]),Eu(512,zl,zl,[Hl]),Eu(512,gi,gi,[]),Eu(512,Bo,Gi,[gi,[2,qi]]),Eu(1024,tv,function(){return[[]]},[]),Eu(1024,uv,Tv,[Hi,Oh,lv,zl,pr,Bo,gi,tv,yv,[2,nv],[2,Jd]]),Eu(1073742336,wv,wv,[[2,mv],[2,uv]]),Eu(1073742336,Jg,Jg,[]),Eu(1073742336,Ug,Ug,[]),Eu(1073742336,Lg,Lg,[]),Eu(1073742336,Ml,Ml,[]),Eu(256,Tr,!0,[])])});(function(){if(vo)throw new Error("Cannot enable prod mode after platform setup.");ho=!1})(),Hp().bootstrapModuleFactory(Xg).catch(function(t){return console.error(t)})}},[[0,0]]]);
Xs
gmm-acc-stats_8cc.js
var gmm_acc_stats_8cc = [ [ "main", "gmm-acc-stats_8cc.html#a0ddf1224851353fc92bfbff6f499fa97", null ] ];
main.rs
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate error_chain; extern crate reqwest; extern crate serde_json; use std::io::{self, Write}; use std::{env, process}; use serde_json::{map, Value}; // We'll put our errors in a `errors` module mod errors { // Create the Error, ErrorKind, ResultExt, and Result types #[allow(unused_doc_comments)] error_chain! { // Automatic conversions between this error chain and other // error types not defined by the `error_chain!`. foreign_links { IO(::std::io::Error); Reqwest(::reqwest::Error); } } } type Map = map::Map<String, Value>; fn download<F>(uri: &str, mut action: F, debug: bool) -> errors::Result<()> where F: FnMut(Map) -> errors::Result<()>, { let json: Value = reqwest::blocking::get(uri)?.json()?; let json = if let Value::Object(m) = json { m } else { bail!("Malformed JSON: {:?}", json) }; if debug { writeln!(io::stderr(), "#json == {}", json.len())?; writeln!( io::stderr(), "License list version {}", get(&json, "licenseListVersion")? )?; } action(json) } fn get<'a>(m: &'a Map, k: &str) -> errors::Result<&'a Value> { if let Some(v) = m.get(k) { Ok(v) } else { bail!("Malformed JSON: {:?} lacks {}", m, k) } } fn main1(args: &[String]) -> errors::Result<()> { let mut upstream_tag = "master"; let mut debug = false; for e in args { match e.as_str() { "-d" => { debug = true; } s if s.starts_with('v') => { upstream_tag = &s; } _ => bail!("Unknown option {:?}", e), } } let mut stdout = io::stdout(); let mut stderr = io::stderr(); if upstream_tag == "master" { writeln!( stderr, "WARN: fetching data from the master branch of spdx/license-list-data; \ consider specifying a tag (e.g. v3.0)" )?; } else { writeln!(stderr, "Using tag {:?}", upstream_tag)?; } writeln!( stdout, "\ /* * whitelist fetched from https://github.com/spdx/license-list-data * * AUTO-GENERATED BY ./fetch-license-list-from-spdx * DO NOT MODIFY * * cargo run -p fetch-license-list-from-spdx -- {} > src/spdx.rs */ ", upstream_tag )?; let licenses_json_uri = format!( "https://raw.githubusercontent.com/spdx/license-list-data/{}/json/licenses.json", upstream_tag ); download( &licenses_json_uri, |json| { let licenses = get(&json, "licenses")?; let licenses = if let &Value::Array(ref v) = licenses { v } else { bail!("Malformed JSON: {:?}", licenses) }; writeln!(stderr, "#licenses == {}", licenses.len())?; let mut v = vec![]; for lic in licenses.iter() { let lic = if let Value::Object(ref m) = *lic { m } else { bail!("Malformed JSON: {:?}", lic) }; if debug { writeln!( stderr, "{:?},{:?}", get(&lic, "licenseId"), get(&lic, "name") )?; } let lic_id = get(&lic, "licenseId")?; if let &Value::String(ref s) = lic_id { v.push(s); } else { bail!("Malformed JSON: {:?}", lic_id); } } v.sort(); let lic_list_ver = get(&json, "licenseListVersion")?; if let &Value::String(ref s) = lic_list_ver { writeln!(stdout, "pub const VERSION: &'static str = {:?};", s)?; } else { bail!("Malformed JSON: {:?}", lic_list_ver) } writeln!(stdout)?; writeln!(stdout, "pub const LICENSES: &'static [&'static str] = &[")?; for lic in v.iter() { writeln!(stdout, " \"{}\",", lic)?; } writeln!(stdout, "];")?; Ok(()) }, debug, )?; writeln!(stdout)?; let exceptions_json_uri = format!( "https://raw.githubusercontent.com/spdx/license-list-data/{}/json/exceptions.json", upstream_tag ); download( &exceptions_json_uri, |json| { let exceptions = get(&json, "exceptions")?; let exceptions = if let &Value::Array(ref v) = exceptions { v } else { bail!("Malformed JSON: {:?}", exceptions) }; writeln!(stderr, "#exceptions == {}", exceptions.len())?; let mut v = vec![]; for exc in exceptions.iter() { let exc = if let Value::Object(ref m) = *exc { m } else { bail!("Malformed JSON: {:?}", exc) }; if debug { writeln!( stderr, "{:?},{:?}", get(&exc, "licenseExceptionId"),
} let lic_exc_id = get(&exc, "licenseExceptionId")?; if let &Value::String(ref s) = lic_exc_id { v.push(s); } else { bail!("Malformed JSON: {:?}", lic_exc_id) }; } writeln!(stdout, "pub const EXCEPTIONS: &'static [&'static str] = &[")?; v.sort(); for exc in v.iter() { writeln!(stdout, " \"{}\",", exc)?; } writeln!(stdout, "];")?; Ok(()) }, debug, )?; Ok(()) } fn main() { let args = env::args().skip(1).collect::<Vec<_>>(); if let Err(ref e) = main1(args.as_ref()) { use error_chain::ChainedError; // trait which holds `display_chain` writeln!(io::stderr(), "{}", e.display_chain()).expect("writeln to stderr"); process::exit(1); } }
get(&exc, "name") )?;
project-api.interface.ts
/*! * @license * Copyright 2019 Alfresco, Inc. and/or its affiliates.
* * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Project, Release, Pagination, ReleaseEntry, ServerSideSorting, SearchQuery, CollaboratorEntry, FetchQueries } from './types'; import { ValidationErrors } from '../interfaces/validation-errors.interface'; import { PaginatedEntries } from '@alfresco/js-api'; import { IdentityUserModel } from '@alfresco/adf-core'; @Injectable() export abstract class ProjectApi { public abstract create(project: Partial<Project>): Observable<Project>; public abstract get(projectId: string): Observable<Project>; public abstract update(projectId: string, project: Partial<Project>): Observable<Project>; public abstract copy(projectId: string, name: string): Observable<Project>; public abstract delete(projectId: string): Observable<void>; public abstract validate(projectId: string): Observable<void | ValidationErrors>; public abstract addToFavorites(projectId: string): Observable<void>; public abstract removeFromFavorites(projectId: string): Observable<void>; public abstract import(file: File, name?: string): Observable<any>; public abstract export(projectId: string): Observable<Blob>; public abstract getAll(fetchQueries?: FetchQueries, sorting?: ServerSideSorting, search?: SearchQuery, fetchFavorites?: boolean): Observable<PaginatedEntries<Project>>; public abstract release(projectId: string): Observable<Release>; public abstract getProjectReleases(projectId: string, pagination?: Partial<Pagination>): Observable<PaginatedEntries<ReleaseEntry>>; public abstract getCollaborators(projectId: string): Observable<PaginatedEntries<CollaboratorEntry>>; public abstract addCollaborator(projectId: string, collaborator: IdentityUserModel): Observable<CollaboratorEntry>; public abstract removeCollaborator(projectId: string, collaborator: IdentityUserModel): Observable<void>; public abstract downloadRelease(releaseId: string): Observable<Blob>; public abstract uploadRelease(projectId: string, file: File): Observable<Release>; public abstract restoreRelease(releaseId: string): Observable<Release>; }
* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at
types.generated.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ************************************************************ // DO NOT EDIT. // THIS FILE IS AUTO-GENERATED BY codecgen. // ************************************************************ package v2alpha1 import ( "errors" "fmt" codec1978 "github.com/ugorji/go/codec" pkg1_resource "k8s.io/apimachinery/pkg/api/resource" pkg3_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" pkg4_types "k8s.io/apimachinery/pkg/types" pkg2_v1 "k8s.io/kubernetes/pkg/api/v1" "reflect" "runtime" time "time" ) const ( // ----- content types ---- codecSelferC_UTF81234 = 1 codecSelferC_RAW1234 = 0 // ----- value types used ---- codecSelferValueTypeArray1234 = 10 codecSelferValueTypeMap1234 = 9 // ----- containerStateValues ---- codecSelfer_containerMapKey1234 = 2 codecSelfer_containerMapValue1234 = 3 codecSelfer_containerMapEnd1234 = 4 codecSelfer_containerArrayElem1234 = 6 codecSelfer_containerArrayEnd1234 = 7 ) var ( codecSelferBitsize1234 = uint8(reflect.TypeOf(uint(0)).Bits()) codecSelferOnlyMapOrArrayEncodeToStructErr1234 = errors.New(`only encoded map or array can be decoded into a struct`) ) type codecSelfer1234 struct{} func
() { if codec1978.GenVersion != 5 { _, file, _, _ := runtime.Caller(0) err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", 5, codec1978.GenVersion, file) panic(err) } if false { // reference the types, but skip this branch at build/run time var v0 pkg1_resource.Quantity var v1 pkg3_v1.Time var v2 pkg4_types.UID var v3 pkg2_v1.ResourceName var v4 time.Time _, _, _, _, _ = v0, v1, v2, v3, v4 } } func (x *CrossVersionObjectReference) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[2] = x.APIVersion != "" var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) } else { yynn2 = 2 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym4 := z.EncBinary() _ = yym4 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym7 := z.EncBinary() _ = yym7 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Name)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("name")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Name)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym11 := z.EncBinary() _ = yym11 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *CrossVersionObjectReference) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *CrossVersionObjectReference) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "kind": if r.TryDecodeAsNil() { x.Kind = "" } else { yyv4 := &x.Kind yym5 := z.DecBinary() _ = yym5 if false { } else { *((*string)(yyv4)) = r.DecodeString() } } case "name": if r.TryDecodeAsNil() { x.Name = "" } else { yyv6 := &x.Name yym7 := z.DecBinary() _ = yym7 if false { } else { *((*string)(yyv6)) = r.DecodeString() } } case "apiVersion": if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv8 := &x.APIVersion yym9 := z.DecBinary() _ = yym9 if false { } else { *((*string)(yyv8)) = r.DecodeString() } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *CrossVersionObjectReference) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj10 int var yyb10 bool var yyhl10 bool = l >= 0 yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = r.CheckBreak() } if yyb10 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Kind = "" } else { yyv11 := &x.Kind yym12 := z.DecBinary() _ = yym12 if false { } else { *((*string)(yyv11)) = r.DecodeString() } } yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = r.CheckBreak() } if yyb10 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Name = "" } else { yyv13 := &x.Name yym14 := z.DecBinary() _ = yym14 if false { } else { *((*string)(yyv13)) = r.DecodeString() } } yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = r.CheckBreak() } if yyb10 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv15 := &x.APIVersion yym16 := z.DecBinary() _ = yym16 if false { } else { *((*string)(yyv15)) = r.DecodeString() } } for { yyj10++ if yyhl10 { yyb10 = yyj10 > l } else { yyb10 = r.CheckBreak() } if yyb10 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj10-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *HorizontalPodAutoscalerSpec) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [4]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.MinReplicas != nil yyq2[3] = len(x.Metrics) != 0 var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(4) } else { yynn2 = 2 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy4 := &x.ScaleTargetRef yy4.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("scaleTargetRef")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy6 := &x.ScaleTargetRef yy6.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.MinReplicas == nil { r.EncodeNil() } else { yy9 := *x.MinReplicas yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeInt(int64(yy9)) } } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("minReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.MinReplicas == nil { r.EncodeNil() } else { yy11 := *x.MinReplicas yym12 := z.EncBinary() _ = yym12 if false { } else { r.EncodeInt(int64(yy11)) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym14 := z.EncBinary() _ = yym14 if false { } else { r.EncodeInt(int64(x.MaxReplicas)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("maxReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym15 := z.EncBinary() _ = yym15 if false { } else { r.EncodeInt(int64(x.MaxReplicas)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[3] { if x.Metrics == nil { r.EncodeNil() } else { yym17 := z.EncBinary() _ = yym17 if false { } else { h.encSliceMetricSpec(([]MetricSpec)(x.Metrics), e) } } } else { r.EncodeNil() } } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metrics")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Metrics == nil { r.EncodeNil() } else { yym18 := z.EncBinary() _ = yym18 if false { } else { h.encSliceMetricSpec(([]MetricSpec)(x.Metrics), e) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *HorizontalPodAutoscalerSpec) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *HorizontalPodAutoscalerSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "scaleTargetRef": if r.TryDecodeAsNil() { x.ScaleTargetRef = CrossVersionObjectReference{} } else { yyv4 := &x.ScaleTargetRef yyv4.CodecDecodeSelf(d) } case "minReplicas": if r.TryDecodeAsNil() { if x.MinReplicas != nil { x.MinReplicas = nil } } else { if x.MinReplicas == nil { x.MinReplicas = new(int32) } yym6 := z.DecBinary() _ = yym6 if false { } else { *((*int32)(x.MinReplicas)) = int32(r.DecodeInt(32)) } } case "maxReplicas": if r.TryDecodeAsNil() { x.MaxReplicas = 0 } else { yyv7 := &x.MaxReplicas yym8 := z.DecBinary() _ = yym8 if false { } else { *((*int32)(yyv7)) = int32(r.DecodeInt(32)) } } case "metrics": if r.TryDecodeAsNil() { x.Metrics = nil } else { yyv9 := &x.Metrics yym10 := z.DecBinary() _ = yym10 if false { } else { h.decSliceMetricSpec((*[]MetricSpec)(yyv9), d) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *HorizontalPodAutoscalerSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj11 int var yyb11 bool var yyhl11 bool = l >= 0 yyj11++ if yyhl11 { yyb11 = yyj11 > l } else { yyb11 = r.CheckBreak() } if yyb11 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.ScaleTargetRef = CrossVersionObjectReference{} } else { yyv12 := &x.ScaleTargetRef yyv12.CodecDecodeSelf(d) } yyj11++ if yyhl11 { yyb11 = yyj11 > l } else { yyb11 = r.CheckBreak() } if yyb11 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.MinReplicas != nil { x.MinReplicas = nil } } else { if x.MinReplicas == nil { x.MinReplicas = new(int32) } yym14 := z.DecBinary() _ = yym14 if false { } else { *((*int32)(x.MinReplicas)) = int32(r.DecodeInt(32)) } } yyj11++ if yyhl11 { yyb11 = yyj11 > l } else { yyb11 = r.CheckBreak() } if yyb11 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.MaxReplicas = 0 } else { yyv15 := &x.MaxReplicas yym16 := z.DecBinary() _ = yym16 if false { } else { *((*int32)(yyv15)) = int32(r.DecodeInt(32)) } } yyj11++ if yyhl11 { yyb11 = yyj11 > l } else { yyb11 = r.CheckBreak() } if yyb11 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Metrics = nil } else { yyv17 := &x.Metrics yym18 := z.DecBinary() _ = yym18 if false { } else { h.decSliceMetricSpec((*[]MetricSpec)(yyv17), d) } } for { yyj11++ if yyhl11 { yyb11 = yyj11 > l } else { yyb11 = r.CheckBreak() } if yyb11 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj11-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x MetricSourceType) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { r.EncodeString(codecSelferC_UTF81234, string(x)) } } func (x *MetricSourceType) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { *((*string)(x)) = r.DecodeString() } } func (x *MetricSpec) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [4]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.Object != nil yyq2[2] = x.Pods != nil yyq2[3] = x.Resource != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(4) } else { yynn2 = 1 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) x.Type.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("type")) z.EncSendContainerState(codecSelfer_containerMapValue1234) x.Type.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.Object == nil { r.EncodeNil() } else { x.Object.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("object")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Object == nil { r.EncodeNil() } else { x.Object.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { if x.Pods == nil { r.EncodeNil() } else { x.Pods.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("pods")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Pods == nil { r.EncodeNil() } else { x.Pods.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[3] { if x.Resource == nil { r.EncodeNil() } else { x.Resource.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("resource")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Resource == nil { r.EncodeNil() } else { x.Resource.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *MetricSpec) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *MetricSpec) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "type": if r.TryDecodeAsNil() { x.Type = "" } else { yyv4 := &x.Type yyv4.CodecDecodeSelf(d) } case "object": if r.TryDecodeAsNil() { if x.Object != nil { x.Object = nil } } else { if x.Object == nil { x.Object = new(ObjectMetricSource) } x.Object.CodecDecodeSelf(d) } case "pods": if r.TryDecodeAsNil() { if x.Pods != nil { x.Pods = nil } } else { if x.Pods == nil { x.Pods = new(PodsMetricSource) } x.Pods.CodecDecodeSelf(d) } case "resource": if r.TryDecodeAsNil() { if x.Resource != nil { x.Resource = nil } } else { if x.Resource == nil { x.Resource = new(ResourceMetricSource) } x.Resource.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *MetricSpec) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj8 int var yyb8 bool var yyhl8 bool = l >= 0 yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Type = "" } else { yyv9 := &x.Type yyv9.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Object != nil { x.Object = nil } } else { if x.Object == nil { x.Object = new(ObjectMetricSource) } x.Object.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Pods != nil { x.Pods = nil } } else { if x.Pods == nil { x.Pods = new(PodsMetricSource) } x.Pods.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Resource != nil { x.Resource = nil } } else { if x.Resource == nil { x.Resource = new(ResourceMetricSource) } x.Resource.CodecDecodeSelf(d) } for { yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj8-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *ObjectMetricSource) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) } else { yynn2 = 3 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy4 := &x.Target yy4.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("target")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy6 := &x.Target yy6.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym9 := z.EncBinary() _ = yym9 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metricName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy12 := &x.TargetValue yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(yy12) { } else if !yym13 && z.IsJSONHandle() { z.EncJSONMarshal(yy12) } else { z.EncFallback(yy12) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("targetValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy14 := &x.TargetValue yym15 := z.EncBinary() _ = yym15 if false { } else if z.HasExtensions() && z.EncExt(yy14) { } else if !yym15 && z.IsJSONHandle() { z.EncJSONMarshal(yy14) } else { z.EncFallback(yy14) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *ObjectMetricSource) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *ObjectMetricSource) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "target": if r.TryDecodeAsNil() { x.Target = CrossVersionObjectReference{} } else { yyv4 := &x.Target yyv4.CodecDecodeSelf(d) } case "metricName": if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv5 := &x.MetricName yym6 := z.DecBinary() _ = yym6 if false { } else { *((*string)(yyv5)) = r.DecodeString() } } case "targetValue": if r.TryDecodeAsNil() { x.TargetValue = pkg1_resource.Quantity{} } else { yyv7 := &x.TargetValue yym8 := z.DecBinary() _ = yym8 if false { } else if z.HasExtensions() && z.DecExt(yyv7) { } else if !yym8 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv7) } else { z.DecFallback(yyv7, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *ObjectMetricSource) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj9 int var yyb9 bool var yyhl9 bool = l >= 0 yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Target = CrossVersionObjectReference{} } else { yyv10 := &x.Target yyv10.CodecDecodeSelf(d) } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv11 := &x.MetricName yym12 := z.DecBinary() _ = yym12 if false { } else { *((*string)(yyv11)) = r.DecodeString() } } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.TargetValue = pkg1_resource.Quantity{} } else { yyv13 := &x.TargetValue yym14 := z.DecBinary() _ = yym14 if false { } else if z.HasExtensions() && z.DecExt(yyv13) { } else if !yym14 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv13) } else { z.DecFallback(yyv13, false) } } for { yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *PodsMetricSource) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [2]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(2) } else { yynn2 = 2 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym4 := z.EncBinary() _ = yym4 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metricName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy7 := &x.TargetAverageValue yym8 := z.EncBinary() _ = yym8 if false { } else if z.HasExtensions() && z.EncExt(yy7) { } else if !yym8 && z.IsJSONHandle() { z.EncJSONMarshal(yy7) } else { z.EncFallback(yy7) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("targetAverageValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy9 := &x.TargetAverageValue yym10 := z.EncBinary() _ = yym10 if false { } else if z.HasExtensions() && z.EncExt(yy9) { } else if !yym10 && z.IsJSONHandle() { z.EncJSONMarshal(yy9) } else { z.EncFallback(yy9) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *PodsMetricSource) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *PodsMetricSource) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "metricName": if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv4 := &x.MetricName yym5 := z.DecBinary() _ = yym5 if false { } else { *((*string)(yyv4)) = r.DecodeString() } } case "targetAverageValue": if r.TryDecodeAsNil() { x.TargetAverageValue = pkg1_resource.Quantity{} } else { yyv6 := &x.TargetAverageValue yym7 := z.DecBinary() _ = yym7 if false { } else if z.HasExtensions() && z.DecExt(yyv6) { } else if !yym7 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv6) } else { z.DecFallback(yyv6, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *PodsMetricSource) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj8 int var yyb8 bool var yyhl8 bool = l >= 0 yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv9 := &x.MetricName yym10 := z.DecBinary() _ = yym10 if false { } else { *((*string)(yyv9)) = r.DecodeString() } } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.TargetAverageValue = pkg1_resource.Quantity{} } else { yyv11 := &x.TargetAverageValue yym12 := z.DecBinary() _ = yym12 if false { } else if z.HasExtensions() && z.DecExt(yyv11) { } else if !yym12 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv11) } else { z.DecFallback(yyv11, false) } } for { yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj8-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *ResourceMetricSource) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.TargetAverageUtilization != nil yyq2[2] = x.TargetAverageValue != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) } else { yynn2 = 1 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yysf4 := &x.Name yysf4.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("name")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yysf5 := &x.Name yysf5.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.TargetAverageUtilization == nil { r.EncodeNil() } else { yy7 := *x.TargetAverageUtilization yym8 := z.EncBinary() _ = yym8 if false { } else { r.EncodeInt(int64(yy7)) } } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("targetAverageUtilization")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.TargetAverageUtilization == nil { r.EncodeNil() } else { yy9 := *x.TargetAverageUtilization yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeInt(int64(yy9)) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { if x.TargetAverageValue == nil { r.EncodeNil() } else { yym12 := z.EncBinary() _ = yym12 if false { } else if z.HasExtensions() && z.EncExt(x.TargetAverageValue) { } else if !yym12 && z.IsJSONHandle() { z.EncJSONMarshal(x.TargetAverageValue) } else { z.EncFallback(x.TargetAverageValue) } } } else { r.EncodeNil() } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("targetAverageValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.TargetAverageValue == nil { r.EncodeNil() } else { yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(x.TargetAverageValue) { } else if !yym13 && z.IsJSONHandle() { z.EncJSONMarshal(x.TargetAverageValue) } else { z.EncFallback(x.TargetAverageValue) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *ResourceMetricSource) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *ResourceMetricSource) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "name": if r.TryDecodeAsNil() { x.Name = "" } else { yyv4 := &x.Name yyv4.CodecDecodeSelf(d) } case "targetAverageUtilization": if r.TryDecodeAsNil() { if x.TargetAverageUtilization != nil { x.TargetAverageUtilization = nil } } else { if x.TargetAverageUtilization == nil { x.TargetAverageUtilization = new(int32) } yym6 := z.DecBinary() _ = yym6 if false { } else { *((*int32)(x.TargetAverageUtilization)) = int32(r.DecodeInt(32)) } } case "targetAverageValue": if r.TryDecodeAsNil() { if x.TargetAverageValue != nil { x.TargetAverageValue = nil } } else { if x.TargetAverageValue == nil { x.TargetAverageValue = new(pkg1_resource.Quantity) } yym8 := z.DecBinary() _ = yym8 if false { } else if z.HasExtensions() && z.DecExt(x.TargetAverageValue) { } else if !yym8 && z.IsJSONHandle() { z.DecJSONUnmarshal(x.TargetAverageValue) } else { z.DecFallback(x.TargetAverageValue, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *ResourceMetricSource) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj9 int var yyb9 bool var yyhl9 bool = l >= 0 yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Name = "" } else { yyv10 := &x.Name yyv10.CodecDecodeSelf(d) } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.TargetAverageUtilization != nil { x.TargetAverageUtilization = nil } } else { if x.TargetAverageUtilization == nil { x.TargetAverageUtilization = new(int32) } yym12 := z.DecBinary() _ = yym12 if false { } else { *((*int32)(x.TargetAverageUtilization)) = int32(r.DecodeInt(32)) } } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.TargetAverageValue != nil { x.TargetAverageValue = nil } } else { if x.TargetAverageValue == nil { x.TargetAverageValue = new(pkg1_resource.Quantity) } yym14 := z.DecBinary() _ = yym14 if false { } else if z.HasExtensions() && z.DecExt(x.TargetAverageValue) { } else if !yym14 && z.IsJSONHandle() { z.DecJSONUnmarshal(x.TargetAverageValue) } else { z.DecFallback(x.TargetAverageValue, false) } } for { yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *HorizontalPodAutoscalerStatus) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [5]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = x.ObservedGeneration != nil yyq2[1] = x.LastScaleTime != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(5) } else { yynn2 = 3 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[0] { if x.ObservedGeneration == nil { r.EncodeNil() } else { yy4 := *x.ObservedGeneration yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeInt(int64(yy4)) } } } else { r.EncodeNil() } } else { if yyq2[0] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("observedGeneration")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.ObservedGeneration == nil { r.EncodeNil() } else { yy6 := *x.ObservedGeneration yym7 := z.EncBinary() _ = yym7 if false { } else { r.EncodeInt(int64(yy6)) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.LastScaleTime == nil { r.EncodeNil() } else { yym9 := z.EncBinary() _ = yym9 if false { } else if z.HasExtensions() && z.EncExt(x.LastScaleTime) { } else if yym9 { z.EncBinaryMarshal(x.LastScaleTime) } else if !yym9 && z.IsJSONHandle() { z.EncJSONMarshal(x.LastScaleTime) } else { z.EncFallback(x.LastScaleTime) } } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("lastScaleTime")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.LastScaleTime == nil { r.EncodeNil() } else { yym10 := z.EncBinary() _ = yym10 if false { } else if z.HasExtensions() && z.EncExt(x.LastScaleTime) { } else if yym10 { z.EncBinaryMarshal(x.LastScaleTime) } else if !yym10 && z.IsJSONHandle() { z.EncJSONMarshal(x.LastScaleTime) } else { z.EncFallback(x.LastScaleTime) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym12 := z.EncBinary() _ = yym12 if false { } else { r.EncodeInt(int64(x.CurrentReplicas)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym13 := z.EncBinary() _ = yym13 if false { } else { r.EncodeInt(int64(x.CurrentReplicas)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym15 := z.EncBinary() _ = yym15 if false { } else { r.EncodeInt(int64(x.DesiredReplicas)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("desiredReplicas")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym16 := z.EncBinary() _ = yym16 if false { } else { r.EncodeInt(int64(x.DesiredReplicas)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if x.CurrentMetrics == nil { r.EncodeNil() } else { yym18 := z.EncBinary() _ = yym18 if false { } else { h.encSliceMetricStatus(([]MetricStatus)(x.CurrentMetrics), e) } } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentMetrics")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.CurrentMetrics == nil { r.EncodeNil() } else { yym19 := z.EncBinary() _ = yym19 if false { } else { h.encSliceMetricStatus(([]MetricStatus)(x.CurrentMetrics), e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *HorizontalPodAutoscalerStatus) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *HorizontalPodAutoscalerStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "observedGeneration": if r.TryDecodeAsNil() { if x.ObservedGeneration != nil { x.ObservedGeneration = nil } } else { if x.ObservedGeneration == nil { x.ObservedGeneration = new(int64) } yym5 := z.DecBinary() _ = yym5 if false { } else { *((*int64)(x.ObservedGeneration)) = int64(r.DecodeInt(64)) } } case "lastScaleTime": if r.TryDecodeAsNil() { if x.LastScaleTime != nil { x.LastScaleTime = nil } } else { if x.LastScaleTime == nil { x.LastScaleTime = new(pkg3_v1.Time) } yym7 := z.DecBinary() _ = yym7 if false { } else if z.HasExtensions() && z.DecExt(x.LastScaleTime) { } else if yym7 { z.DecBinaryUnmarshal(x.LastScaleTime) } else if !yym7 && z.IsJSONHandle() { z.DecJSONUnmarshal(x.LastScaleTime) } else { z.DecFallback(x.LastScaleTime, false) } } case "currentReplicas": if r.TryDecodeAsNil() { x.CurrentReplicas = 0 } else { yyv8 := &x.CurrentReplicas yym9 := z.DecBinary() _ = yym9 if false { } else { *((*int32)(yyv8)) = int32(r.DecodeInt(32)) } } case "desiredReplicas": if r.TryDecodeAsNil() { x.DesiredReplicas = 0 } else { yyv10 := &x.DesiredReplicas yym11 := z.DecBinary() _ = yym11 if false { } else { *((*int32)(yyv10)) = int32(r.DecodeInt(32)) } } case "currentMetrics": if r.TryDecodeAsNil() { x.CurrentMetrics = nil } else { yyv12 := &x.CurrentMetrics yym13 := z.DecBinary() _ = yym13 if false { } else { h.decSliceMetricStatus((*[]MetricStatus)(yyv12), d) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *HorizontalPodAutoscalerStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj14 int var yyb14 bool var yyhl14 bool = l >= 0 yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.ObservedGeneration != nil { x.ObservedGeneration = nil } } else { if x.ObservedGeneration == nil { x.ObservedGeneration = new(int64) } yym16 := z.DecBinary() _ = yym16 if false { } else { *((*int64)(x.ObservedGeneration)) = int64(r.DecodeInt(64)) } } yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.LastScaleTime != nil { x.LastScaleTime = nil } } else { if x.LastScaleTime == nil { x.LastScaleTime = new(pkg3_v1.Time) } yym18 := z.DecBinary() _ = yym18 if false { } else if z.HasExtensions() && z.DecExt(x.LastScaleTime) { } else if yym18 { z.DecBinaryUnmarshal(x.LastScaleTime) } else if !yym18 && z.IsJSONHandle() { z.DecJSONUnmarshal(x.LastScaleTime) } else { z.DecFallback(x.LastScaleTime, false) } } yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.CurrentReplicas = 0 } else { yyv19 := &x.CurrentReplicas yym20 := z.DecBinary() _ = yym20 if false { } else { *((*int32)(yyv19)) = int32(r.DecodeInt(32)) } } yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.DesiredReplicas = 0 } else { yyv21 := &x.DesiredReplicas yym22 := z.DecBinary() _ = yym22 if false { } else { *((*int32)(yyv21)) = int32(r.DecodeInt(32)) } } yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.CurrentMetrics = nil } else { yyv23 := &x.CurrentMetrics yym24 := z.DecBinary() _ = yym24 if false { } else { h.decSliceMetricStatus((*[]MetricStatus)(yyv23), d) } } for { yyj14++ if yyhl14 { yyb14 = yyj14 > l } else { yyb14 = r.CheckBreak() } if yyb14 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj14-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *MetricStatus) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [4]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.Object != nil yyq2[2] = x.Pods != nil yyq2[3] = x.Resource != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(4) } else { yynn2 = 1 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) x.Type.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("type")) z.EncSendContainerState(codecSelfer_containerMapValue1234) x.Type.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.Object == nil { r.EncodeNil() } else { x.Object.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("object")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Object == nil { r.EncodeNil() } else { x.Object.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { if x.Pods == nil { r.EncodeNil() } else { x.Pods.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("pods")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Pods == nil { r.EncodeNil() } else { x.Pods.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[3] { if x.Resource == nil { r.EncodeNil() } else { x.Resource.CodecEncodeSelf(e) } } else { r.EncodeNil() } } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("resource")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Resource == nil { r.EncodeNil() } else { x.Resource.CodecEncodeSelf(e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *MetricStatus) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *MetricStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "type": if r.TryDecodeAsNil() { x.Type = "" } else { yyv4 := &x.Type yyv4.CodecDecodeSelf(d) } case "object": if r.TryDecodeAsNil() { if x.Object != nil { x.Object = nil } } else { if x.Object == nil { x.Object = new(ObjectMetricStatus) } x.Object.CodecDecodeSelf(d) } case "pods": if r.TryDecodeAsNil() { if x.Pods != nil { x.Pods = nil } } else { if x.Pods == nil { x.Pods = new(PodsMetricStatus) } x.Pods.CodecDecodeSelf(d) } case "resource": if r.TryDecodeAsNil() { if x.Resource != nil { x.Resource = nil } } else { if x.Resource == nil { x.Resource = new(ResourceMetricStatus) } x.Resource.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *MetricStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj8 int var yyb8 bool var yyhl8 bool = l >= 0 yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Type = "" } else { yyv9 := &x.Type yyv9.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Object != nil { x.Object = nil } } else { if x.Object == nil { x.Object = new(ObjectMetricStatus) } x.Object.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Pods != nil { x.Pods = nil } } else { if x.Pods == nil { x.Pods = new(PodsMetricStatus) } x.Pods.CodecDecodeSelf(d) } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.Resource != nil { x.Resource = nil } } else { if x.Resource == nil { x.Resource = new(ResourceMetricStatus) } x.Resource.CodecDecodeSelf(d) } for { yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj8-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *ObjectMetricStatus) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) } else { yynn2 = 3 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy4 := &x.Target yy4.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("target")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy6 := &x.Target yy6.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym9 := z.EncBinary() _ = yym9 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metricName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy12 := &x.CurrentValue yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(yy12) { } else if !yym13 && z.IsJSONHandle() { z.EncJSONMarshal(yy12) } else { z.EncFallback(yy12) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy14 := &x.CurrentValue yym15 := z.EncBinary() _ = yym15 if false { } else if z.HasExtensions() && z.EncExt(yy14) { } else if !yym15 && z.IsJSONHandle() { z.EncJSONMarshal(yy14) } else { z.EncFallback(yy14) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *ObjectMetricStatus) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *ObjectMetricStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "target": if r.TryDecodeAsNil() { x.Target = CrossVersionObjectReference{} } else { yyv4 := &x.Target yyv4.CodecDecodeSelf(d) } case "metricName": if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv5 := &x.MetricName yym6 := z.DecBinary() _ = yym6 if false { } else { *((*string)(yyv5)) = r.DecodeString() } } case "currentValue": if r.TryDecodeAsNil() { x.CurrentValue = pkg1_resource.Quantity{} } else { yyv7 := &x.CurrentValue yym8 := z.DecBinary() _ = yym8 if false { } else if z.HasExtensions() && z.DecExt(yyv7) { } else if !yym8 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv7) } else { z.DecFallback(yyv7, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *ObjectMetricStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj9 int var yyb9 bool var yyhl9 bool = l >= 0 yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Target = CrossVersionObjectReference{} } else { yyv10 := &x.Target yyv10.CodecDecodeSelf(d) } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv11 := &x.MetricName yym12 := z.DecBinary() _ = yym12 if false { } else { *((*string)(yyv11)) = r.DecodeString() } } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.CurrentValue = pkg1_resource.Quantity{} } else { yyv13 := &x.CurrentValue yym14 := z.DecBinary() _ = yym14 if false { } else if z.HasExtensions() && z.DecExt(yyv13) { } else if !yym14 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv13) } else { z.DecFallback(yyv13, false) } } for { yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *PodsMetricStatus) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [2]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(2) } else { yynn2 = 2 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yym4 := z.EncBinary() _ = yym4 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metricName")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.MetricName)) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy7 := &x.CurrentAverageValue yym8 := z.EncBinary() _ = yym8 if false { } else if z.HasExtensions() && z.EncExt(yy7) { } else if !yym8 && z.IsJSONHandle() { z.EncJSONMarshal(yy7) } else { z.EncFallback(yy7) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentAverageValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy9 := &x.CurrentAverageValue yym10 := z.EncBinary() _ = yym10 if false { } else if z.HasExtensions() && z.EncExt(yy9) { } else if !yym10 && z.IsJSONHandle() { z.EncJSONMarshal(yy9) } else { z.EncFallback(yy9) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *PodsMetricStatus) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *PodsMetricStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "metricName": if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv4 := &x.MetricName yym5 := z.DecBinary() _ = yym5 if false { } else { *((*string)(yyv4)) = r.DecodeString() } } case "currentAverageValue": if r.TryDecodeAsNil() { x.CurrentAverageValue = pkg1_resource.Quantity{} } else { yyv6 := &x.CurrentAverageValue yym7 := z.DecBinary() _ = yym7 if false { } else if z.HasExtensions() && z.DecExt(yyv6) { } else if !yym7 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv6) } else { z.DecFallback(yyv6, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *PodsMetricStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj8 int var yyb8 bool var yyhl8 bool = l >= 0 yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.MetricName = "" } else { yyv9 := &x.MetricName yym10 := z.DecBinary() _ = yym10 if false { } else { *((*string)(yyv9)) = r.DecodeString() } } yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.CurrentAverageValue = pkg1_resource.Quantity{} } else { yyv11 := &x.CurrentAverageValue yym12 := z.DecBinary() _ = yym12 if false { } else if z.HasExtensions() && z.DecExt(yyv11) { } else if !yym12 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv11) } else { z.DecFallback(yyv11, false) } } for { yyj8++ if yyhl8 { yyb8 = yyj8 > l } else { yyb8 = r.CheckBreak() } if yyb8 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj8-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *ResourceMetricStatus) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [3]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[1] = x.CurrentAverageUtilization != nil var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(3) } else { yynn2 = 2 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yysf4 := &x.Name yysf4.CodecEncodeSelf(e) } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("name")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yysf5 := &x.Name yysf5.CodecEncodeSelf(e) } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { if x.CurrentAverageUtilization == nil { r.EncodeNil() } else { yy7 := *x.CurrentAverageUtilization yym8 := z.EncBinary() _ = yym8 if false { } else { r.EncodeInt(int64(yy7)) } } } else { r.EncodeNil() } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentAverageUtilization")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.CurrentAverageUtilization == nil { r.EncodeNil() } else { yy9 := *x.CurrentAverageUtilization yym10 := z.EncBinary() _ = yym10 if false { } else { r.EncodeInt(int64(yy9)) } } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy12 := &x.CurrentAverageValue yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(yy12) { } else if !yym13 && z.IsJSONHandle() { z.EncJSONMarshal(yy12) } else { z.EncFallback(yy12) } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("currentAverageValue")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy14 := &x.CurrentAverageValue yym15 := z.EncBinary() _ = yym15 if false { } else if z.HasExtensions() && z.EncExt(yy14) { } else if !yym15 && z.IsJSONHandle() { z.EncJSONMarshal(yy14) } else { z.EncFallback(yy14) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *ResourceMetricStatus) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *ResourceMetricStatus) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "name": if r.TryDecodeAsNil() { x.Name = "" } else { yyv4 := &x.Name yyv4.CodecDecodeSelf(d) } case "currentAverageUtilization": if r.TryDecodeAsNil() { if x.CurrentAverageUtilization != nil { x.CurrentAverageUtilization = nil } } else { if x.CurrentAverageUtilization == nil { x.CurrentAverageUtilization = new(int32) } yym6 := z.DecBinary() _ = yym6 if false { } else { *((*int32)(x.CurrentAverageUtilization)) = int32(r.DecodeInt(32)) } } case "currentAverageValue": if r.TryDecodeAsNil() { x.CurrentAverageValue = pkg1_resource.Quantity{} } else { yyv7 := &x.CurrentAverageValue yym8 := z.DecBinary() _ = yym8 if false { } else if z.HasExtensions() && z.DecExt(yyv7) { } else if !yym8 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv7) } else { z.DecFallback(yyv7, false) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *ResourceMetricStatus) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj9 int var yyb9 bool var yyhl9 bool = l >= 0 yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Name = "" } else { yyv10 := &x.Name yyv10.CodecDecodeSelf(d) } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { if x.CurrentAverageUtilization != nil { x.CurrentAverageUtilization = nil } } else { if x.CurrentAverageUtilization == nil { x.CurrentAverageUtilization = new(int32) } yym12 := z.DecBinary() _ = yym12 if false { } else { *((*int32)(x.CurrentAverageUtilization)) = int32(r.DecodeInt(32)) } } yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.CurrentAverageValue = pkg1_resource.Quantity{} } else { yyv13 := &x.CurrentAverageValue yym14 := z.DecBinary() _ = yym14 if false { } else if z.HasExtensions() && z.DecExt(yyv13) { } else if !yym14 && z.IsJSONHandle() { z.DecJSONUnmarshal(yyv13) } else { z.DecFallback(yyv13, false) } } for { yyj9++ if yyhl9 { yyb9 = yyj9 > l } else { yyb9 = r.CheckBreak() } if yyb9 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj9-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *HorizontalPodAutoscaler) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [5]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = x.Kind != "" yyq2[1] = x.APIVersion != "" yyq2[2] = true yyq2[3] = true yyq2[4] = true var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(5) } else { yynn2 = 0 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[0] { yym4 := z.EncBinary() _ = yym4 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { if yyq2[0] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { yym7 := z.EncBinary() _ = yym7 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { yy10 := &x.ObjectMeta yym11 := z.EncBinary() _ = yym11 if false { } else if z.HasExtensions() && z.EncExt(yy10) { } else { z.EncFallback(yy10) } } else { r.EncodeNil() } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metadata")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy12 := &x.ObjectMeta yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(yy12) { } else { z.EncFallback(yy12) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[3] { yy15 := &x.Spec yy15.CodecEncodeSelf(e) } else { r.EncodeNil() } } else { if yyq2[3] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("spec")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy17 := &x.Spec yy17.CodecEncodeSelf(e) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[4] { yy20 := &x.Status yy20.CodecEncodeSelf(e) } else { r.EncodeNil() } } else { if yyq2[4] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("status")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy22 := &x.Status yy22.CodecEncodeSelf(e) } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *HorizontalPodAutoscaler) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *HorizontalPodAutoscaler) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "kind": if r.TryDecodeAsNil() { x.Kind = "" } else { yyv4 := &x.Kind yym5 := z.DecBinary() _ = yym5 if false { } else { *((*string)(yyv4)) = r.DecodeString() } } case "apiVersion": if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv6 := &x.APIVersion yym7 := z.DecBinary() _ = yym7 if false { } else { *((*string)(yyv6)) = r.DecodeString() } } case "metadata": if r.TryDecodeAsNil() { x.ObjectMeta = pkg3_v1.ObjectMeta{} } else { yyv8 := &x.ObjectMeta yym9 := z.DecBinary() _ = yym9 if false { } else if z.HasExtensions() && z.DecExt(yyv8) { } else { z.DecFallback(yyv8, false) } } case "spec": if r.TryDecodeAsNil() { x.Spec = HorizontalPodAutoscalerSpec{} } else { yyv10 := &x.Spec yyv10.CodecDecodeSelf(d) } case "status": if r.TryDecodeAsNil() { x.Status = HorizontalPodAutoscalerStatus{} } else { yyv11 := &x.Status yyv11.CodecDecodeSelf(d) } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *HorizontalPodAutoscaler) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj12 int var yyb12 bool var yyhl12 bool = l >= 0 yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Kind = "" } else { yyv13 := &x.Kind yym14 := z.DecBinary() _ = yym14 if false { } else { *((*string)(yyv13)) = r.DecodeString() } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv15 := &x.APIVersion yym16 := z.DecBinary() _ = yym16 if false { } else { *((*string)(yyv15)) = r.DecodeString() } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.ObjectMeta = pkg3_v1.ObjectMeta{} } else { yyv17 := &x.ObjectMeta yym18 := z.DecBinary() _ = yym18 if false { } else if z.HasExtensions() && z.DecExt(yyv17) { } else { z.DecFallback(yyv17, false) } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Spec = HorizontalPodAutoscalerSpec{} } else { yyv19 := &x.Spec yyv19.CodecDecodeSelf(d) } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Status = HorizontalPodAutoscalerStatus{} } else { yyv20 := &x.Status yyv20.CodecDecodeSelf(d) } for { yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj12-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x *HorizontalPodAutoscalerList) CodecEncodeSelf(e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r if x == nil { r.EncodeNil() } else { yym1 := z.EncBinary() _ = yym1 if false { } else if z.HasExtensions() && z.EncExt(x) { } else { yysep2 := !z.EncBinary() yy2arr2 := z.EncBasicHandle().StructToArray var yyq2 [4]bool _, _, _ = yysep2, yyq2, yy2arr2 const yyr2 bool = false yyq2[0] = x.Kind != "" yyq2[1] = x.APIVersion != "" yyq2[2] = true var yynn2 int if yyr2 || yy2arr2 { r.EncodeArrayStart(4) } else { yynn2 = 1 for _, b := range yyq2 { if b { yynn2++ } } r.EncodeMapStart(yynn2) yynn2 = 0 } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[0] { yym4 := z.EncBinary() _ = yym4 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { if yyq2[0] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("kind")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym5 := z.EncBinary() _ = yym5 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.Kind)) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[1] { yym7 := z.EncBinary() _ = yym7 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } else { r.EncodeString(codecSelferC_UTF81234, "") } } else { if yyq2[1] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("apiVersion")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yym8 := z.EncBinary() _ = yym8 if false { } else { r.EncodeString(codecSelferC_UTF81234, string(x.APIVersion)) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if yyq2[2] { yy10 := &x.ListMeta yym11 := z.EncBinary() _ = yym11 if false { } else if z.HasExtensions() && z.EncExt(yy10) { } else { z.EncFallback(yy10) } } else { r.EncodeNil() } } else { if yyq2[2] { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("metadata")) z.EncSendContainerState(codecSelfer_containerMapValue1234) yy12 := &x.ListMeta yym13 := z.EncBinary() _ = yym13 if false { } else if z.HasExtensions() && z.EncExt(yy12) { } else { z.EncFallback(yy12) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayElem1234) if x.Items == nil { r.EncodeNil() } else { yym15 := z.EncBinary() _ = yym15 if false { } else { h.encSliceHorizontalPodAutoscaler(([]HorizontalPodAutoscaler)(x.Items), e) } } } else { z.EncSendContainerState(codecSelfer_containerMapKey1234) r.EncodeString(codecSelferC_UTF81234, string("items")) z.EncSendContainerState(codecSelfer_containerMapValue1234) if x.Items == nil { r.EncodeNil() } else { yym16 := z.EncBinary() _ = yym16 if false { } else { h.encSliceHorizontalPodAutoscaler(([]HorizontalPodAutoscaler)(x.Items), e) } } } if yyr2 || yy2arr2 { z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } else { z.EncSendContainerState(codecSelfer_containerMapEnd1234) } } } } func (x *HorizontalPodAutoscalerList) CodecDecodeSelf(d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yym1 := z.DecBinary() _ = yym1 if false { } else if z.HasExtensions() && z.DecExt(x) { } else { yyct2 := r.ContainerType() if yyct2 == codecSelferValueTypeMap1234 { yyl2 := r.ReadMapStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerMapEnd1234) } else { x.codecDecodeSelfFromMap(yyl2, d) } } else if yyct2 == codecSelferValueTypeArray1234 { yyl2 := r.ReadArrayStart() if yyl2 == 0 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } else { x.codecDecodeSelfFromArray(yyl2, d) } } else { panic(codecSelferOnlyMapOrArrayEncodeToStructErr1234) } } } func (x *HorizontalPodAutoscalerList) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yys3Slc = z.DecScratchBuffer() // default slice to decode into _ = yys3Slc var yyhl3 bool = l >= 0 for yyj3 := 0; ; yyj3++ { if yyhl3 { if yyj3 >= l { break } } else { if r.CheckBreak() { break } } z.DecSendContainerState(codecSelfer_containerMapKey1234) yys3Slc = r.DecodeBytes(yys3Slc, true, true) yys3 := string(yys3Slc) z.DecSendContainerState(codecSelfer_containerMapValue1234) switch yys3 { case "kind": if r.TryDecodeAsNil() { x.Kind = "" } else { yyv4 := &x.Kind yym5 := z.DecBinary() _ = yym5 if false { } else { *((*string)(yyv4)) = r.DecodeString() } } case "apiVersion": if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv6 := &x.APIVersion yym7 := z.DecBinary() _ = yym7 if false { } else { *((*string)(yyv6)) = r.DecodeString() } } case "metadata": if r.TryDecodeAsNil() { x.ListMeta = pkg3_v1.ListMeta{} } else { yyv8 := &x.ListMeta yym9 := z.DecBinary() _ = yym9 if false { } else if z.HasExtensions() && z.DecExt(yyv8) { } else { z.DecFallback(yyv8, false) } } case "items": if r.TryDecodeAsNil() { x.Items = nil } else { yyv10 := &x.Items yym11 := z.DecBinary() _ = yym11 if false { } else { h.decSliceHorizontalPodAutoscaler((*[]HorizontalPodAutoscaler)(yyv10), d) } } default: z.DecStructFieldNotFound(-1, yys3) } // end switch yys3 } // end for yyj3 z.DecSendContainerState(codecSelfer_containerMapEnd1234) } func (x *HorizontalPodAutoscalerList) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r var yyj12 int var yyb12 bool var yyhl12 bool = l >= 0 yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Kind = "" } else { yyv13 := &x.Kind yym14 := z.DecBinary() _ = yym14 if false { } else { *((*string)(yyv13)) = r.DecodeString() } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.APIVersion = "" } else { yyv15 := &x.APIVersion yym16 := z.DecBinary() _ = yym16 if false { } else { *((*string)(yyv15)) = r.DecodeString() } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.ListMeta = pkg3_v1.ListMeta{} } else { yyv17 := &x.ListMeta yym18 := z.DecBinary() _ = yym18 if false { } else if z.HasExtensions() && z.DecExt(yyv17) { } else { z.DecFallback(yyv17, false) } } yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { z.DecSendContainerState(codecSelfer_containerArrayEnd1234) return } z.DecSendContainerState(codecSelfer_containerArrayElem1234) if r.TryDecodeAsNil() { x.Items = nil } else { yyv19 := &x.Items yym20 := z.DecBinary() _ = yym20 if false { } else { h.decSliceHorizontalPodAutoscaler((*[]HorizontalPodAutoscaler)(yyv19), d) } } for { yyj12++ if yyhl12 { yyb12 = yyj12 > l } else { yyb12 = r.CheckBreak() } if yyb12 { break } z.DecSendContainerState(codecSelfer_containerArrayElem1234) z.DecStructFieldNotFound(yyj12-1, "") } z.DecSendContainerState(codecSelfer_containerArrayEnd1234) } func (x codecSelfer1234) encSliceMetricSpec(v []MetricSpec, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r r.EncodeArrayStart(len(v)) for _, yyv1 := range v { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } func (x codecSelfer1234) decSliceMetricSpec(v *[]MetricSpec, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyl1 == 0 { if yyv1 == nil { yyv1 = []MetricSpec{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else if yyl1 > 0 { var yyrr1, yyrl1 int var yyrt1 bool _, _ = yyrl1, yyrt1 yyrr1 = yyl1 // len(yyv1) if yyl1 > cap(yyv1) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]MetricSpec, yyrl1) } } else { yyv1 = make([]MetricSpec, yyrl1) } yyc1 = true yyrr1 = len(yyv1) if yyrg1 { copy(yyv1, yyv21) } } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } yyj1 := 0 for ; yyj1 < yyrr1; yyj1++ { yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = MetricSpec{} } else { yyv2 := &yyv1[yyj1] yyv2.CodecDecodeSelf(d) } } if yyrt1 { for ; yyj1 < yyl1; yyj1++ { yyv1 = append(yyv1, MetricSpec{}) yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = MetricSpec{} } else { yyv3 := &yyv1[yyj1] yyv3.CodecDecodeSelf(d) } } } } else { yyj1 := 0 for ; !r.CheckBreak(); yyj1++ { if yyj1 >= len(yyv1) { yyv1 = append(yyv1, MetricSpec{}) // var yyz1 MetricSpec yyc1 = true } yyh1.ElemContainerState(yyj1) if yyj1 < len(yyv1) { if r.TryDecodeAsNil() { yyv1[yyj1] = MetricSpec{} } else { yyv4 := &yyv1[yyj1] yyv4.CodecDecodeSelf(d) } } else { z.DecSwallow() } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = []MetricSpec{} yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer1234) encSliceMetricStatus(v []MetricStatus, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r r.EncodeArrayStart(len(v)) for _, yyv1 := range v { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } func (x codecSelfer1234) decSliceMetricStatus(v *[]MetricStatus, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyl1 == 0 { if yyv1 == nil { yyv1 = []MetricStatus{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else if yyl1 > 0 { var yyrr1, yyrl1 int var yyrt1 bool _, _ = yyrl1, yyrt1 yyrr1 = yyl1 // len(yyv1) if yyl1 > cap(yyv1) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 40) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]MetricStatus, yyrl1) } } else { yyv1 = make([]MetricStatus, yyrl1) } yyc1 = true yyrr1 = len(yyv1) if yyrg1 { copy(yyv1, yyv21) } } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } yyj1 := 0 for ; yyj1 < yyrr1; yyj1++ { yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = MetricStatus{} } else { yyv2 := &yyv1[yyj1] yyv2.CodecDecodeSelf(d) } } if yyrt1 { for ; yyj1 < yyl1; yyj1++ { yyv1 = append(yyv1, MetricStatus{}) yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = MetricStatus{} } else { yyv3 := &yyv1[yyj1] yyv3.CodecDecodeSelf(d) } } } } else { yyj1 := 0 for ; !r.CheckBreak(); yyj1++ { if yyj1 >= len(yyv1) { yyv1 = append(yyv1, MetricStatus{}) // var yyz1 MetricStatus yyc1 = true } yyh1.ElemContainerState(yyj1) if yyj1 < len(yyv1) { if r.TryDecodeAsNil() { yyv1[yyj1] = MetricStatus{} } else { yyv4 := &yyv1[yyj1] yyv4.CodecDecodeSelf(d) } } else { z.DecSwallow() } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = []MetricStatus{} yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } } func (x codecSelfer1234) encSliceHorizontalPodAutoscaler(v []HorizontalPodAutoscaler, e *codec1978.Encoder) { var h codecSelfer1234 z, r := codec1978.GenHelperEncoder(e) _, _, _ = h, z, r r.EncodeArrayStart(len(v)) for _, yyv1 := range v { z.EncSendContainerState(codecSelfer_containerArrayElem1234) yy2 := &yyv1 yy2.CodecEncodeSelf(e) } z.EncSendContainerState(codecSelfer_containerArrayEnd1234) } func (x codecSelfer1234) decSliceHorizontalPodAutoscaler(v *[]HorizontalPodAutoscaler, d *codec1978.Decoder) { var h codecSelfer1234 z, r := codec1978.GenHelperDecoder(d) _, _, _ = h, z, r yyv1 := *v yyh1, yyl1 := z.DecSliceHelperStart() var yyc1 bool _ = yyc1 if yyl1 == 0 { if yyv1 == nil { yyv1 = []HorizontalPodAutoscaler{} yyc1 = true } else if len(yyv1) != 0 { yyv1 = yyv1[:0] yyc1 = true } } else if yyl1 > 0 { var yyrr1, yyrl1 int var yyrt1 bool _, _ = yyrl1, yyrt1 yyrr1 = yyl1 // len(yyv1) if yyl1 > cap(yyv1) { yyrg1 := len(yyv1) > 0 yyv21 := yyv1 yyrl1, yyrt1 = z.DecInferLen(yyl1, z.DecBasicHandle().MaxInitLen, 392) if yyrt1 { if yyrl1 <= cap(yyv1) { yyv1 = yyv1[:yyrl1] } else { yyv1 = make([]HorizontalPodAutoscaler, yyrl1) } } else { yyv1 = make([]HorizontalPodAutoscaler, yyrl1) } yyc1 = true yyrr1 = len(yyv1) if yyrg1 { copy(yyv1, yyv21) } } else if yyl1 != len(yyv1) { yyv1 = yyv1[:yyl1] yyc1 = true } yyj1 := 0 for ; yyj1 < yyrr1; yyj1++ { yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = HorizontalPodAutoscaler{} } else { yyv2 := &yyv1[yyj1] yyv2.CodecDecodeSelf(d) } } if yyrt1 { for ; yyj1 < yyl1; yyj1++ { yyv1 = append(yyv1, HorizontalPodAutoscaler{}) yyh1.ElemContainerState(yyj1) if r.TryDecodeAsNil() { yyv1[yyj1] = HorizontalPodAutoscaler{} } else { yyv3 := &yyv1[yyj1] yyv3.CodecDecodeSelf(d) } } } } else { yyj1 := 0 for ; !r.CheckBreak(); yyj1++ { if yyj1 >= len(yyv1) { yyv1 = append(yyv1, HorizontalPodAutoscaler{}) // var yyz1 HorizontalPodAutoscaler yyc1 = true } yyh1.ElemContainerState(yyj1) if yyj1 < len(yyv1) { if r.TryDecodeAsNil() { yyv1[yyj1] = HorizontalPodAutoscaler{} } else { yyv4 := &yyv1[yyj1] yyv4.CodecDecodeSelf(d) } } else { z.DecSwallow() } } if yyj1 < len(yyv1) { yyv1 = yyv1[:yyj1] yyc1 = true } else if yyj1 == 0 && yyv1 == nil { yyv1 = []HorizontalPodAutoscaler{} yyc1 = true } } yyh1.End() if yyc1 { *v = yyv1 } }
init
poll.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::{ cell::{Cell, Ref, RefCell}, cmp::min, fs::File, i32, i64, marker::PhantomData, os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}, ptr::null_mut, slice, thread, time::Duration, }; use libc::{ c_int, epoll_create1, epoll_ctl, epoll_event, epoll_wait, EPOLLHUP, EPOLLIN, EPOLLOUT, EPOLLRDHUP, EPOLL_CLOEXEC, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD, }; use super::{errno_result, Result}; const POLL_CONTEXT_MAX_EVENTS: usize = 16; /// EpollEvents wraps raw epoll_events, it should only be used with EpollContext. pub struct EpollEvents(RefCell<[epoll_event; POLL_CONTEXT_MAX_EVENTS]>); impl EpollEvents { pub fn new() -> EpollEvents { EpollEvents(RefCell::new( [epoll_event { events: 0, u64: 0 }; POLL_CONTEXT_MAX_EVENTS], )) } } impl Default for EpollEvents { fn default() -> EpollEvents { Self::new() } } /// Trait for a token that can be associated with an `fd` in a `PollContext`. /// /// Simple enums that have no or primitive variant data data can use the `#[derive(PollToken)]` /// custom derive to implement this trait. See /// [poll_token_derive::poll_token](../poll_token_derive/fn.poll_token.html) for details. pub trait PollToken { /// Converts this token into a u64 that can be turned back into a token via `from_raw_token`. fn as_raw_token(&self) -> u64; /// Converts a raw token as returned from `as_raw_token` back into a token. /// /// It is invalid to give a raw token that was not returned via `as_raw_token` from the same /// `Self`. The implementation can expect that this will never happen as a result of its usage /// in `PollContext`. fn from_raw_token(data: u64) -> Self; } impl PollToken for usize { fn as_raw_token(&self) -> u64 { *self as u64 } fn from_raw_token(data: u64) -> Self { data as Self } } impl PollToken for u64 { fn as_raw_token(&self) -> u64 { *self as u64 } fn from_raw_token(data: u64) -> Self { data as Self } } impl PollToken for u32 { fn as_raw_token(&self) -> u64 { u64::from(*self) } fn from_raw_token(data: u64) -> Self { data as Self } } impl PollToken for u16 { fn as_raw_token(&self) -> u64 { u64::from(*self) } fn from_raw_token(data: u64) -> Self { data as Self } } impl PollToken for u8 { fn as_raw_token(&self) -> u64 { u64::from(*self) } fn from_raw_token(data: u64) -> Self { data as Self } } impl PollToken for () { fn as_raw_token(&self) -> u64 { 0 } fn from_raw_token(_data: u64) -> Self {} } /// An event returned by `PollContext::wait`. pub struct PollEvent<'a, T> { event: &'a epoll_event, token: PhantomData<T>, // Needed to satisfy usage of T } impl<'a, T: PollToken> PollEvent<'a, T> { /// Gets the token associated in `PollContext::add` with this event. pub fn token(&self) -> T { T::from_raw_token(self.event.u64) } /// True if the `fd` associated with this token in `PollContext::add` is readable. pub fn readable(&self) -> bool { self.event.events & (EPOLLIN as u32) != 0 } /// True if the `fd` associated with this token in `PollContext::add` is writable. pub fn writable(&self) -> bool { self.event.events & (EPOLLOUT as u32) != 0 } /// True if the `fd` associated with this token in `PollContext::add` has been hungup on. pub fn hungup(&self) -> bool { self.event.events & ((EPOLLHUP | EPOLLRDHUP) as u32) != 0 } } /// An iterator over some (sub)set of events returned by `PollContext::wait`. pub struct PollEventIter<'a, I, T> where I: Iterator<Item = &'a epoll_event>, { mask: u32, iter: I, tokens: PhantomData<[T]>, // Needed to satisfy usage of T } impl<'a, I, T> Iterator for PollEventIter<'a, I, T> where I: Iterator<Item = &'a epoll_event>, T: PollToken, { type Item = PollEvent<'a, T>; fn next(&mut self) -> Option<Self::Item> { let mask = self.mask; self.iter .find(|event| (event.events & mask) != 0) .map(|event| PollEvent { event, token: PhantomData, }) } } /// The list of event returned by `PollContext::wait`. pub struct PollEvents<'a, T> { count: usize, events: Ref<'a, [epoll_event; POLL_CONTEXT_MAX_EVENTS]>, tokens: PhantomData<[T]>, // Needed to satisfy usage of T } impl<'a, T: PollToken> PollEvents<'a, T> { /// Copies the events to an owned structure so the reference to this (and by extension /// `PollContext`) can be dropped. pub fn to_owned(&self) -> PollEventsOwned<T> { PollEventsOwned { count: self.count, events: RefCell::new(*self.events), tokens: PhantomData, } } /// Iterates over each event. pub fn iter(&self) -> PollEventIter<slice::Iter<epoll_event>, T> { PollEventIter { mask: 0xffff_ffff, iter: self.events[..self.count].iter(), tokens: PhantomData, } } /// Iterates over each readable event. pub fn iter_readable(&self) -> PollEventIter<slice::Iter<epoll_event>, T> { PollEventIter { mask: EPOLLIN as u32, iter: self.events[..self.count].iter(), tokens: PhantomData, } } /// Iterates over each writable event. pub fn iter_writable(&self) -> PollEventIter<slice::Iter<epoll_event>, T> { PollEventIter { mask: EPOLLOUT as u32, iter: self.events[..self.count].iter(), tokens: PhantomData, } } /// Iterates over each hungup event. pub fn iter_hungup(&self) -> PollEventIter<slice::Iter<epoll_event>, T> { PollEventIter { mask: (EPOLLHUP | EPOLLRDHUP) as u32, iter: self.events[..self.count].iter(), tokens: PhantomData, } } } impl<'a, T: PollToken> IntoIterator for &'a PollEvents<'_, T> { type Item = PollEvent<'a, T>; type IntoIter = PollEventIter<'a, slice::Iter<'a, epoll_event>, T>; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// A deep copy of the event records from `PollEvents`. pub struct PollEventsOwned<T> { count: usize, events: RefCell<[epoll_event; POLL_CONTEXT_MAX_EVENTS]>, tokens: PhantomData<T>, // Needed to satisfy usage of T } impl<T: PollToken> PollEventsOwned<T> { /// Takes a reference to the events so that they can be iterated via methods in `PollEvents`. pub fn as_ref(&self) -> PollEvents<T> { PollEvents { count: self.count, events: self.events.borrow(), tokens: PhantomData, } } } /// Watching events taken by PollContext. pub struct WatchingEvents(u32); impl WatchingEvents { /// Returns empty Events. #[inline(always)] pub fn empty() -> WatchingEvents { WatchingEvents(0) } /// Build Events from raw epoll events (defined in epoll_ctl(2)). #[inline(always)] pub fn new(raw: u32) -> WatchingEvents { WatchingEvents(raw) } /// Set read events. #[inline(always)] pub fn set_read(self) -> WatchingEvents { WatchingEvents(self.0 | EPOLLIN as u32) } /// Set write events. #[inline(always)] pub fn set_write(self) -> WatchingEvents { WatchingEvents(self.0 | EPOLLOUT as u32) } /// Get the underlying epoll events. pub fn get_raw(&self) -> u32 { self.0 } } /// EpollContext wraps linux epoll. It provides similar interface to PollContext. /// It is thread safe while PollContext is not. It requires user to pass in a reference of /// EpollEvents while PollContext does not. Always use PollContext if you don't need to access the /// same epoll from different threads. pub struct EpollContext<T> { epoll_ctx: File, // Needed to satisfy usage of T tokens: PhantomData<[T]>, } impl<T: PollToken> EpollContext<T> { /// Creates a new `EpollContext`. pub fn new() -> Result<EpollContext<T>> { // Safe because we check the return value. let epoll_fd = unsafe { epoll_create1(EPOLL_CLOEXEC) }; if epoll_fd < 0 { return errno_result(); } Ok(EpollContext { epoll_ctx: unsafe { File::from_raw_fd(epoll_fd) }, tokens: PhantomData, }) } /// Creates a new `EpollContext` and adds the slice of `fd` and `token` tuples to the new /// context. /// /// This is equivalent to calling `new` followed by `add_many`. If there is an error, this will /// return the error instead of the new context. pub fn build_with(fd_tokens: &[(&dyn AsRawFd, T)]) -> Result<EpollContext<T>> { let ctx = EpollContext::new()?; ctx.add_many(fd_tokens)?; Ok(ctx) } /// Adds the given slice of `fd` and `token` tuples to this context. /// /// This is equivalent to calling `add` with each `fd` and `token`. If there are any errors, /// this method will stop adding `fd`s and return the first error, leaving this context in a /// undefined state. pub fn add_many(&self, fd_tokens: &[(&dyn AsRawFd, T)]) -> Result<()> { for (fd, token) in fd_tokens { self.add(*fd, T::from_raw_token(token.as_raw_token()))?; } Ok(()) } /// Adds the given `fd` to this context and associates the given `token` with the `fd`'s /// readable events. /// /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different /// FD number) added to this context, events will not be reported by `wait` anymore. pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> { self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token) } /// Adds the given `fd` to this context, watching for the specified events and associates the /// given 'token' with those events. /// /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different /// FD number) added to this context, events will not be reported by `wait` anymore. pub fn add_fd_with_events( &self, fd: &dyn AsRawFd, events: WatchingEvents, token: T, ) -> Result<()> { let mut evt = epoll_event { events: events.get_raw(), u64: token.as_raw_token(), }; // Safe because we give a valid epoll FD and FD to watch, as well as a valid epoll_event // structure. Then we check the return value. let ret = unsafe { epoll_ctl( self.epoll_ctx.as_raw_fd(), EPOLL_CTL_ADD, fd.as_raw_fd(), &mut evt, ) }; if ret < 0
; Ok(()) } /// If `fd` was previously added to this context, the watched events will be replaced with /// `events` and the token associated with it will be replaced with the given `token`. pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> { let mut evt = epoll_event { events: events.0, u64: token.as_raw_token(), }; // Safe because we give a valid epoll FD and FD to modify, as well as a valid epoll_event // structure. Then we check the return value. let ret = unsafe { epoll_ctl( self.epoll_ctx.as_raw_fd(), EPOLL_CTL_MOD, fd.as_raw_fd(), &mut evt, ) }; if ret < 0 { return errno_result(); }; Ok(()) } /// Deletes the given `fd` from this context. /// /// If an `fd`'s token shows up in the list of hangup events, it should be removed using this /// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`. /// Failure to do so will cause the `wait` method to always return immediately, causing ~100% /// CPU load. pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> { // Safe because we give a valid epoll FD and FD to stop watching. Then we check the return // value. let ret = unsafe { epoll_ctl( self.epoll_ctx.as_raw_fd(), EPOLL_CTL_DEL, fd.as_raw_fd(), null_mut(), ) }; if ret < 0 { return errno_result(); }; Ok(()) } /// Waits for any events to occur in FDs that were previously added to this context. /// /// The events are level-triggered, meaning that if any events are unhandled (i.e. not reading /// for readable events and not closing for hungup events), subsequent calls to `wait` will /// return immediately. The consequence of not handling an event perpetually while calling /// `wait` is that the callers loop will degenerated to busy loop polling, pinning a CPU to /// ~100% usage. pub fn wait<'a>(&self, events: &'a EpollEvents) -> Result<PollEvents<'a, T>> { self.wait_timeout(events, Duration::new(i64::MAX as u64, 0)) } /// Like `wait` except will only block for a maximum of the given `timeout`. /// /// This may return earlier than `timeout` with zero events if the duration indicated exceeds /// system limits. pub fn wait_timeout<'a>( &self, events: &'a EpollEvents, timeout: Duration, ) -> Result<PollEvents<'a, T>> { let timeout_millis = if timeout.as_secs() as i64 == i64::max_value() { // We make the convenient assumption that 2^63 seconds is an effectively unbounded time // frame. This is meant to mesh with `wait` calling us with no timeout. -1 } else { // In cases where we the number of milliseconds would overflow an i32, we substitute the // maximum timeout which is ~24.8 days. let millis = timeout .as_secs() .checked_mul(1_000) .and_then(|ms| ms.checked_add(u64::from(timeout.subsec_nanos()) / 1_000_000)) .unwrap_or(i32::max_value() as u64); min(i32::max_value() as u64, millis) as i32 }; let ret = { let mut epoll_events = events.0.borrow_mut(); let max_events = epoll_events.len() as c_int; // Safe because we give an epoll context and a properly sized epoll_events array // pointer, which we trust the kernel to fill in properly. unsafe { handle_eintr_errno!(epoll_wait( self.epoll_ctx.as_raw_fd(), &mut epoll_events[0], max_events, timeout_millis )) } }; if ret < 0 { return errno_result(); } let epoll_events = events.0.borrow(); let events = PollEvents { count: ret as usize, events: epoll_events, tokens: PhantomData, }; Ok(events) } } impl<T: PollToken> AsRawFd for EpollContext<T> { fn as_raw_fd(&self) -> RawFd { self.epoll_ctx.as_raw_fd() } } impl<T: PollToken> IntoRawFd for EpollContext<T> { fn into_raw_fd(self) -> RawFd { self.epoll_ctx.into_raw_fd() } } /// Used to poll multiple objects that have file descriptors. /// /// # Example /// /// ``` /// # use sys_util::{Result, EventFd, PollContext, PollEvents}; /// # fn test() -> Result<()> { /// let evt1 = EventFd::new()?; /// let evt2 = EventFd::new()?; /// evt2.write(1)?; /// /// let ctx: PollContext<u32> = PollContext::new()?; /// ctx.add(&evt1, 1)?; /// ctx.add(&evt2, 2)?; /// /// let pollevents: PollEvents<u32> = ctx.wait()?; /// let tokens: Vec<u32> = pollevents.iter_readable().map(|e| e.token()).collect(); /// assert_eq!(&tokens[..], &[2]); /// # Ok(()) /// # } /// ``` pub struct PollContext<T> { epoll_ctx: EpollContext<T>, // We use a RefCell here so that the `wait` method only requires an immutable self reference // while returning the events (encapsulated by PollEvents). Without the RefCell, `wait` would // hold a mutable reference that lives as long as its returned reference (i.e. the PollEvents), // even though that reference is immutable. This is terribly inconvenient for the caller because // the borrow checking would prevent them from using `delete` and `add` while the events are in // scope. events: EpollEvents, // Hangup busy loop detection variables. See `check_for_hungup_busy_loop`. hangups: Cell<usize>, max_hangups: Cell<usize>, } impl<T: PollToken> PollContext<T> { /// Creates a new `PollContext`. pub fn new() -> Result<PollContext<T>> { Ok(PollContext { epoll_ctx: EpollContext::new()?, events: EpollEvents::new(), hangups: Cell::new(0), max_hangups: Cell::new(0), }) } /// Creates a new `PollContext` and adds the slice of `fd` and `token` tuples to the new /// context. /// /// This is equivalent to calling `new` followed by `add_many`. If there is an error, this will /// return the error instead of the new context. pub fn build_with(fd_tokens: &[(&dyn AsRawFd, T)]) -> Result<PollContext<T>> { let ctx = PollContext::new()?; ctx.add_many(fd_tokens)?; Ok(ctx) } /// Adds the given slice of `fd` and `token` tuples to this context. /// /// This is equivalent to calling `add` with each `fd` and `token`. If there are any errors, /// this method will stop adding `fd`s and return the first error, leaving this context in a /// undefined state. pub fn add_many(&self, fd_tokens: &[(&dyn AsRawFd, T)]) -> Result<()> { for (fd, token) in fd_tokens { self.add(*fd, T::from_raw_token(token.as_raw_token()))?; } Ok(()) } /// Adds the given `fd` to this context and associates the given `token` with the `fd`'s /// readable events. /// /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different /// FD number) added to this context, events will not be reported by `wait` anymore. pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> { self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token) } /// Adds the given `fd` to this context, watching for the specified events and associates the /// given 'token' with those events. /// /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different /// FD number) added to this context, events will not be reported by `wait` anymore. pub fn add_fd_with_events( &self, fd: &dyn AsRawFd, events: WatchingEvents, token: T, ) -> Result<()> { self.epoll_ctx.add_fd_with_events(fd, events, token)?; self.hangups.set(0); self.max_hangups.set(self.max_hangups.get() + 1); Ok(()) } /// If `fd` was previously added to this context, the watched events will be replaced with /// `events` and the token associated with it will be replaced with the given `token`. pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> { self.epoll_ctx.modify(fd, events, token) } /// Deletes the given `fd` from this context. /// /// If an `fd`'s token shows up in the list of hangup events, it should be removed using this /// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`. /// Failure to do so will cause the `wait` method to always return immediately, causing ~100% /// CPU load. pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> { self.epoll_ctx.delete(fd)?; self.hangups.set(0); self.max_hangups.set(self.max_hangups.get() - 1); Ok(()) } // This method determines if the the user of wait is misusing the `PollContext` by leaving FDs // in this `PollContext` that have been shutdown or hungup on. Such an FD will cause `wait` to // return instantly with a hungup event. If that FD is perpetually left in this context, a busy // loop burning ~100% of one CPU will silently occur with no human visible malfunction. // // How do we know if the client of this context is ignoring hangups? A naive implementation // would trigger if consecutive wait calls yield hangup events, but there are legitimate cases // for this, such as two distinct sockets becoming hungup across two consecutive wait calls. A // smarter implementation would only trigger if `delete` wasn't called between waits that // yielded hangups. Sadly `delete` isn't the only way to remove an FD from this context. The // other way is for the client to close the hungup FD, which automatically removes it from this // context. Assuming that the client always uses close, this implementation would too eagerly // trigger. // // The implementation used here keeps an upper bound of FDs in this context using a counter // hooked into add/delete (which is imprecise because close can also remove FDs without us // knowing). The number of consecutive (no add or delete in between) hangups yielded by wait // calls is counted and compared to the upper bound. If the upper bound is exceeded by the // consecutive hangups, the implementation triggers the check and logs. // // This implementation has false negatives because the upper bound can be completely too high, // in the worst case caused by only using close instead of delete. However, this method has the // advantage of always triggering eventually genuine busy loop cases, requires no dynamic // allocations, is fast and constant time to compute, and has no false positives. fn check_for_hungup_busy_loop(&self, new_hangups: usize) { let old_hangups = self.hangups.get(); let max_hangups = self.max_hangups.get(); if old_hangups <= max_hangups && old_hangups + new_hangups > max_hangups { warn!( "busy poll wait loop with hungup FDs detected on thread {}", thread::current().name().unwrap_or("") ); // This panic is helpful for tests of this functionality. #[cfg(test)] panic!("hungup busy loop detected"); } self.hangups.set(old_hangups + new_hangups); } /// Waits for any events to occur in FDs that were previously added to this context. /// /// The events are level-triggered, meaning that if any events are unhandled (i.e. not reading /// for readable events and not closing for hungup events), subsequent calls to `wait` will /// return immediately. The consequence of not handling an event perpetually while calling /// `wait` is that the callers loop will degenerated to busy loop polling, pinning a CPU to /// ~100% usage. /// /// # Panics /// Panics if the returned `PollEvents` structure is not dropped before subsequent `wait` calls. pub fn wait(&self) -> Result<PollEvents<T>> { self.wait_timeout(Duration::new(i64::MAX as u64, 0)) } /// Like `wait` except will only block for a maximum of the given `timeout`. /// /// This may return earlier than `timeout` with zero events if the duration indicated exceeds /// system limits. pub fn wait_timeout(&self, timeout: Duration) -> Result<PollEvents<T>> { let events = self.epoll_ctx.wait_timeout(&self.events, timeout)?; let hangups = events.iter_hungup().count(); self.check_for_hungup_busy_loop(hangups); Ok(events) } } impl<T: PollToken> AsRawFd for PollContext<T> { fn as_raw_fd(&self) -> RawFd { self.epoll_ctx.as_raw_fd() } } impl<T: PollToken> IntoRawFd for PollContext<T> { fn into_raw_fd(self) -> RawFd { self.epoll_ctx.into_raw_fd() } } #[cfg(test)] mod tests { use super::{super::EventFd, *}; use poll_token_derive::PollToken; use std::{os::unix::net::UnixStream, time::Instant}; #[test] fn poll_context() { let evt1 = EventFd::new().unwrap(); let evt2 = EventFd::new().unwrap(); evt1.write(1).unwrap(); evt2.write(1).unwrap(); let ctx: PollContext<u32> = PollContext::build_with(&[(&evt1, 1), (&evt2, 2)]).unwrap(); let mut evt_count = 0; while evt_count < 2 { for event in ctx.wait().unwrap().iter_readable() { evt_count += 1; match event.token() { 1 => { evt1.read().unwrap(); ctx.delete(&evt1).unwrap(); } 2 => { evt2.read().unwrap(); ctx.delete(&evt2).unwrap(); } _ => panic!("unexpected token"), }; } } assert_eq!(evt_count, 2); } #[test] fn poll_context_overflow() { const EVT_COUNT: usize = POLL_CONTEXT_MAX_EVENTS * 2 + 1; let ctx: PollContext<usize> = PollContext::new().unwrap(); let mut evts = Vec::with_capacity(EVT_COUNT); for i in 0..EVT_COUNT { let evt = EventFd::new().unwrap(); evt.write(1).unwrap(); ctx.add(&evt, i).unwrap(); evts.push(evt); } let mut evt_count = 0; while evt_count < EVT_COUNT { for event in ctx.wait().unwrap().iter_readable() { evts[event.token()].read().unwrap(); evt_count += 1; } } } #[test] #[should_panic] fn poll_context_hungup() { let (s1, s2) = UnixStream::pair().unwrap(); let ctx: PollContext<u32> = PollContext::new().unwrap(); ctx.add(&s1, 1).unwrap(); // Causes s1 to receive hangup events, which we purposefully ignore to trip the detection // logic in `PollContext`. drop(s2); // Should easily panic within this many iterations. for _ in 0..1000 { ctx.wait().unwrap(); } } #[test] fn poll_context_timeout() { let ctx: PollContext<u32> = PollContext::new().unwrap(); let dur = Duration::from_millis(10); let start_inst = Instant::now(); ctx.wait_timeout(dur).unwrap(); assert!(start_inst.elapsed() >= dur); } #[test] #[allow(dead_code)] fn poll_token_derive() { #[derive(PollToken)] enum EmptyToken {} #[derive(PartialEq, Debug, PollToken)] enum Token { Alpha, Beta, // comments Gamma(u32), Delta { index: usize }, Omega, } assert_eq!( Token::from_raw_token(Token::Alpha.as_raw_token()), Token::Alpha ); assert_eq!( Token::from_raw_token(Token::Beta.as_raw_token()), Token::Beta ); assert_eq!( Token::from_raw_token(Token::Gamma(55).as_raw_token()), Token::Gamma(55) ); assert_eq!( Token::from_raw_token(Token::Delta { index: 100 }.as_raw_token()), Token::Delta { index: 100 } ); assert_eq!( Token::from_raw_token(Token::Omega.as_raw_token()), Token::Omega ); } }
{ return errno_result(); }
metrics_test.go
// Copyright (C) 2021 ScyllaDB package healthcheck import ( "testing" "github.com/prometheus/client_golang/prometheus" "github.com/scylladb/scylla-manager/pkg/util/uuid" ) // Removing of cluster metrics deadlocked when number of metrics exceeded buffered channel length // used for metric collection. // Issue #2843 func TestRemoveClusterMetricsWhenNumberOfMetricsExceedsDefaultChannelLength_2843(t *testing.T) { clusterID := uuid.MustRandom() metric := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: "scylla_manager", Subsystem: "healthcheck", Name: "status",
}, []string{clusterKey, hostKey}) for i := 0; i < 3*10*metricBufferSize; i++ { hl := prometheus.Labels{ clusterKey: clusterID.String(), hostKey: uuid.MustRandom().String(), } metric.With(hl).Set(1) } r := runner{metrics: &runnerMetrics{ status: metric, rtt: metric, timeout: metric, }} r.removeMetricsForCluster(clusterID) }
dump_nat_vppcalls.go
// Copyright (c) 2019 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vpp2001 import ( "fmt" "net" "sort" "strings" "github.com/gogo/protobuf/proto" ifs "github.com/ligato/vpp-agent/api/models/vpp/interfaces" nat "github.com/ligato/vpp-agent/api/models/vpp/nat" vpp_nat "github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp2001/nat" "github.com/ligato/vpp-agent/plugins/vpp/ifplugin/ifaceidx" ) // DNATs sorted by tags type dnatMap map[string]*nat.DNat44 // static mappings sorted by tags type stMappingMap map[string][]*nat.DNat44_StaticMapping // identity mappings sorted by tags type idMappingMap map[string][]*nat.DNat44_IdentityMapping // Nat44GlobalConfigDump dumps global NAT44 config in NB format. func (h *NatVppHandler) Nat44GlobalConfigDump() (*nat.Nat44Global, error) { isEnabled, err := h.isNat44ForwardingEnabled() if err != nil { return nil, err } natInterfaces, err := h.nat44InterfaceDump() if err != nil { return nil, err } natAddressPool, err := h.nat44AddressDump() if err != nil { return nil, err } vrIPv4, _, err := h.virtualReassemblyDump() if err != nil { return nil, err } // combine into the global NAT configuration return &nat.Nat44Global{ Forwarding: isEnabled, NatInterfaces: natInterfaces, AddressPool: natAddressPool, VirtualReassembly: vrIPv4, }, nil } // DNat44Dump dumps all configured DNAT-44 configurations ordered by label. func (h *NatVppHandler) DNat44Dump() (dnats []*nat.DNat44, err error) { dnatMap := make(dnatMap) // Static mappings natStMappings, err := h.nat44StaticMappingDump() if err != nil { return nil, fmt.Errorf("failed to dump NAT44 static mappings: %v", err) } for label, mappings := range natStMappings { dnat := getOrCreateDNAT(dnatMap, label) dnat.StMappings = append(dnat.StMappings, mappings...) } // Static mappings with load balancer natStLbMappings, err := h.nat44StaticMappingLbDump() if err != nil { return nil, fmt.Errorf("failed to dump NAT44 static mappings with load balancer: %v", err) } for label, mappings := range natStLbMappings { dnat := getOrCreateDNAT(dnatMap, label) dnat.StMappings = append(dnat.StMappings, mappings...) } // Identity mappings natIDMappings, err := h.nat44IdentityMappingDump() if err != nil { return nil, fmt.Errorf("failed to dump NAT44 identity mappings: %v", err) } for label, mappings := range natIDMappings { dnat := getOrCreateDNAT(dnatMap, label) dnat.IdMappings = append(dnat.IdMappings, mappings...) } // Convert map of DNAT configurations into a list. for _, dnat := range dnatMap { dnats = append(dnats, dnat) } // sort to simplify testing sort.Slice(dnats, func(i, j int) bool { return dnats[i].Label < dnats[j].Label }) return dnats, nil } // nat44AddressDump returns NAT44 address pool configured in the VPP. func (h *NatVppHandler) nat44AddressDump() (addressPool []*nat.Nat44Global_Address, err error) { req := &vpp_nat.Nat44AddressDump{} reqContext := h.callsChannel.SendMultiRequest(req) for { msg := &vpp_nat.Nat44AddressDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 Address pool: %v", err) } if stop { break } addressPool = append(addressPool, &nat.Nat44Global_Address{ Address: net.IP(msg.IPAddress[:]).String(), VrfId: msg.VrfID, TwiceNat: getNat44Flags(msg.Flags).isTwiceNat, }) } return } // virtualReassemblyDump returns current NAT virtual-reassembly configuration. func (h *NatVppHandler) virtualReassemblyDump() (vrIPv4 *nat.VirtualReassembly, vrIPv6 *nat.VirtualReassembly, err error) { req := &vpp_nat.NatGetReass{} reply := &vpp_nat.NatGetReassReply{} if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil { return nil, nil, fmt.Errorf("failed to get NAT virtual reassembly configuration: %v", err) } vrIPv4 = &nat.VirtualReassembly{ Timeout: reply.IP4Timeout, MaxReassemblies: uint32(reply.IP4MaxReass), MaxFragments: uint32(reply.IP4MaxFrag), DropFragments: uintToBool(reply.IP4DropFrag), } vrIPv6 = &nat.VirtualReassembly{ Timeout: reply.IP6Timeout, MaxReassemblies: uint32(reply.IP6MaxReass), MaxFragments: uint32(reply.IP6MaxFrag), DropFragments: uintToBool(reply.IP6DropFrag), } return } // nat44StaticMappingDump returns a map of NAT44 static mappings sorted by tags func (h *NatVppHandler) nat44StaticMappingDump() (entries stMappingMap, err error) { entries = make(stMappingMap) childMappings := make(stMappingMap) req := &vpp_nat.Nat44StaticMappingDump{} reqContext := h.callsChannel.SendMultiRequest(req) for { msg := &vpp_nat.Nat44StaticMappingDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 static mapping: %v", err) } if stop { break } lcIPAddress := net.IP(msg.LocalIPAddress[:]).String() exIPAddress := net.IP(msg.ExternalIPAddress[:]).String() // Parse tag (DNAT label) tag := strings.TrimRight(msg.Tag, "\x00") if _, hasTag := entries[tag]; !hasTag { entries[tag] = []*nat.DNat44_StaticMapping{} childMappings[tag] = []*nat.DNat44_StaticMapping{} } // resolve interface name var ( found bool extIfaceName string extIfaceMeta *ifaceidx.IfaceMetadata ) if msg.ExternalSwIfIndex != NoInterface { extIfaceName, extIfaceMeta, found = h.ifIndexes.LookupBySwIfIndex(uint32(msg.ExternalSwIfIndex)) if !found { h.log.Warnf("Interface with index %v not found in the mapping", msg.ExternalSwIfIndex) continue } } flags := getNat44Flags(msg.Flags) // Add mapping into the map. mapping := &nat.DNat44_StaticMapping{ ExternalInterface: extIfaceName, ExternalIp: exIPAddress, ExternalPort: uint32(msg.ExternalPort), LocalIps: []*nat.DNat44_StaticMapping_LocalIP{ // single-value { VrfId: msg.VrfID, LocalIp: lcIPAddress, LocalPort: uint32(msg.LocalPort), }, }, Protocol: h.protocolNumberToNBValue(msg.Protocol), TwiceNat: h.getTwiceNatMode(flags.isTwiceNat, flags.isSelfTwiceNat), // if there is only one backend the affinity can not be set SessionAffinity: 0, } entries[tag] = append(entries[tag], mapping) if msg.ExternalSwIfIndex != NoInterface { // collect auto-generated "child" mappings (interface replaced with every assigned IP address) for _, ipAddr := range h.getInterfaceIPAddresses(extIfaceName, extIfaceMeta) { childMapping := proto.Clone(mapping).(*nat.DNat44_StaticMapping) childMapping.ExternalIp = ipAddr childMapping.ExternalInterface = "" childMappings[tag] = append(childMappings[tag], childMapping) } } } // do not dump auto-generated child mappings for tag, mappings := range entries { var filtered []*nat.DNat44_StaticMapping for _, mapping := range mappings { isChild := false for _, child := range childMappings[tag] { if proto.Equal(mapping, child) { isChild = true break } } if !isChild { filtered = append(filtered, mapping) } } entries[tag] = filtered } return entries, nil } // nat44StaticMappingLbDump returns a map of NAT44 static mapping with load balancing sorted by tags. func (h *NatVppHandler) nat44StaticMappingLbDump() (entries stMappingMap, err error) { entries = make(stMappingMap) req := &vpp_nat.Nat44LbStaticMappingDump{} reqContext := h.callsChannel.SendMultiRequest(req) for { msg := &vpp_nat.Nat44LbStaticMappingDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 lb-static mapping: %v", err) } if stop { break } // Parse tag (DNAT label) tag := strings.TrimRight(msg.Tag, "\x00") if _, hasTag := entries[tag]; !hasTag { entries[tag] = []*nat.DNat44_StaticMapping{} } // Prepare localIPs var locals []*nat.DNat44_StaticMapping_LocalIP for _, localIPVal := range msg.Locals { locals = append(locals, &nat.DNat44_StaticMapping_LocalIP{ VrfId: localIPVal.VrfID, LocalIp: net.IP(localIPVal.Addr[:]).String(), LocalPort: uint32(localIPVal.Port), Probability: uint32(localIPVal.Probability), }) } exIPAddress := net.IP(msg.ExternalAddr[:]).String() flags := getNat44Flags(msg.Flags) // Add mapping into the map. mapping := &nat.DNat44_StaticMapping{ ExternalIp: exIPAddress, ExternalPort: uint32(msg.ExternalPort), LocalIps: locals, Protocol: h.protocolNumberToNBValue(msg.Protocol), TwiceNat: h.getTwiceNatMode(flags.isTwiceNat, flags.isSelfTwiceNat), SessionAffinity: msg.Affinity, } entries[tag] = append(entries[tag], mapping) } return entries, nil } // nat44IdentityMappingDump returns a map of NAT44 identity mappings sorted by tags. func (h *NatVppHandler) nat44IdentityMappingDump() (entries idMappingMap, err error) { entries = make(idMappingMap) childMappings := make(idMappingMap) req := &vpp_nat.Nat44IdentityMappingDump{} reqContext := h.callsChannel.SendMultiRequest(req) for { msg := &vpp_nat.Nat44IdentityMappingDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 identity mapping: %v", err) } if stop { break } // Parse tag (DNAT label) tag := strings.TrimRight(msg.Tag, "\x00") if _, hasTag := entries[tag]; !hasTag { entries[tag] = []*nat.DNat44_IdentityMapping{} childMappings[tag] = []*nat.DNat44_IdentityMapping{} } // resolve interface name var ( found bool ifaceName string ifaceMeta *ifaceidx.IfaceMetadata ) if msg.SwIfIndex != NoInterface { ifaceName, ifaceMeta, found = h.ifIndexes.LookupBySwIfIndex(uint32(msg.SwIfIndex)) if !found { h.log.Warnf("Interface with index %v not found in the mapping", msg.SwIfIndex) continue } } // Add mapping into the map. mapping := &nat.DNat44_IdentityMapping{ IpAddress: net.IP(msg.IPAddress[:]).String(), VrfId: msg.VrfID, Interface: ifaceName, Port: uint32(msg.Port), Protocol: h.protocolNumberToNBValue(msg.Protocol), } entries[tag] = append(entries[tag], mapping) if msg.SwIfIndex != NoInterface { // collect auto-generated "child" mappings (interface replaced with every assigned IP address) for _, ipAddr := range h.getInterfaceIPAddresses(ifaceName, ifaceMeta) { childMapping := proto.Clone(mapping).(*nat.DNat44_IdentityMapping) childMapping.IpAddress = ipAddr childMapping.Interface = "" childMappings[tag] = append(childMappings[tag], childMapping) } } } // do not dump auto-generated child mappings for tag, mappings := range entries { var filtered []*nat.DNat44_IdentityMapping for _, mapping := range mappings { isChild := false for _, child := range childMappings[tag] { if proto.Equal(mapping, child) { isChild = true break } } if !isChild { filtered = append(filtered, mapping) } } entries[tag] = filtered } return entries, nil } // nat44InterfaceDump dumps NAT44 interface features. func (h *NatVppHandler) nat44InterfaceDump() (interfaces []*nat.Nat44Global_Interface, err error) { /* dump non-Output interfaces first */ req1 := &vpp_nat.Nat44InterfaceDump{} reqContext := h.callsChannel.SendMultiRequest(req1) for { msg := &vpp_nat.Nat44InterfaceDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 interface: %v", err) } if stop { break } // Find interface name ifName, _, found := h.ifIndexes.LookupBySwIfIndex(uint32(msg.SwIfIndex)) if !found { h.log.Warnf("Interface with index %d not found in the mapping", msg.SwIfIndex) continue } flags := getNat44Flags(msg.Flags) if flags.isInside { interfaces = append(interfaces, &nat.Nat44Global_Interface{ Name: ifName, IsInside: true, }) } else { interfaces = append(interfaces, &nat.Nat44Global_Interface{ Name: ifName, IsInside: false, }) } } /* dump Output interfaces next */ req2 := &vpp_nat.Nat44InterfaceOutputFeatureDump{} reqContext = h.callsChannel.SendMultiRequest(req2) for { msg := &vpp_nat.Nat44InterfaceOutputFeatureDetails{} stop, err := reqContext.ReceiveReply(msg) if err != nil { return nil, fmt.Errorf("failed to dump NAT44 interface output feature: %v", err) } if stop { break } // Find interface name ifName, _, found := h.ifIndexes.LookupBySwIfIndex(uint32(msg.SwIfIndex)) if !found { h.log.Warnf("Interface with index %d not found in the mapping", msg.SwIfIndex) continue } flags := getNat44Flags(msg.Flags) interfaces = append(interfaces, &nat.Nat44Global_Interface{ Name: ifName, IsInside: flags.isInside, OutputFeature: true, }) } return interfaces, nil } // Nat44IsForwardingEnabled checks if the NAT44 forwarding is enabled. func (h *NatVppHandler) isNat44ForwardingEnabled() (isEnabled bool, err error) { req := &vpp_nat.Nat44ForwardingIsEnabled{} reply := &vpp_nat.Nat44ForwardingIsEnabledReply{} if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil { return false, fmt.Errorf("failed to dump NAT44 forwarding: %v", err) } isEnabled = reply.Enabled return isEnabled, nil } func (h *NatVppHandler) getInterfaceIPAddresses(ifaceName string, ifaceMeta *ifaceidx.IfaceMetadata) (ipAddrs []string) { ipAddrNets := ifaceMeta.IPAddresses dhcpLease, hasDHCPLease := h.dhcpIndex.GetValue(ifaceName) if hasDHCPLease { lease := dhcpLease.(*ifs.DHCPLease) ipAddrNets = append(ipAddrNets, lease.HostIpAddress) } for _, ipAddrNet := range ipAddrNets { ipAddr := strings.Split(ipAddrNet, "/")[0] ipAddrs = append(ipAddrs, ipAddr) } return ipAddrs } // protocolNumberToNBValue converts protocol numeric representation into the corresponding enum // enum value from the NB model. func (h *NatVppHandler) protocolNumberToNBValue(protocol uint8) (proto nat.DNat44_Protocol) { switch protocol { case TCP: return nat.DNat44_TCP case UDP: return nat.DNat44_UDP case ICMP: return nat.DNat44_ICMP default: h.log.Warnf("Unknown protocol %v", protocol) return 0 } } // protocolNBValueToNumber converts protocol enum value from the NB model into the // corresponding numeric representation. func (h *NatVppHandler) protocolNBValueToNumber(protocol nat.DNat44_Protocol) (proto uint8) { switch protocol { case nat.DNat44_TCP: return TCP case nat.DNat44_UDP: return UDP case nat.DNat44_ICMP: return ICMP default: h.log.Warnf("Unknown protocol %v, defaulting to TCP", protocol) return TCP } } func (h *NatVppHandler) getTwiceNatMode(twiceNat, selfTwiceNat bool) nat.DNat44_StaticMapping_TwiceNatMode { if twiceNat { if selfTwiceNat { h.log.Warnf("Both TwiceNAT and self-TwiceNAT are enabled") return 0 } return nat.DNat44_StaticMapping_ENABLED } if selfTwiceNat { return nat.DNat44_StaticMapping_SELF } return nat.DNat44_StaticMapping_DISABLED } func
(dnats dnatMap, label string) *nat.DNat44 { if _, created := dnats[label]; !created { dnats[label] = &nat.DNat44{Label: label} } return dnats[label] } func getNat44Flags(flags vpp_nat.NatConfigFlags) *nat44Flags { natFlags := &nat44Flags{} if flags&vpp_nat.NAT_IS_EXT_HOST_VALID != 0 { natFlags.isExtHostValid = true } if flags&vpp_nat.NAT_IS_STATIC != 0 { natFlags.isStatic = true } if flags&vpp_nat.NAT_IS_INSIDE != 0 { natFlags.isInside = true } if flags&vpp_nat.NAT_IS_OUTSIDE != 0 { natFlags.isOutside = true } if flags&vpp_nat.NAT_IS_ADDR_ONLY != 0 { natFlags.isAddrOnly = true } if flags&vpp_nat.NAT_IS_OUT2IN_ONLY != 0 { natFlags.isOut2In = true } if flags&vpp_nat.NAT_IS_SELF_TWICE_NAT != 0 { natFlags.isSelfTwiceNat = true } if flags&vpp_nat.NAT_IS_TWICE_NAT != 0 { natFlags.isTwiceNat = true } return natFlags } func uintToBool(value uint8) bool { if value == 0 { return false } return true }
getOrCreateDNAT
index.js
import itf from './itf'; import mvi from './mvi'; import formConfig from '../config/form'; import { createSaveInProgressFormReducer } from 'platform/forms/save-in-progress/reducers'; export default { form: createSaveInProgressFormReducer(formConfig),
itf, mvi, };
moment.js
/* * Copyright (c) 2020 aureliancnx * * MIT LICENSE * * This project is part of aureliancnx. * See https://github.com/aureliancnx/Bubulle-Norminette for further info. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var e,i;function c(){return e.apply(null,arguments)}function o(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function u(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function r(e){return void 0===e}function l(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function a(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function d(e,t){for(var n=[],s=0;s<e.length;++s)n.push(t(e[s],s));return n}function f(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function h(e,t){for(var n in t)f(t,n)&&(e[n]=t[n]);return f(t,"toString")&&(e.toString=t.toString),f(t,"valueOf")&&(e.valueOf=t.valueOf),e}function m(e,t,n,s){return Ot(e,t,n,s,!0).utc()}function _(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function y(e){if(null==e._isValid){var t=_(e),n=i.call(t.parsedDateParts,function(e){return null!=e}),s=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return s;e._isValid=s}return e._isValid}function g(e){var t=m(NaN);return null!=e?h(_(t),e):_(t).userInvalidated=!0,t}i=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var p=c.momentProperties=[];function v(e,t){var n,s,i;if(r(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),r(t._i)||(e._i=t._i),r(t._f)||(e._f=t._f),r(t._l)||(e._l=t._l),r(t._strict)||(e._strict=t._strict),r(t._tzm)||(e._tzm=t._tzm),r(t._isUTC)||(e._isUTC=t._isUTC),r(t._offset)||(e._offset=t._offset),r(t._pf)||(e._pf=_(t)),r(t._locale)||(e._locale=t._locale),0<p.length)for(n=0;n<p.length;n++)r(i=t[s=p[n]])||(e[s]=i);return e}var t=!1;function w(e){v(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===t&&(t=!0,c.updateOffset(this),t=!1)}function M(e){return e instanceof w||null!=e&&null!=e._isAMomentObject}function k(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function S(e){var t=+e,n=0;return 0!=t&&isFinite(t)&&(n=k(t)),n}function D(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&S(e[a])!==S(t[a]))&&r++;return r+i}function Y(e){!1===c.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function n(i,r){var a=!0;return h(function(){if(null!=c.deprecationHandler&&c.deprecationHandler(null,i),a){for(var e,t=[],n=0;n<arguments.length;n++){if(e="","object"==typeof arguments[n]){for(var s in e+="\n["+n+"] ",arguments[0])e+=s+": "+arguments[0][s]+", ";e=e.slice(0,-2)}else e=arguments[n];t.push(e)}Y(i+"\nArguments: "+Array.prototype.slice.call(t).join("")+"\n"+(new Error).stack),a=!1}return r.apply(this,arguments)},r)}var s,O={};function x(e,t){null!=c.deprecationHandler&&c.deprecationHandler(e,t),O[e]||(Y(t),O[e]=!0)}function T(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function b(e,t){var n,s=h({},e);for(n in t)f(t,n)&&(u(e[n])&&u(t[n])?(s[n]={},h(s[n],e[n]),h(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)f(e,n)&&!f(t,n)&&u(e[n])&&(s[n]=h({},s[n]));return s}function P(e){null!=e&&this.set(e)}c.suppressDeprecationWarnings=!1,c.deprecationHandler=null,s=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)f(e,t)&&n.push(t);return n};var W={};function R(e,t){var n=e.toLowerCase();W[n]=W[n+"s"]=W[t]=e}function C(e){return"string"==typeof e?W[e]||W[e.toLowerCase()]:void 0}function F(e){var t,n,s={};for(n in e)f(e,n)&&(t=C(n))&&(s[t]=e[n]);return s}var U={};function N(e,t){U[e]=t}function H(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}var L=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,G=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,V={},j={};function I(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(j[e]=i),t&&(j[t[0]]=function(){return H(i.apply(this,arguments),t[1],t[2])}),n&&(j[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function E(e,t){return e.isValid()?(t=A(t,e.localeData()),V[t]=V[t]||function(s){for(var e,i=s.match(L),t=0,r=i.length;t<r;t++)j[i[t]]?i[t]=j[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=T(i[n])?i[n].call(e,s):i[n];return t}}(t),V[t](e)):e.localeData().invalidDate()}function A(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(G.lastIndex=0;0<=n&&G.test(e);)e=e.replace(G,s),G.lastIndex=0,--n;return e}var z=/\d/,Z=/\d\d/,$=/\d{3}/,q=/\d{4}/,J=/[+-]?\d{6}/,B=/\d\d?/,Q=/\d\d\d\d?/,X=/\d\d\d\d\d\d?/,K=/\d{1,3}/,ee=/\d{1,4}/,te=/[+-]?\d{1,6}/,ne=/\d+/,se=/[+-]?\d+/,ie=/Z|[+-]\d\d:?\d\d/gi,re=/Z|[+-]\d\d(?::?\d\d)?/gi,ae=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,oe={};function ue(e,n,s){oe[e]=T(n)?n:function(e,t){return e&&s?s:n}}function le(e,t){return f(oe,e)?oe[e](t._strict,t._locale):new RegExp(de(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function de(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var he={};function ce(e,n){var t,s=n;for("string"==typeof e&&(e=[e]),l(n)&&(s=function(e,t){t[n]=S(e)}),t=0;t<e.length;t++)he[e[t]]=s}function fe(e,i){ce(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var me=0,_e=1,ye=2,ge=3,pe=4,ve=5,we=6,Me=7,ke=8;function Se(e){return De(e)?366:365}function De(e){return e%4==0&&e%100!=0||e%400==0}I("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),I(0,["YY",2],0,function(){return this.year()%100}),I(0,["YYYY",4],0,"year"),I(0,["YYYYY",5],0,"year"),I(0,["YYYYYY",6,!0],0,"year"),R("year","y"),N("year",1),ue("Y",se),ue("YY",B,Z),ue("YYYY",ee,q),ue("YYYYY",te,J),ue("YYYYYY",te,J),ce(["YYYYY","YYYYYY"],me),ce("YYYY",function(e,t){t[me]=2===e.length?c.parseTwoDigitYear(e):S(e)}),ce("YY",function(e,t){t[me]=c.parseTwoDigitYear(e)}),ce("Y",function(e,t){t[me]=parseInt(e,10)}),c.parseTwoDigitYear=function(e){return S(e)+(68<S(e)?1900:2e3)};var Ye,Oe=xe("FullYear",!0);function xe(t,n){return function(e){return null!=e?(be(this,t,e),c.updateOffset(this,n),this):Te(this,t)}}function Te(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function
(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&De(e.year())?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Pe(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Pe(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,s=(t%(n=12)+n)%n;return e+=(t-s)/12,1==s?De(e)?29:28:31-s%7%2}Ye=Array.prototype.indexOf?Array.prototype.indexOf:function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},I("M",["MM",2],"Mo",function(){return this.month()+1}),I("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),I("MMMM",0,0,function(e){return this.localeData().months(this,e)}),R("month","M"),N("month",8),ue("M",B),ue("MM",B,Z),ue("MMM",function(e,t){return t.monthsShortRegex(e)}),ue("MMMM",function(e,t){return t.monthsRegex(e)}),ce(["M","MM"],function(e,t){t[_e]=S(e)-1}),ce(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[_e]=i:_(n).invalidMonth=e});var We=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Re="January_February_March_April_May_June_July_August_September_October_November_December".split("_");var Ce="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function Fe(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=S(t);else if(!l(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),Pe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function Ue(e){return null!=e?(Fe(this,e),c.updateOffset(this,!0),this):Te(this,"Month")}var Ne=ae;var He=ae;function Le(){function e(e,t){return t.length-e.length}for(var t,n=[],s=[],i=[],r=0;r<12;r++)t=m([2e3,r]),n.push(this.monthsShort(t,"")),s.push(this.months(t,"")),i.push(this.months(t,"")),i.push(this.monthsShort(t,""));for(n.sort(e),s.sort(e),i.sort(e),r=0;r<12;r++)n[r]=de(n[r]),s[r]=de(s[r]);for(r=0;r<24;r++)i[r]=de(i[r]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+n.join("|")+")","i")}function Ge(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&0<=e&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function Ve(e,t,n){var s=7+t-n;return s-(7+Ge(e,0,s).getUTCDay()-t)%7-1}function je(e,t,n,s,i){var r,a=1+7*(t-1)+(7+n-s)%7+Ve(e,s,i),o=a<=0?Se(r=e-1)+a:a>Se(e)?(r=e+1,a-Se(e)):(r=e,a);return{year:r,dayOfYear:o}}function Ie(e,t,n){var s,i,r=Ve(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+Ee(i=e.year()-1,t,n):a>Ee(e.year(),t,n)?(s=a-Ee(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function Ee(e,t,n){var s=Ve(e,t,n),i=Ve(e+1,t,n);return(Se(e)-s+i)/7}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),R("week","w"),R("isoWeek","W"),N("week",5),N("isoWeek",5),ue("w",B),ue("ww",B,Z),ue("W",B),ue("WW",B,Z),fe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=S(e)});I("d",0,"do","day"),I("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),I("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),I("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),R("day","d"),R("weekday","e"),R("isoWeekday","E"),N("day",11),N("weekday",11),N("isoWeekday",11),ue("d",B),ue("e",B),ue("E",B),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),fe(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:_(n).invalidWeekday=e}),fe(["d","e","E"],function(e,t,n,s){t[s]=S(e)});var Ae="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");var ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");var Ze="Su_Mo_Tu_We_Th_Fr_Sa".split("_");var $e=ae;var qe=ae;var Je=ae;function Be(){function e(e,t){return t.length-e.length}for(var t,n,s,i,r=[],a=[],o=[],u=[],l=0;l<7;l++)t=m([2e3,1]).day(l),n=this.weekdaysMin(t,""),s=this.weekdaysShort(t,""),i=this.weekdays(t,""),r.push(n),a.push(s),o.push(i),u.push(n),u.push(s),u.push(i);for(r.sort(e),a.sort(e),o.sort(e),u.sort(e),l=0;l<7;l++)a[l]=de(a[l]),o[l]=de(o[l]),u[l]=de(u[l]);this._weekdaysRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+r.join("|")+")","i")}function Qe(){return this.hours()%12||12}function Xe(e,t){I(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Ke(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Qe),I("k",["kk",2],0,function(){return this.hours()||24}),I("hmm",0,0,function(){return""+Qe.apply(this)+H(this.minutes(),2)}),I("hmmss",0,0,function(){return""+Qe.apply(this)+H(this.minutes(),2)+H(this.seconds(),2)}),I("Hmm",0,0,function(){return""+this.hours()+H(this.minutes(),2)}),I("Hmmss",0,0,function(){return""+this.hours()+H(this.minutes(),2)+H(this.seconds(),2)}),Xe("a",!0),Xe("A",!1),R("hour","h"),N("hour",13),ue("a",Ke),ue("A",Ke),ue("H",B),ue("h",B),ue("k",B),ue("HH",B,Z),ue("hh",B,Z),ue("kk",B,Z),ue("hmm",Q),ue("hmmss",X),ue("Hmm",Q),ue("Hmmss",X),ce(["H","HH"],ge),ce(["k","kk"],function(e,t,n){var s=S(e);t[ge]=24===s?0:s}),ce(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),ce(["h","hh"],function(e,t,n){t[ge]=S(e),_(n).bigHour=!0}),ce("hmm",function(e,t,n){var s=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s)),_(n).bigHour=!0}),ce("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s,2)),t[ve]=S(e.substr(i)),_(n).bigHour=!0}),ce("Hmm",function(e,t,n){var s=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s))}),ce("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=S(e.substr(0,s)),t[pe]=S(e.substr(s,2)),t[ve]=S(e.substr(i))});var et,tt=xe("Hours",!0),nt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Re,monthsShort:Ce,week:{dow:0,doy:6},weekdays:Ae,weekdaysMin:Ze,weekdaysShort:ze,meridiemParse:/[ap]\.?m?\.?/i},st={},it={};function rt(e){return e?e.toLowerCase().replace("_","-"):e}function at(e){var t=null;if(!st[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=et._abbr;require("./locale/"+e),ot(t)}catch(e){}return st[e]}function ot(e,t){var n;return e&&(n=r(t)?lt(e):ut(e,t))&&(et=n),et._abbr}function ut(e,t){if(null===t)return delete st[e],null;var n=nt;if(t.abbr=e,null!=st[e])x("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=st[e]._config;else if(null!=t.parentLocale){if(null==st[t.parentLocale])return it[t.parentLocale]||(it[t.parentLocale]=[]),it[t.parentLocale].push({name:e,config:t}),null;n=st[t.parentLocale]._config}return st[e]=new P(b(n,t)),it[e]&&it[e].forEach(function(e){ut(e.name,e.config)}),ot(e),st[e]}function lt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return et;if(!o(e)){if(t=at(e))return t;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=rt(e[r]).split("-")).length,n=(n=rt(e[r+1]))?n.split("-"):null;0<t;){if(s=at(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&D(i,n,!0)>=t-1)break;t--}r++}return null}(e)}function dt(e){var t,n=e._a;return n&&-2===_(e).overflow&&(t=n[_e]<0||11<n[_e]?_e:n[ye]<1||n[ye]>Pe(n[me],n[_e])?ye:n[ge]<0||24<n[ge]||24===n[ge]&&(0!==n[pe]||0!==n[ve]||0!==n[we])?ge:n[pe]<0||59<n[pe]?pe:n[ve]<0||59<n[ve]?ve:n[we]<0||999<n[we]?we:-1,_(e)._overflowDayOfYear&&(t<me||ye<t)&&(t=ye),_(e)._overflowWeeks&&-1===t&&(t=Me),_(e)._overflowWeekday&&-1===t&&(t=ke),_(e).overflow=t),e}function ht(e,t,n){return null!=e?e:null!=t?t:n}function ct(e){var t,n,s,i,r,a,o=[];if(!e._d){for(r=e,a=new Date(c.now()),s=r._useUTC?[a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()]:[a.getFullYear(),a.getMonth(),a.getDate()],e._w&&null==e._a[ye]&&null==e._a[_e]&&function(e){var t,n,s,i,r,a,o,u;{var l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(r=1,a=4,n=ht(t.GG,e._a[me],Ie(xt(),1,4).year),s=ht(t.W,1),((i=ht(t.E,1))<1||7<i)&&(u=!0)):(r=e._locale._week.dow,a=e._locale._week.doy,l=Ie(xt(),r,a),n=ht(t.gg,e._a[me],l.year),s=ht(t.w,l.week),null!=t.d?((i=t.d)<0||6<i)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||6<t.e)&&(u=!0)):i=r)}s<1||s>Ee(n,r,a)?_(e)._overflowWeeks=!0:null!=u?_(e)._overflowWeekday=!0:(o=je(n,s,i,r,a),e._a[me]=o.year,e._dayOfYear=o.dayOfYear)}(e),null!=e._dayOfYear&&(i=ht(e._a[me],s[me]),(e._dayOfYear>Se(i)||0===e._dayOfYear)&&(_(e)._overflowDayOfYear=!0),n=Ge(i,0,e._dayOfYear),e._a[_e]=n.getUTCMonth(),e._a[ye]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=o[t]=s[t];for(;t<7;t++)e._a[t]=o[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ge]&&0===e._a[pe]&&0===e._a[ve]&&0===e._a[we]&&(e._nextDay=!0,e._a[ge]=0),e._d=(e._useUTC?Ge:function(e,t,n,s,i,r,a){var o=new Date(e,t,n,s,i,r,a);return e<100&&0<=e&&isFinite(o.getFullYear())&&o.setFullYear(e),o}).apply(null,o),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ge]=24),e._w&&void 0!==e._w.d&&e._w.d!==e._d.getDay()&&(_(e).weekdayMismatch=!0)}}var ft=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,mt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_t=/Z|[+-]\d\d(?::?\d\d)?/,yt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],gt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],pt=/^\/?Date\((\-?\d+)/i;function vt(e){var t,n,s,i,r,a,o=e._i,u=ft.exec(o)||mt.exec(o);if(u){for(_(e).iso=!0,t=0,n=yt.length;t<n;t++)if(yt[t][1].exec(u[1])){i=yt[t][0],s=!1!==yt[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=gt.length;t<n;t++)if(gt[t][1].exec(u[3])){r=(u[2]||" ")+gt[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!_t.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Dt(e)}else e._isValid=!1}var wt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function Mt(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),Ce.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}var kt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function St(e){var t,n,s,i=wt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim());if(i){var r=Mt(i[4],i[3],i[2],i[5],i[6],i[7]);if(t=i[1],n=r,s=e,t&&ze.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(_(s).weekdayMismatch=!0,!void(s._isValid=!1)))return;e._a=r,e._tzm=function(e,t,n){if(e)return kt[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return 60*((s-i)/100)+i}(i[8],i[9],i[10]),e._d=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),_(e).rfc2822=!0}else e._isValid=!1}function Dt(e){if(e._f!==c.ISO_8601)if(e._f!==c.RFC_2822){e._a=[],_(e).empty=!0;for(var t,n,s,i,r,a,o=""+e._i,u=o.length,l=0,d=A(e._f,e._locale).match(L)||[],h=0;h<d.length;h++)n=d[h],(t=(o.match(le(n,e))||[])[0])&&(0<(s=o.substr(0,o.indexOf(t))).length&&_(e).unusedInput.push(s),o=o.slice(o.indexOf(t)+t.length),l+=t.length),j[n]?(t?_(e).empty=!1:_(e).unusedTokens.push(n),i=n,a=e,null!=(r=t)&&f(he,i)&&he[i](r,a._a,a,i)):e._strict&&!t&&_(e).unusedTokens.push(n);_(e).charsLeftOver=u-l,0<o.length&&_(e).unusedInput.push(o),e._a[ge]<=12&&!0===_(e).bigHour&&0<e._a[ge]&&(_(e).bigHour=void 0),_(e).parsedDateParts=e._a.slice(0),_(e).meridiem=e._meridiem,e._a[ge]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):(null!=e.isPM&&((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0)),t)}(e._locale,e._a[ge],e._meridiem),ct(e),dt(e)}else St(e);else vt(e)}function Yt(e){var t,n,s=e._i,i=e._f;return e._locale=e._locale||lt(e._l),null===s||void 0===i&&""===s?g({nullInput:!0}):("string"==typeof s&&(e._i=s=e._locale.preparse(s)),M(s)?new w(dt(s)):(a(s)?e._d=s:o(i)?function(e){var t,n,s,i,r;if(0===e._f.length)return _(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<e._f.length;i++)r=0,t=v({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Dt(t),y(t)&&(r+=_(t).charsLeftOver,r+=10*_(t).unusedTokens.length,_(t).score=r,(null==s||r<s)&&(s=r,n=t));h(e,n||t)}(e):i?Dt(e):r(n=(t=e)._i)?t._d=new Date(c.now()):a(n)?t._d=new Date(n.valueOf()):"string"==typeof n?function(e){var t=pt.exec(e._i);null===t?(vt(e),!1===e._isValid&&(delete e._isValid,St(e),!1===e._isValid&&(delete e._isValid,c.createFromInputFallback(e)))):e._d=new Date(+t[1])}(t):o(n)?(t._a=d(n.slice(0),function(e){return parseInt(e,10)}),ct(t)):u(n)?function(e){var t;e._d||(t=F(e._i),e._a=d([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ct(e))}(t):l(n)?t._d=new Date(n):c.createFromInputFallback(t),y(e)||(e._d=null),e))}function Ot(e,t,n,s,i){var r,a={};return!0!==n&&!1!==n||(s=n,n=void 0),(u(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return;return 1}(e)||o(e)&&0===e.length)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=s,(r=new w(dt(Yt(a))))._nextDay&&(r.add(1,"d"),r._nextDay=void 0),r}function xt(e,t,n,s){return Ot(e,t,n,s,!1)}c.createFromInputFallback=n("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),c.ISO_8601=function(){},c.RFC_2822=function(){};var Tt=n("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=xt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:g()}),bt=n("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=xt.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:g()});function Pt(e,t){var n,s;if(1===t.length&&o(t[0])&&(t=t[0]),!t.length)return xt();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Rt(e){var t=F(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,d=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ye.call(Wt,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<Wt.length;++s)if(e[Wt[s]]){if(n)return!1;parseFloat(e[Wt[s]])!==S(e[Wt[s]])&&(n=!0)}return!0}(t),this._milliseconds=+d+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=lt(),this._bubble()}function Ct(e){return e instanceof Rt}function Ft(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ut(e,n){I(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+H(~~(e/60),2)+n+H(~~e%60,2)})}Ut("Z",":"),Ut("ZZ",""),ue("Z",re),ue("ZZ",re),ce(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Ht(re,e)});var Nt=/([\+\-]|\d\d)/gi;function Ht(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(Nt)||["-",0,0],i=60*s[1]+S(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Lt(e,t){var n,s;return t._isUTC?(n=t.clone(),s=(M(e)||a(e)?e.valueOf():xt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+s),c.updateOffset(n,!1),n):xt(e).local()}function Gt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Vt(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}c.updateOffset=function(){};var jt=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,It=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Et(e,t){var n,s,i,r=e,a=null;return Ct(e)?r={ms:e._milliseconds,d:e._days,M:e._months}:l(e)?(r={},t?r[t]=e:r.milliseconds=e):(a=jt.exec(e))?(n="-"===a[1]?-1:1,r={y:0,d:S(a[ye])*n,h:S(a[ge])*n,m:S(a[pe])*n,s:S(a[ve])*n,ms:S(Ft(1e3*a[we]))*n}):(a=It.exec(e))?(n="-"===a[1]?-1:(a[1],1),r={y:At(a[2],n),M:At(a[3],n),w:At(a[4],n),d:At(a[5],n),h:At(a[6],n),m:At(a[7],n),s:At(a[8],n)}):null==r?r={}:"object"==typeof r&&("from"in r||"to"in r)&&(i=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Lt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(xt(r.from),xt(r.to)),(r={}).ms=i.milliseconds,r.M=i.months),s=new Rt(r),Ct(e)&&f(e,"_locale")&&(s._locale=e._locale),s}function At(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function zt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=t-e.clone().add(n.months,"M"),n}function Zt(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(x(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),$t(this,Et(e="string"==typeof e?+e:e,t),s),this}}function $t(e,t,n,s){var i=t._milliseconds,r=Ft(t._days),a=Ft(t._months);e.isValid()&&(s=null==s||s,a&&Fe(e,Te(e,"Month")+a*n),r&&be(e,"Date",Te(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&c.updateOffset(e,r||a))}Et.fn=Rt.prototype,Et.invalid=function(){return Et(NaN)};var qt=Zt(1,"add"),Jt=Zt(-1,"subtract");function Bt(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months"),i=t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s);return-(n+i)||0}function Qt(e){var t;return void 0===e?this._locale._abbr:(null!=(t=lt(e))&&(this._locale=t),this)}c.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",c.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Xt=n("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}function en(e,t){I(0,[e,e.length],0,t)}function tn(e,t,n,s,i){var r;return null==e?Ie(this,s,i).year:((r=Ee(e,s,i))<t&&(t=r),function(e,t,n,s,i){var r=je(e,t,n,s,i),a=Ge(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}I(0,["gg",2],0,function(){return this.weekYear()%100}),I(0,["GG",2],0,function(){return this.isoWeekYear()%100}),en("gggg","weekYear"),en("ggggg","weekYear"),en("GGGG","isoWeekYear"),en("GGGGG","isoWeekYear"),R("weekYear","gg"),R("isoWeekYear","GG"),N("weekYear",1),N("isoWeekYear",1),ue("G",se),ue("g",se),ue("GG",B,Z),ue("gg",B,Z),ue("GGGG",ee,q),ue("gggg",ee,q),ue("GGGGG",te,J),ue("ggggg",te,J),fe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=S(e)}),fe(["gg","GG"],function(e,t,n,s){t[s]=c.parseTwoDigitYear(e)}),I("Q",0,"Qo","quarter"),R("quarter","Q"),N("quarter",7),ue("Q",z),ce("Q",function(e,t){t[_e]=3*(S(e)-1)}),I("D",["DD",2],"Do","date"),R("date","D"),N("date",9),ue("D",B),ue("DD",B,Z),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),ce(["D","DD"],ye),ce("Do",function(e,t){t[ye]=S(e.match(B)[0])});var nn=xe("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),R("dayOfYear","DDD"),N("dayOfYear",4),ue("DDD",K),ue("DDDD",$),ce(["DDD","DDDD"],function(e,t,n){n._dayOfYear=S(e)}),I("m",["mm",2],0,"minute"),R("minute","m"),N("minute",14),ue("m",B),ue("mm",B,Z),ce(["m","mm"],pe);var sn=xe("Minutes",!1);I("s",["ss",2],0,"second"),R("second","s"),N("second",15),ue("s",B),ue("ss",B,Z),ce(["s","ss"],ve);var rn,an=xe("Seconds",!1);for(I("S",0,0,function(){return~~(this.millisecond()/100)}),I(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,function(){return 10*this.millisecond()}),I(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),I(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),I(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),I(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),I(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),R("millisecond","ms"),N("millisecond",16),ue("S",K,z),ue("SS",K,Z),ue("SSS",K,$),rn="SSSS";rn.length<=9;rn+="S")ue(rn,ne);function on(e,t){t[we]=S(1e3*("0."+e))}for(rn="S";rn.length<=9;rn+="S")ce(rn,on);var un=xe("Milliseconds",!1);I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var ln=w.prototype;function dn(e){return e}ln.add=qt,ln.calendar=function(e,t){var n=e||xt(),s=Lt(n,this).startOf("day"),i=c.calendarFormat(this,s)||"sameElse",r=t&&(T(t[i])?t[i].call(this,n):t[i]);return this.format(r||this.localeData().calendar(i,this,xt(n)))},ln.clone=function(){return new w(this)},ln.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Lt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=C(t)){case"year":r=Bt(this,s)/12;break;case"month":r=Bt(this,s);break;case"quarter":r=Bt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:k(r)},ln.endOf=function(e){return void 0===(e=C(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},ln.format=function(e){e=e||(this.isUtc()?c.defaultFormatUtc:c.defaultFormat);var t=E(this,e);return this.localeData().postformat(t)},ln.from=function(e,t){return this.isValid()&&(M(e)&&e.isValid()||xt(e).isValid())?Et({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.fromNow=function(e){return this.from(xt(),e)},ln.to=function(e,t){return this.isValid()&&(M(e)&&e.isValid()||xt(e).isValid())?Et({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.toNow=function(e){return this.to(xt(),e)},ln.get=function(e){return T(this[e=C(e)])?this[e]():this},ln.invalidAt=function(){return _(this).overflow},ln.isAfter=function(e,t){var n=M(e)?e:xt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=C(r(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},ln.isBefore=function(e,t){var n=M(e)?e:xt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=C(r(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},ln.isBetween=function(e,t,n,s){return("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},ln.isSame=function(e,t){var n,s=M(e)?e:xt(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=C(t||"millisecond"))?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},ln.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},ln.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},ln.isValid=function(){return y(this)},ln.lang=Xt,ln.locale=Qt,ln.localeData=Kt,ln.max=bt,ln.min=Tt,ln.parsingFlags=function(){return h({},_(this))},ln.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:U[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=F(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(T(this[e=C(e)]))return this[e](t);return this},ln.startOf=function(e){switch(e=C(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},ln.subtract=Jt,ln.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},ln.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},ln.toDate=function(){return new Date(this.valueOf())},ln.toISOString=function(){if(!this.isValid())return null;var e=this.clone().utc();return e.year()<0||9999<e.year()?E(e,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):T(Date.prototype.toISOString)?this.toDate().toISOString():E(e,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},ln.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},ln.toJSON=function(){return this.isValid()?this.toISOString():null},ln.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},ln.unix=function(){return Math.floor(this.valueOf()/1e3)},ln.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},ln.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},ln.year=Oe,ln.isLeapYear=function(){return De(this.year())},ln.weekYear=function(e){return tn.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},ln.isoWeekYear=function(e){return tn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},ln.quarter=ln.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},ln.month=Ue,ln.daysInMonth=function(){return Pe(this.year(),this.month())},ln.week=ln.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},ln.isoWeek=ln.isoWeeks=function(e){var t=Ie(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},ln.weeksInYear=function(){var e=this.localeData()._week;return Ee(this.year(),e.dow,e.doy)},ln.isoWeeksInYear=function(){return Ee(this.year(),1,4)},ln.date=nn,ln.day=ln.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},ln.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},ln.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null==e)return this.day()||7;var t,n,s=(t=e,n=this.localeData(),"string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t);return this.day(this.day()%7?s:s-7)},ln.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},ln.hour=ln.hours=tt,ln.minute=ln.minutes=sn,ln.second=ln.seconds=an,ln.millisecond=ln.milliseconds=un,ln.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Gt(this);if("string"==typeof e){if(null===(e=Ht(re,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Gt(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?$t(this,Et(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,c.updateOffset(this,!0),this._changeInProgress=null)),this},ln.utc=function(e){return this.utcOffset(0,e)},ln.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Gt(this),"m")),this},ln.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Ht(ie,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},ln.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?xt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},ln.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},ln.isLocal=function(){return!!this.isValid()&&!this._isUTC},ln.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},ln.isUtc=Vt,ln.isUTC=Vt,ln.zoneAbbr=function(){return this._isUTC?"UTC":""},ln.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},ln.dates=n("dates accessor is deprecated. Use date instead.",nn),ln.months=n("months accessor is deprecated. Use month instead",Ue),ln.years=n("years accessor is deprecated. Use year instead",Oe),ln.zone=n("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),ln.isDSTShifted=n("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!r(this._isDSTShifted))return this._isDSTShifted;var e,t={};return v(t,this),(t=Yt(t))._a?(e=(t._isUTC?m:xt)(t._a),this._isDSTShifted=this.isValid()&&0<D(t._a,e.toArray())):this._isDSTShifted=!1,this._isDSTShifted});var hn=P.prototype;function cn(e,t,n,s){var i=lt(),r=m().set(s,t);return i[n](r,e)}function fn(e,t,n){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?l(t)&&(n=t,t=void 0):(t=e,e=!1,l(n=t)&&(n=t,t=void 0)),t||"");var i=lt(),r=e?i._week.dow:0;if(null!=n)return cn(t,(n+r)%7,s,"day");for(var a=[],o=0;o<7;o++)a[o]=cn(t,(o+r)%7,s,"day");return a}hn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return T(s)?s.call(t,n):s},hn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},hn.invalidDate=function(){return this._invalidDate},hn.ordinal=function(e){return this._ordinal.replace("%d",e)},hn.preparse=dn,hn.postformat=dn,hn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return T(i)?i(e,t,n,s):i.replace(/%d/i,e)},hn.pastFuture=function(e,t){var n=this._relativeTime[0<e?"future":"past"];return T(n)?n(t):n.replace(/%s/i,t)},hn.set=function(e){var t,n;for(n in e)T(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},hn.months=function(e,t){return e?o(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||We).test(t)?"format":"standalone"][e.month()]:o(this._months)?this._months:this._months.standalone},hn.monthsShort=function(e,t){return e?o(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[We.test(t)?"format":"standalone"][e.month()]:o(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},hn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=m([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))||-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))||-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=m([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},hn.monthsRegex=function(e){return this._monthsParseExact?(f(this,"_monthsRegex")||Le.call(this),e?this._monthsStrictRegex:this._monthsRegex):(f(this,"_monthsRegex")||(this._monthsRegex=He),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},hn.monthsShortRegex=function(e){return this._monthsParseExact?(f(this,"_monthsRegex")||Le.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(f(this,"_monthsShortRegex")||(this._monthsShortRegex=Ne),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},hn.week=function(e){return Ie(e,this._week.dow,this._week.doy).week},hn.firstDayOfYear=function(){return this._week.doy},hn.firstDayOfWeek=function(){return this._week.dow},hn.weekdays=function(e,t){return e?o(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:o(this._weekdays)?this._weekdays:this._weekdays.standalone},hn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},hn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},hn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=m([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._shortWeekdaysParse,a))||-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))||-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))||-1!==(i=Ye.call(this._weekdaysParse,a))||-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=m([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},hn.weekdaysRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(f(this,"_weekdaysRegex")||(this._weekdaysRegex=$e),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},hn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(f(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=qe),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},hn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(f(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Je),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},hn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},hn.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ot("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===S(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),c.lang=n("moment.lang is deprecated. Use moment.locale instead.",ot),c.langData=n("moment.langData is deprecated. Use moment.localeData instead.",lt);var _n=Math.abs;function yn(e,t,n,s){var i=Et(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function pn(e){return 4800*e/146097}function vn(e){return 146097*e/4800}function wn(e){return function(){return this.as(e)}}var Mn=wn("ms"),kn=wn("s"),Sn=wn("m"),Dn=wn("h"),Yn=wn("d"),On=wn("w"),xn=wn("M"),Tn=wn("y");function bn(e){return function(){return this.isValid()?this._data[e]:NaN}}var Pn=bn("milliseconds"),Wn=bn("seconds"),Rn=bn("minutes"),Cn=bn("hours"),Fn=bn("days"),Un=bn("months"),Nn=bn("years");var Hn=Math.round,Ln={ss:44,s:45,m:45,h:22,d:26,M:11};function Gn(e,t,n){var s=Et(e).abs(),i=Hn(s.as("s")),r=Hn(s.as("m")),a=Hn(s.as("h")),o=Hn(s.as("d")),u=Hn(s.as("M")),l=Hn(s.as("y")),d=(i<=Ln.ss?["s",i]:i<Ln.s&&["ss",i])||r<=1&&["m"]||r<Ln.m&&["mm",r]||a<=1&&["h"]||a<Ln.h&&["hh",a]||o<=1&&["d"]||o<Ln.d&&["dd",o]||u<=1&&["M"]||u<Ln.M&&["MM",u]||l<=1&&["y"]||["yy",l];return d[2]=t,d[3]=0<+e,d[4]=n,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,d)}var Vn=Math.abs;function jn(e){return(0<e)-(e<0)||+e}function In(){if(!this.isValid())return this.localeData().invalidDate();var e=Vn(this._milliseconds)/1e3,t=Vn(this._days),n=Vn(this._months),s=k(e/60),i=k(s/60);e%=60,s%=60;var r=k(n/12),a=n%=12,o=t,u=i,l=s,d=e?e.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return"P0D";var c=h<0?"-":"",f=jn(this._months)!==jn(h)?"-":"",m=jn(this._days)!==jn(h)?"-":"",_=jn(this._milliseconds)!==jn(h)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||d?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(d?_+d+"S":"")}var En=Rt.prototype;return En.isValid=function(){return this._isValid},En.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},En.add=function(e,t){return yn(this,e,t,1)},En.subtract=function(e,t){return yn(this,e,t,-1)},En.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=C(e))||"year"===e)return t=this._days+s/864e5,n=this._months+pn(t),"month"===e?n:n/12;switch(t=this._days+Math.round(vn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},En.asMilliseconds=Mn,En.asSeconds=kn,En.asMinutes=Sn,En.asHours=Dn,En.asDays=Yn,En.asWeeks=On,En.asMonths=xn,En.asYears=Tn,En.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*S(this._months/12):NaN},En._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return 0<=r&&0<=a&&0<=o||r<=0&&a<=0&&o<=0||(r+=864e5*gn(vn(o)+a),o=a=0),u.milliseconds=r%1e3,e=k(r/1e3),u.seconds=e%60,t=k(e/60),u.minutes=t%60,n=k(t/60),u.hours=n%24,a+=k(n/24),o+=i=k(pn(a)),a-=gn(vn(i)),s=k(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},En.clone=function(){return Et(this)},En.get=function(e){return e=C(e),this.isValid()?this[e+"s"]():NaN},En.milliseconds=Pn,En.seconds=Wn,En.minutes=Rn,En.hours=Cn,En.days=Fn,En.weeks=function(){return k(this.days()/7)},En.months=Un,En.years=Nn,En.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t=this.localeData(),n=Gn(this,!e,t);return e&&(n=t.pastFuture(+this,n)),t.postformat(n)},En.toISOString=In,En.toString=In,En.toJSON=In,En.locale=Qt,En.localeData=Kt,En.toIsoString=n("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",In),En.lang=Xt,I("X",0,0,"unix"),I("x",0,0,"valueOf"),ue("x",se),ue("X",/[+-]?\d+(\.\d{1,3})?/),ce("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),ce("x",function(e,t,n){n._d=new Date(S(e))}),c.version="2.19.1",e=xt,c.fn=ln,c.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},c.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},c.now=function(){return Date.now?Date.now():+new Date},c.utc=m,c.unix=function(e){return xt(1e3*e)},c.months=function(e,t){return fn(e,t,"months")},c.isDate=a,c.locale=ot,c.invalid=g,c.duration=Et,c.isMoment=M,c.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},c.parseZone=function(){return xt.apply(null,arguments).parseZone()},c.localeData=lt,c.isDuration=Ct,c.monthsShort=function(e,t){return fn(e,t,"monthsShort")},c.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},c.defineLocale=ut,c.updateLocale=function(e,t){var n,s;return null!=t?(s=nt,null!=st[e]&&(s=st[e]._config),(n=new P(t=b(s,t))).parentLocale=st[e],st[e]=n,ot(e)):null!=st[e]&&(null!=st[e].parentLocale?st[e]=st[e].parentLocale:null!=st[e]&&delete st[e]),st[e]},c.locales=function(){return s(st)},c.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},c.normalizeUnits=C,c.relativeTimeRounding=function(e){return void 0===e?Hn:"function"==typeof e&&(Hn=e,!0)},c.relativeTimeThreshold=function(e,t){return void 0!==Ln[e]&&(void 0===t?Ln[e]:(Ln[e]=t,"s"===e&&(Ln.ss=t-1),!0))},c.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},c.prototype=ln,c});
be
main.go
/* Package best_time_to_buy_and_sell_stock_iii https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/ 123. 买卖股票的最佳时机 III 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 提示: 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^5 */ package best_time_to_buy_and_sell_stock_iii import "math" // --- 自己 /* 方法一: 动态规划 时间复杂度: 空间复杂度: */ func maxProfit(prices []int) int { if len(prices) <= 1 { return 0 } maxK := 2 dp := make([][3][2]int, len(prices)) for i := 0; i < len(prices); i++ { for k := 1; k <= maxK; k++ { if i == 0 { dp[i][k][0] = 0 dp[i][k][1] = -prices[i] continue } dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1]+prices[i]) dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0]-prices[i]) } } return dp[len(prices)-1][maxK][0] } func max(x, y int) int { if x > y { return x } return y } /* 方法一: 动态规划优化 时间复杂度: 空间复杂度: */ func maxProfitS1(prices []int) int { sell1, sell2 := 0, 0 buy1, buy2 := math.MinInt64, math.MinInt64 for _, price := range prices { sell2 = max(sell2, buy2+price) buy2 = max(buy2, sell1-price) sell1 = max(sell1, buy1+price) buy1 = max(buy1, -price) } return sell2 }
serviceusage-gen.go
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated file. DO NOT EDIT. // Package serviceusage provides access to the Service Usage API. // // For product documentation, see: https://cloud.google.com/service-usage/ // // Creating a client // // Usage example: // // import "google.golang.org/api/serviceusage/v1beta1" // ... // ctx := context.Background() // serviceusageService, err := serviceusage.NewService(ctx) // // In this example, Google Application Default Credentials are used for authentication. // // For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials. // // Other authentication options // // By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes: // // serviceusageService, err := serviceusage.NewService(ctx, option.WithScopes(serviceusage.ServiceManagementScope)) // // To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey: // // serviceusageService, err := serviceusage.NewService(ctx, option.WithAPIKey("AIza...")) // // To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource: // // config := &oauth2.Config{...} // // ... // token, err := config.Exchange(ctx, ...) // serviceusageService, err := serviceusage.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) // // See https://godoc.org/google.golang.org/api/option/ for details on options. package serviceusage // import "google.golang.org/api/serviceusage/v1beta1" import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" googleapi "google.golang.org/api/googleapi" gensupport "google.golang.org/api/internal/gensupport" option "google.golang.org/api/option" internaloption "google.golang.org/api/option/internaloption" htransport "google.golang.org/api/transport/http" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = internaloption.WithDefaultEndpoint const apiId = "serviceusage:v1beta1" const apiName = "serviceusage" const apiVersion = "v1beta1" const basePath = "https://serviceusage.googleapis.com/" const mtlsBasePath = "https://serviceusage.mtls.googleapis.com/" // OAuth2 scopes used by this API. const ( // View and manage your data across Google Cloud Platform services CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" // View your data across Google Cloud Platform services CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only" // Manage your Google API service configuration ServiceManagementScope = "https://www.googleapis.com/auth/service.management" ) // NewService creates a new APIService. func NewService(ctx context.Context, opts ...option.ClientOption) (*APIService, error) { scopesOption := option.WithScopes( "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/service.management", ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) opts = append(opts, internaloption.WithDefaultEndpoint(basePath)) opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath)) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err } s, err := New(client) if err != nil { return nil, err } if endpoint != "" { s.BasePath = endpoint } return s, nil } // New creates a new APIService. It uses the provided http.Client for requests. // // Deprecated: please use NewService instead. // To provide a custom HTTP client, use option.WithHTTPClient. // If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead. func New(client *http.Client) (*APIService, error) { if client == nil { return nil, errors.New("client is nil") } s := &APIService{client: client, BasePath: basePath} s.Operations = NewOperationsService(s) s.Services = NewServicesService(s) return s, nil } type APIService struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Operations *OperationsService Services *ServicesService } func (s *APIService) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewOperationsService(s *APIService) *OperationsService
type OperationsService struct { s *APIService } func NewServicesService(s *APIService) *ServicesService { rs := &ServicesService{s: s} rs.ConsumerQuotaMetrics = NewServicesConsumerQuotaMetricsService(s) return rs } type ServicesService struct { s *APIService ConsumerQuotaMetrics *ServicesConsumerQuotaMetricsService } func NewServicesConsumerQuotaMetricsService(s *APIService) *ServicesConsumerQuotaMetricsService { rs := &ServicesConsumerQuotaMetricsService{s: s} rs.Limits = NewServicesConsumerQuotaMetricsLimitsService(s) return rs } type ServicesConsumerQuotaMetricsService struct { s *APIService Limits *ServicesConsumerQuotaMetricsLimitsService } func NewServicesConsumerQuotaMetricsLimitsService(s *APIService) *ServicesConsumerQuotaMetricsLimitsService { rs := &ServicesConsumerQuotaMetricsLimitsService{s: s} rs.AdminOverrides = NewServicesConsumerQuotaMetricsLimitsAdminOverridesService(s) rs.ConsumerOverrides = NewServicesConsumerQuotaMetricsLimitsConsumerOverridesService(s) return rs } type ServicesConsumerQuotaMetricsLimitsService struct { s *APIService AdminOverrides *ServicesConsumerQuotaMetricsLimitsAdminOverridesService ConsumerOverrides *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService } func NewServicesConsumerQuotaMetricsLimitsAdminOverridesService(s *APIService) *ServicesConsumerQuotaMetricsLimitsAdminOverridesService { rs := &ServicesConsumerQuotaMetricsLimitsAdminOverridesService{s: s} return rs } type ServicesConsumerQuotaMetricsLimitsAdminOverridesService struct { s *APIService } func NewServicesConsumerQuotaMetricsLimitsConsumerOverridesService(s *APIService) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService { rs := &ServicesConsumerQuotaMetricsLimitsConsumerOverridesService{s: s} return rs } type ServicesConsumerQuotaMetricsLimitsConsumerOverridesService struct { s *APIService } // AdminQuotaPolicy: Quota policy created by quota administrator. type AdminQuotaPolicy struct { // Container: The cloud resource container at which the quota policy is // created. The format is {container_type}/{container_number} Container string `json:"container,omitempty"` // Dimensions: If this map is nonempty, then this policy applies only // to specific values for dimensions defined in the limit unit. For // example, an policy on a limit with the unit 1/{project}/{region} // could contain an entry with the key "region" and the value // "us-east-1"; the policy is only applied to quota consumed in that // region. This map has the following restrictions: * If "region" // appears as a key, its value must be a valid Cloud region. * If "zone" // appears as a key, its value must be a valid Cloud zone. * Keys other // than "region" or "zone" are not valid. Dimensions map[string]string `json:"dimensions,omitempty"` // Metric: The name of the metric to which this policy applies. An // example name would be: `compute.googleapis.com/cpus` Metric string `json:"metric,omitempty"` // Name: The resource name of the policy. This name is generated by the // server when the policy is created. Example names would be: // `organizations/123/services/compute.googleapis.com/consumerQuotaMetric // s/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminQuotaP // olicies/4a3f2c1d` Name string `json:"name,omitempty"` // PolicyValue: The quota policy value. Can be any nonnegative integer, // or -1 (unlimited quota). PolicyValue int64 `json:"policyValue,omitempty,string"` // Unit: The limit unit of the limit to which this policy applies. An // example unit would be: `1/{project}/{region}` Note that `{project}` // and `{region}` are not placeholders in this example; the literal // characters `{` and `}` occur in the string. Unit string `json:"unit,omitempty"` // ForceSendFields is a list of field names (e.g. "Container") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Container") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *AdminQuotaPolicy) MarshalJSON() ([]byte, error) { type NoMethod AdminQuotaPolicy raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Api: Api is a light-weight descriptor for an API Interface. // Interfaces are also described as "protocol buffer services" in some // contexts, such as by the "service" keyword in a .proto file, but they // are different from API Services, which represent a concrete // implementation of an interface as opposed to simply a description of // methods and bindings. They are also sometimes simply referred to as // "APIs" in other contexts, such as the name of this message itself. // See https://cloud.google.com/apis/design/glossary for detailed // terminology. type Api struct { // Methods: The methods of this interface, in unspecified order. Methods []*Method `json:"methods,omitempty"` // Mixins: Included interfaces. See Mixin. Mixins []*Mixin `json:"mixins,omitempty"` // Name: The fully qualified name of this interface, including package // name followed by the interface's simple name. Name string `json:"name,omitempty"` // Options: Any metadata attached to the interface. Options []*Option `json:"options,omitempty"` // SourceContext: Source context for the protocol buffer service // represented by this message. SourceContext *SourceContext `json:"sourceContext,omitempty"` // Syntax: The source syntax of the service. // // Possible values: // "SYNTAX_PROTO2" - Syntax `proto2`. // "SYNTAX_PROTO3" - Syntax `proto3`. Syntax string `json:"syntax,omitempty"` // Version: A version string for this interface. If specified, must have // the form `major-version.minor-version`, as in `1.10`. If the minor // version is omitted, it defaults to zero. If the entire version field // is empty, the major version is derived from the package name, as // outlined below. If the field is not empty, the version in the package // name will be verified to be consistent with what is provided here. // The versioning schema uses [semantic versioning](http://semver.org) // where the major version number indicates a breaking change and the // minor version an additive, non-breaking change. Both version numbers // are signals to users what to expect from different versions, and // should be carefully chosen based on the product plan. The major // version is also reflected in the package name of the interface, which // must end in `v`, as in `google.feature.v1`. For major versions 0 and // 1, the suffix can be omitted. Zero major versions must only be used // for experimental, non-GA interfaces. Version string `json:"version,omitempty"` // ForceSendFields is a list of field names (e.g. "Methods") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Methods") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Api) MarshalJSON() ([]byte, error) { type NoMethod Api raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // AuthProvider: Configuration for an authentication provider, including // support for [JSON Web Token // (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32) // . type AuthProvider struct { // Audiences: The list of JWT // [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-toke // n-32#section-4.1.3). that are allowed to access. A JWT containing any // of these audiences will be accepted. When this setting is absent, // JWTs with audiences: - // "https://[service.name]/[google.protobuf.Api.name]" - // "https://[service.name]/" will be accepted. For example, if no // audiences are in the setting, LibraryService API will accept JWTs // with the following audiences: - // https://library-example.googleapis.com/google.example.library.v1.LibraryService - https://library-example.googleapis.com/ Example: audiences: bookstore_android.apps.googleusercontent.com, // bookstore_web.apps.googleusercontent.com Audiences string `json:"audiences,omitempty"` // AuthorizationUrl: Redirect URL if JWT token is required but not // present or is expired. Implement authorizationUrl of // securityDefinitions in OpenAPI spec. AuthorizationUrl string `json:"authorizationUrl,omitempty"` // Id: The unique identifier of the auth provider. It will be referred // to by `AuthRequirement.provider_id`. Example: "bookstore_auth". Id string `json:"id,omitempty"` // Issuer: Identifies the principal that issued the JWT. See // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1 Usually a URL or an email address. Example: https://securetoken.google.com Example: // [email protected] Issuer string `json:"issuer,omitempty"` // JwksUri: URL of the provider's public key set to validate signature // of the JWT. See [OpenID // Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html# // ProviderMetadata). Optional if the key set document: - can be // retrieved from [OpenID // Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html // of the issuer. - can be inferred from the email domain of the issuer // (e.g. a Google service account). Example: // https://www.googleapis.com/oauth2/v1/certs JwksUri string `json:"jwksUri,omitempty"` // JwtLocations: Defines the locations to extract the JWT. JWT locations // can be either from HTTP headers or URL query parameters. The rule is // that the first match wins. The checking order is: checking all // headers first, then URL query parameters. If not specified, default // to use following 3 locations: 1) Authorization: Bearer 2) // x-goog-iap-jwt-assertion 3) access_token query parameter Default // locations can be specified as followings: jwt_locations: - header: // Authorization value_prefix: "Bearer " - header: // x-goog-iap-jwt-assertion - query: access_token JwtLocations []*JwtLocation `json:"jwtLocations,omitempty"` // ForceSendFields is a list of field names (e.g. "Audiences") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Audiences") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *AuthProvider) MarshalJSON() ([]byte, error) { type NoMethod AuthProvider raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // AuthRequirement: User-defined authentication requirements, including // support for [JSON Web Token // (JWT)](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32) // . type AuthRequirement struct { // Audiences: NOTE: This will be deprecated soon, once // AuthProvider.audiences is implemented and accepted in all the runtime // components. The list of JWT // [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-toke // n-32#section-4.1.3). that are allowed to access. A JWT containing any // of these audiences will be accepted. When this setting is absent, // only JWTs with audience "https://Service_name/API_name" will be // accepted. For example, if no audiences are in the setting, // LibraryService API will only accept JWTs with the following audience // "https://library-example.googleapis.com/google.example.library.v1.Libr // aryService". Example: audiences: // bookstore_android.apps.googleusercontent.com, // bookstore_web.apps.googleusercontent.com Audiences string `json:"audiences,omitempty"` // ProviderId: id from authentication provider. Example: provider_id: // bookstore_auth ProviderId string `json:"providerId,omitempty"` // ForceSendFields is a list of field names (e.g. "Audiences") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Audiences") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *AuthRequirement) MarshalJSON() ([]byte, error) { type NoMethod AuthRequirement raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Authentication: `Authentication` defines the authentication // configuration for an API. Example for an API targeted for external // use: name: calendar.googleapis.com authentication: providers: - id: // google_calendar_auth jwks_uri: // https://www.googleapis.com/oauth2/v1/certs issuer: // https://securetoken.google.com rules: - selector: "*" requirements: // provider_id: google_calendar_auth type Authentication struct { // Providers: Defines a set of authentication providers that a service // supports. Providers []*AuthProvider `json:"providers,omitempty"` // Rules: A list of authentication rules that apply to individual API // methods. **NOTE:** All service configuration rules follow "last one // wins" order. Rules []*AuthenticationRule `json:"rules,omitempty"` // ForceSendFields is a list of field names (e.g. "Providers") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Providers") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Authentication) MarshalJSON() ([]byte, error) { type NoMethod Authentication raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // AuthenticationRule: Authentication rules for the service. By default, // if a method has any authentication requirements, every request must // include a valid credential matching one of the requirements. It's an // error to include more than one kind of credential in a single // request. If a method doesn't have any auth requirements, request // credentials will be ignored. type AuthenticationRule struct { // AllowWithoutCredential: If true, the service accepts API keys without // any other credential. This flag only applies to HTTP and gRPC // requests. AllowWithoutCredential bool `json:"allowWithoutCredential,omitempty"` // Oauth: The requirements for OAuth credentials. Oauth *OAuthRequirements `json:"oauth,omitempty"` // Requirements: Requirements for additional authentication providers. Requirements []*AuthRequirement `json:"requirements,omitempty"` // Selector: Selects the methods to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. // "AllowWithoutCredential") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AllowWithoutCredential") // to include in API requests with the JSON null value. By default, // fields with empty values are omitted from API requests. However, any // field with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *AuthenticationRule) MarshalJSON() ([]byte, error) { type NoMethod AuthenticationRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Backend: `Backend` defines the backend configuration for a service. type Backend struct { // Rules: A list of API backend rules that apply to individual API // methods. **NOTE:** All service configuration rules follow "last one // wins" order. Rules []*BackendRule `json:"rules,omitempty"` // ForceSendFields is a list of field names (e.g. "Rules") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Rules") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Backend) MarshalJSON() ([]byte, error) { type NoMethod Backend raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // BackendRule: A backend rule provides configuration for an individual // API element. type BackendRule struct { // Address: The address of the API backend. The scheme is used to // determine the backend protocol and security. The following schemes // are accepted: SCHEME PROTOCOL SECURITY http:// HTTP None https:// // HTTP TLS grpc:// gRPC None grpcs:// gRPC TLS It is recommended to // explicitly include a scheme. Leaving out the scheme may cause // constrasting behaviors across platforms. If the port is unspecified, // the default is: - 80 for schemes without TLS - 443 for schemes with // TLS For HTTP backends, use protocol to specify the protocol version. Address string `json:"address,omitempty"` // Deadline: The number of seconds to wait for a response from a // request. The default varies based on the request protocol and // deployment environment. Deadline float64 `json:"deadline,omitempty"` // DisableAuth: When disable_auth is true, a JWT ID token won't be // generated and the original "Authorization" HTTP header will be // preserved. If the header is used to carry the original token and is // expected by the backend, this field must be set to true to preserve // the header. DisableAuth bool `json:"disableAuth,omitempty"` // JwtAudience: The JWT audience is used when generating a JWT ID token // for the backend. This ID token will be added in the HTTP // "authorization" header, and sent to the backend. JwtAudience string `json:"jwtAudience,omitempty"` // MinDeadline: Minimum deadline in seconds needed for this method. // Calls having deadline value lower than this will be rejected. MinDeadline float64 `json:"minDeadline,omitempty"` // OperationDeadline: The number of seconds to wait for the completion // of a long running operation. The default is no deadline. OperationDeadline float64 `json:"operationDeadline,omitempty"` // Possible values: // "PATH_TRANSLATION_UNSPECIFIED" // "CONSTANT_ADDRESS" - Use the backend address as-is, with no // modification to the path. If the URL pattern contains variables, the // variable names and values will be appended to the query string. If a // query string parameter and a URL pattern variable have the same name, // this may result in duplicate keys in the query string. # Examples // Given the following operation config: Method path: // /api/company/{cid}/user/{uid} Backend address: // https://example.cloudfunctions.net/getUser Requests to the following // request paths will call the backend at the translated path: Request // path: /api/company/widgetworks/user/johndoe Translated: // https://example.cloudfunctions.net/getUser?cid=widgetworks&uid=johndoe Request path: /api/company/widgetworks/user/johndoe?timezone=EST Translated: // https://example.cloudfunctions.net/getUser?timezone=EST&cid=widgetworks&uid=johndoe // "APPEND_PATH_TO_ADDRESS" - The request path will be appended to the // backend address. # Examples Given the following operation config: // Method path: /api/company/{cid}/user/{uid} Backend address: // https://example.appspot.com Requests to the following request paths // will call the backend at the translated path: Request path: // /api/company/widgetworks/user/johndoe Translated: // https://example.appspot.com/api/company/widgetworks/user/johndoe // Request path: /api/company/widgetworks/user/johndoe?timezone=EST // Translated: // https://example.appspot.com/api/company/widgetworks/user/johndoe?timezone=EST PathTranslation string `json:"pathTranslation,omitempty"` // Protocol: The protocol used for sending a request to the backend. The // supported values are "http/1.1" and "h2". The default value is // inferred from the scheme in the address field: SCHEME PROTOCOL // http:// http/1.1 https:// http/1.1 grpc:// h2 grpcs:// h2 For secure // HTTP backends (https://) that support HTTP/2, set this field to "h2" // for improved performance. Configuring this field to non-default // values is only supported for secure HTTP backends. This field will be // ignored for all other backends. See // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids for more details on the supported // values. Protocol string `json:"protocol,omitempty"` // Selector: Selects the methods to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. "Address") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Address") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BackendRule) MarshalJSON() ([]byte, error) { type NoMethod BackendRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } func (s *BackendRule) UnmarshalJSON(data []byte) error { type NoMethod BackendRule var s1 struct { Deadline gensupport.JSONFloat64 `json:"deadline"` MinDeadline gensupport.JSONFloat64 `json:"minDeadline"` OperationDeadline gensupport.JSONFloat64 `json:"operationDeadline"` *NoMethod } s1.NoMethod = (*NoMethod)(s) if err := json.Unmarshal(data, &s1); err != nil { return err } s.Deadline = float64(s1.Deadline) s.MinDeadline = float64(s1.MinDeadline) s.OperationDeadline = float64(s1.OperationDeadline) return nil } // BatchCreateAdminOverridesResponse: Response message for // BatchCreateAdminOverrides type BatchCreateAdminOverridesResponse struct { // Overrides: The overrides that were created. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ForceSendFields is a list of field names (e.g. "Overrides") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Overrides") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BatchCreateAdminOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod BatchCreateAdminOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // BatchCreateConsumerOverridesResponse: Response message for // BatchCreateConsumerOverrides type BatchCreateConsumerOverridesResponse struct { // Overrides: The overrides that were created. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ForceSendFields is a list of field names (e.g. "Overrides") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Overrides") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BatchCreateConsumerOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod BatchCreateConsumerOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // BatchEnableServicesRequest: Request message for the // `BatchEnableServices` method. type BatchEnableServicesRequest struct { // ServiceIds: The identifiers of the services to enable on the project. // A valid identifier would be: serviceusage.googleapis.com Enabling // services requires that each service is public or is shared with the // user enabling the service. Two or more services must be specified. To // enable a single service, use the `EnableService` method instead. A // single request can enable a maximum of 20 services at a time. If more // than 20 services are specified, the request will fail, and no state // changes will occur. ServiceIds []string `json:"serviceIds,omitempty"` // ForceSendFields is a list of field names (e.g. "ServiceIds") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ServiceIds") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BatchEnableServicesRequest) MarshalJSON() ([]byte, error) { type NoMethod BatchEnableServicesRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // BatchEnableServicesResponse: Response message for the // `BatchEnableServices` method. This response message is assigned to // the `response` field of the returned Operation when that operation is // done. type BatchEnableServicesResponse struct { // Failures: If allow_partial_success is true, and one or more services // could not be enabled, this field contains the details about each // failure. Failures []*EnableFailure `json:"failures,omitempty"` // Services: The new state of the services after enabling. Services []*GoogleApiServiceusageV1Service `json:"services,omitempty"` // ForceSendFields is a list of field names (e.g. "Failures") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Failures") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BatchEnableServicesResponse) MarshalJSON() ([]byte, error) { type NoMethod BatchEnableServicesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Billing: Billing related configuration of the service. The following // example shows how to configure monitored resources and metrics for // billing, `consumer_destinations` is the only supported destination // and the monitored resources need at least one label key // `cloud.googleapis.com/location` to indicate the location of the // billing usage, using different monitored resources between monitoring // and billing is recommended so they can be evolved independently: // monitored_resources: - type: library.googleapis.com/billing_branch // labels: - key: cloud.googleapis.com/location description: | // Predefined label to support billing location restriction. - key: city // description: | Custom label to define the city where the library // branch is located in. - key: name description: Custom label to define // the name of the library branch. metrics: - name: // library.googleapis.com/book/borrowed_count metric_kind: DELTA // value_type: INT64 unit: "1" billing: consumer_destinations: - // monitored_resource: library.googleapis.com/billing_branch metrics: - // library.googleapis.com/book/borrowed_count type Billing struct { // ConsumerDestinations: Billing configurations for sending metrics to // the consumer project. There can be multiple consumer destinations per // service, each one must have a different monitored resource type. A // metric can be used in at most one consumer destination. ConsumerDestinations []*BillingDestination `json:"consumerDestinations,omitempty"` // ForceSendFields is a list of field names (e.g. // "ConsumerDestinations") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ConsumerDestinations") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *Billing) MarshalJSON() ([]byte, error) { type NoMethod Billing raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // BillingDestination: Configuration of a specific billing destination // (Currently only support bill against consumer project). type BillingDestination struct { // Metrics: Names of the metrics to report to this billing destination. // Each name must be defined in Service.metrics section. Metrics []string `json:"metrics,omitempty"` // MonitoredResource: The monitored resource type. The type must be // defined in Service.monitored_resources section. MonitoredResource string `json:"monitoredResource,omitempty"` // ForceSendFields is a list of field names (e.g. "Metrics") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Metrics") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *BillingDestination) MarshalJSON() ([]byte, error) { type NoMethod BillingDestination raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ConsumerQuotaLimit: Consumer quota settings for a quota limit. type ConsumerQuotaLimit struct { // AllowsAdminOverrides: Whether admin overrides are allowed on this // limit AllowsAdminOverrides bool `json:"allowsAdminOverrides,omitempty"` // IsPrecise: Whether this limit is precise or imprecise. IsPrecise bool `json:"isPrecise,omitempty"` // Metric: The name of the parent metric of this limit. An example name // would be: `compute.googleapis.com/cpus` Metric string `json:"metric,omitempty"` // Name: The resource name of the quota limit. An example name would be: // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/com // pute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion` The resource // name is intended to be opaque and should not be parsed for its // component strings, since its representation could change in the // future. Name string `json:"name,omitempty"` // QuotaBuckets: Summary of the enforced quota buckets, organized by // quota dimension, ordered from least specific to most specific (for // example, the global default bucket, with no quota dimensions, will // always appear first). QuotaBuckets []*QuotaBucket `json:"quotaBuckets,omitempty"` // Unit: The limit unit. An example unit would be `1/{project}/{region}` // Note that `{project}` and `{region}` are not placeholders in this // example; the literal characters `{` and `}` occur in the string. Unit string `json:"unit,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. // "AllowsAdminOverrides") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AllowsAdminOverrides") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *ConsumerQuotaLimit) MarshalJSON() ([]byte, error) { type NoMethod ConsumerQuotaLimit raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ConsumerQuotaMetric: Consumer quota settings for a quota metric. type ConsumerQuotaMetric struct { // ConsumerQuotaLimits: The consumer quota for each quota limit defined // on the metric. ConsumerQuotaLimits []*ConsumerQuotaLimit `json:"consumerQuotaLimits,omitempty"` // DisplayName: The display name of the metric. An example name would // be: "CPUs" DisplayName string `json:"displayName,omitempty"` // Metric: The name of the metric. An example name would be: // `compute.googleapis.com/cpus` Metric string `json:"metric,omitempty"` // Name: The resource name of the quota settings on this metric for this // consumer. An example name would be: // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/com // pute.googleapis.com%2Fcpus The resource name is intended to be opaque // and should not be parsed for its component strings, since its // representation could change in the future. Name string `json:"name,omitempty"` // Unit: The units in which the metric value is reported. Unit string `json:"unit,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "ConsumerQuotaLimits") // to unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ConsumerQuotaLimits") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *ConsumerQuotaMetric) MarshalJSON() ([]byte, error) { type NoMethod ConsumerQuotaMetric raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Context: `Context` defines which contexts an API requests. Example: // context: rules: - selector: "*" requested: - // google.rpc.context.ProjectContext - google.rpc.context.OriginContext // The above specifies that all methods in the API request // `google.rpc.context.ProjectContext` and // `google.rpc.context.OriginContext`. Available context types are // defined in package `google.rpc.context`. This also provides mechanism // to allowlist any protobuf message extension that can be sent in grpc // metadata using “x-goog-ext--bin” and “x-goog-ext--jspb” // format. For example, list any service specific protobuf types that // can appear in grpc metadata as follows in your yaml file: Example: // context: rules: - selector: // "google.example.library.v1.LibraryService.CreateBook" // allowed_request_extensions: - google.foo.v1.NewExtension // allowed_response_extensions: - google.foo.v1.NewExtension You can // also specify extension ID instead of fully qualified extension name // here. type Context struct { // Rules: A list of RPC context rules that apply to individual API // methods. **NOTE:** All service configuration rules follow "last one // wins" order. Rules []*ContextRule `json:"rules,omitempty"` // ForceSendFields is a list of field names (e.g. "Rules") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Rules") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Context) MarshalJSON() ([]byte, error) { type NoMethod Context raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ContextRule: A context rule provides information about the context // for an individual API element. type ContextRule struct { // AllowedRequestExtensions: A list of full type names or extension IDs // of extensions allowed in grpc side channel from client to backend. AllowedRequestExtensions []string `json:"allowedRequestExtensions,omitempty"` // AllowedResponseExtensions: A list of full type names or extension IDs // of extensions allowed in grpc side channel from backend to client. AllowedResponseExtensions []string `json:"allowedResponseExtensions,omitempty"` // Provided: A list of full type names of provided contexts. Provided []string `json:"provided,omitempty"` // Requested: A list of full type names of requested contexts. Requested []string `json:"requested,omitempty"` // Selector: Selects the methods to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. // "AllowedRequestExtensions") to unconditionally include in API // requests. By default, fields with empty values are omitted from API // requests. However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AllowedRequestExtensions") // to include in API requests with the JSON null value. By default, // fields with empty values are omitted from API requests. However, any // field with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *ContextRule) MarshalJSON() ([]byte, error) { type NoMethod ContextRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Control: Selects and configures the service controller used by the // service. The service controller handles features like abuse, quota, // billing, logging, monitoring, etc. type Control struct { // Environment: The service control environment to use. If empty, no // control plane feature (like quota and billing) will be enabled. Environment string `json:"environment,omitempty"` // ForceSendFields is a list of field names (e.g. "Environment") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Environment") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Control) MarshalJSON() ([]byte, error) { type NoMethod Control raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // CustomError: Customize service error responses. For example, list any // service specific protobuf types that can appear in error detail lists // of error responses. Example: custom_error: types: - // google.foo.v1.CustomError - google.foo.v1.AnotherError type CustomError struct { // Rules: The list of custom error rules that apply to individual API // messages. **NOTE:** All service configuration rules follow "last one // wins" order. Rules []*CustomErrorRule `json:"rules,omitempty"` // Types: The list of custom error detail types, e.g. // 'google.foo.v1.CustomError'. Types []string `json:"types,omitempty"` // ForceSendFields is a list of field names (e.g. "Rules") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Rules") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *CustomError) MarshalJSON() ([]byte, error) { type NoMethod CustomError raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // CustomErrorRule: A custom error rule. type CustomErrorRule struct { // IsErrorType: Mark this message as possible payload in error response. // Otherwise, objects of this type will be filtered when they appear in // error payload. IsErrorType bool `json:"isErrorType,omitempty"` // Selector: Selects messages to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. "IsErrorType") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "IsErrorType") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *CustomErrorRule) MarshalJSON() ([]byte, error) { type NoMethod CustomErrorRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // CustomHttpPattern: A custom pattern is used for defining custom HTTP // verb. type CustomHttpPattern struct { // Kind: The name of this custom HTTP verb. Kind string `json:"kind,omitempty"` // Path: The path matched by this custom verb. Path string `json:"path,omitempty"` // ForceSendFields is a list of field names (e.g. "Kind") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Kind") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *CustomHttpPattern) MarshalJSON() ([]byte, error) { type NoMethod CustomHttpPattern raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // DisableServiceRequest: Request message for the `DisableService` // method. type DisableServiceRequest struct { } // DisableServiceResponse: Response message for the `DisableService` // method. This response message is assigned to the `response` field of // the returned Operation when that operation is done. type DisableServiceResponse struct { // Service: The new state of the service after disabling. Service *GoogleApiServiceusageV1Service `json:"service,omitempty"` // ForceSendFields is a list of field names (e.g. "Service") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Service") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *DisableServiceResponse) MarshalJSON() ([]byte, error) { type NoMethod DisableServiceResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Documentation: `Documentation` provides the information for // describing a service. Example: documentation: summary: > The Google // Calendar API gives access to most calendar features. pages: - name: // Overview content: (== include google/foo/overview.md ==) - name: // Tutorial content: (== include google/foo/tutorial.md ==) subpages; - // name: Java content: (== include google/foo/tutorial_java.md ==) // rules: - selector: google.calendar.Calendar.Get description: > ... - // selector: google.calendar.Calendar.Put description: > ... // Documentation is provided in markdown syntax. In addition to standard // markdown features, definition lists, tables and fenced code blocks // are supported. Section headers can be provided and are interpreted // relative to the section nesting of the context where a documentation // fragment is embedded. Documentation from the IDL is merged with // documentation defined via the config at normalization time, where // documentation provided by config rules overrides IDL provided. A // number of constructs specific to the API platform are supported in // documentation text. In order to reference a proto element, the // following notation can be used: [fully.qualified.proto.name][] To // override the display text used for the link, this can be used: // [display text][fully.qualified.proto.name] Text can be excluded from // doc using the following notation: (-- internal comment --) A few // directives are available in documentation. Note that directives must // appear on a single line to be properly identified. The `include` // directive includes a markdown file from an external source: (== // include path/to/file ==) The `resource_for` directive marks a message // to be the resource of a collection in REST view. If it is not // specified, tools attempt to infer the resource from the operations in // a collection: (== resource_for v1.shelves.books ==) The directive // `suppress_warning` does not directly affect documentation and is // documented together with service config validation. type Documentation struct { // DocumentationRootUrl: The URL to the root of documentation. DocumentationRootUrl string `json:"documentationRootUrl,omitempty"` // Overview: Declares a single overview page. For example: // documentation: summary: ... overview: (== include overview.md ==) // This is a shortcut for the following declaration (using pages style): // documentation: summary: ... pages: - name: Overview content: (== // include overview.md ==) Note: you cannot specify both `overview` // field and `pages` field. Overview string `json:"overview,omitempty"` // Pages: The top level pages for the documentation set. Pages []*Page `json:"pages,omitempty"` // Rules: A list of documentation rules that apply to individual API // elements. **NOTE:** All service configuration rules follow "last one // wins" order. Rules []*DocumentationRule `json:"rules,omitempty"` // ServiceRootUrl: Specifies the service root url if the default one // (the service name from the yaml file) is not suitable. This can be // seen in any fully specified service urls as well as sections that // show a base that other urls are relative to. ServiceRootUrl string `json:"serviceRootUrl,omitempty"` // Summary: A short summary of what the service does. Can only be // provided by plain text. Summary string `json:"summary,omitempty"` // ForceSendFields is a list of field names (e.g. // "DocumentationRootUrl") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "DocumentationRootUrl") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *Documentation) MarshalJSON() ([]byte, error) { type NoMethod Documentation raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // DocumentationRule: A documentation rule provides information about // individual API elements. type DocumentationRule struct { // DeprecationDescription: Deprecation description of the selected // element(s). It can be provided if an element is marked as // `deprecated`. DeprecationDescription string `json:"deprecationDescription,omitempty"` // Description: Description of the selected API(s). Description string `json:"description,omitempty"` // Selector: The selector is a comma-separated list of patterns. Each // pattern is a qualified name of the element which may end in "*", // indicating a wildcard. Wildcards are only allowed at the end and for // a whole component of the qualified name, i.e. "foo.*" is ok, but not // "foo.b*" or "foo.*.bar". A wildcard will match one or more // components. To specify a default for all applicable elements, the // whole pattern "*" is used. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. // "DeprecationDescription") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "DeprecationDescription") // to include in API requests with the JSON null value. By default, // fields with empty values are omitted from API requests. However, any // field with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *DocumentationRule) MarshalJSON() ([]byte, error) { type NoMethod DocumentationRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Empty: A generic empty message that you can re-use to avoid defining // duplicated empty messages in your APIs. A typical example is to use // it as the request or the response type of an API method. For // instance: service Foo { rpc Bar(google.protobuf.Empty) returns // (google.protobuf.Empty); } The JSON representation for `Empty` is // empty JSON object `{}`. type Empty struct { } // EnableFailure: Provides error messages for the failing services. type EnableFailure struct { // ErrorMessage: An error message describing why the service could not // be enabled. ErrorMessage string `json:"errorMessage,omitempty"` // ServiceId: The service id of a service that could not be enabled. ServiceId string `json:"serviceId,omitempty"` // ForceSendFields is a list of field names (e.g. "ErrorMessage") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ErrorMessage") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *EnableFailure) MarshalJSON() ([]byte, error) { type NoMethod EnableFailure raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // EnableServiceRequest: Request message for the `EnableService` method. type EnableServiceRequest struct { } // EnableServiceResponse: Response message for the `EnableService` // method. This response message is assigned to the `response` field of // the returned Operation when that operation is done. type EnableServiceResponse struct { // Service: The new state of the service after enabling. Service *GoogleApiServiceusageV1Service `json:"service,omitempty"` // ForceSendFields is a list of field names (e.g. "Service") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Service") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *EnableServiceResponse) MarshalJSON() ([]byte, error) { type NoMethod EnableServiceResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Endpoint: `Endpoint` describes a network endpoint that serves a set // of APIs. A service may expose any number of endpoints, and all // endpoints share the same service configuration, such as quota // configuration and monitoring configuration. Example service // configuration: name: library-example.googleapis.com endpoints: # // Below entry makes 'google.example.library.v1.Library' # API be served // from endpoint address library-example.googleapis.com. # It also // allows HTTP OPTIONS calls to be passed to the backend, for # it to // decide whether the subsequent cross-origin request is # allowed to // proceed. - name: library-example.googleapis.com allow_cors: true type Endpoint struct { // Aliases: DEPRECATED: This field is no longer supported. Instead of // using aliases, please specify multiple google.api.Endpoint for each // of the intended aliases. Additional names that this endpoint will be // hosted on. Aliases []string `json:"aliases,omitempty"` // AllowCors: Allowing // [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), // aka cross-domain traffic, would allow the backends served from this // endpoint to receive and respond to HTTP OPTIONS requests. The // response will be used by the browser to determine whether the // subsequent cross-origin request is allowed to proceed. AllowCors bool `json:"allowCors,omitempty"` // Name: The canonical name of this endpoint. Name string `json:"name,omitempty"` // Target: The specification of an Internet routable address of API // frontend that will handle requests to this [API // Endpoint](https://cloud.google.com/apis/design/glossary). It should // be either a valid IPv4 address or a fully-qualified domain name. For // example, "8.8.8.8" or "myservice.appspot.com". Target string `json:"target,omitempty"` // ForceSendFields is a list of field names (e.g. "Aliases") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Aliases") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Endpoint) MarshalJSON() ([]byte, error) { type NoMethod Endpoint raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Enum: Enum type definition. type Enum struct { // Enumvalue: Enum value definitions. Enumvalue []*EnumValue `json:"enumvalue,omitempty"` // Name: Enum type name. Name string `json:"name,omitempty"` // Options: Protocol buffer options. Options []*Option `json:"options,omitempty"` // SourceContext: The source context. SourceContext *SourceContext `json:"sourceContext,omitempty"` // Syntax: The source syntax. // // Possible values: // "SYNTAX_PROTO2" - Syntax `proto2`. // "SYNTAX_PROTO3" - Syntax `proto3`. Syntax string `json:"syntax,omitempty"` // ForceSendFields is a list of field names (e.g. "Enumvalue") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Enumvalue") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Enum) MarshalJSON() ([]byte, error) { type NoMethod Enum raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // EnumValue: Enum value definition. type EnumValue struct { // Name: Enum value name. Name string `json:"name,omitempty"` // Number: Enum value number. Number int64 `json:"number,omitempty"` // Options: Protocol buffer options. Options []*Option `json:"options,omitempty"` // ForceSendFields is a list of field names (e.g. "Name") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Name") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *EnumValue) MarshalJSON() ([]byte, error) { type NoMethod EnumValue raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Field: A single field of a message type. type Field struct { // Cardinality: The field cardinality. // // Possible values: // "CARDINALITY_UNKNOWN" - For fields with unknown cardinality. // "CARDINALITY_OPTIONAL" - For optional fields. // "CARDINALITY_REQUIRED" - For required fields. Proto2 syntax only. // "CARDINALITY_REPEATED" - For repeated fields. Cardinality string `json:"cardinality,omitempty"` // DefaultValue: The string value of the default value of this field. // Proto2 syntax only. DefaultValue string `json:"defaultValue,omitempty"` // JsonName: The field JSON name. JsonName string `json:"jsonName,omitempty"` // Kind: The field type. // // Possible values: // "TYPE_UNKNOWN" - Field type unknown. // "TYPE_DOUBLE" - Field type double. // "TYPE_FLOAT" - Field type float. // "TYPE_INT64" - Field type int64. // "TYPE_UINT64" - Field type uint64. // "TYPE_INT32" - Field type int32. // "TYPE_FIXED64" - Field type fixed64. // "TYPE_FIXED32" - Field type fixed32. // "TYPE_BOOL" - Field type bool. // "TYPE_STRING" - Field type string. // "TYPE_GROUP" - Field type group. Proto2 syntax only, and // deprecated. // "TYPE_MESSAGE" - Field type message. // "TYPE_BYTES" - Field type bytes. // "TYPE_UINT32" - Field type uint32. // "TYPE_ENUM" - Field type enum. // "TYPE_SFIXED32" - Field type sfixed32. // "TYPE_SFIXED64" - Field type sfixed64. // "TYPE_SINT32" - Field type sint32. // "TYPE_SINT64" - Field type sint64. Kind string `json:"kind,omitempty"` // Name: The field name. Name string `json:"name,omitempty"` // Number: The field number. Number int64 `json:"number,omitempty"` // OneofIndex: The index of the field type in `Type.oneofs`, for message // or enumeration types. The first type has index 1; zero means the type // is not in the list. OneofIndex int64 `json:"oneofIndex,omitempty"` // Options: The protocol buffer options. Options []*Option `json:"options,omitempty"` // Packed: Whether to use alternative packed wire representation. Packed bool `json:"packed,omitempty"` // TypeUrl: The field type URL, without the scheme, for message or // enumeration types. Example: // "type.googleapis.com/google.protobuf.Timestamp". TypeUrl string `json:"typeUrl,omitempty"` // ForceSendFields is a list of field names (e.g. "Cardinality") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Cardinality") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Field) MarshalJSON() ([]byte, error) { type NoMethod Field raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GetServiceIdentityResponse: Response message for getting service // identity. type GetServiceIdentityResponse struct { // Identity: Service identity that service producer can use to access // consumer resources. If exists is true, it contains email and // unique_id. If exists is false, it contains pre-constructed email and // empty unique_id. Identity *ServiceIdentity `json:"identity,omitempty"` // State: Service identity state. // // Possible values: // "IDENTITY_STATE_UNSPECIFIED" - Default service identity state. This // value is used if the state is omitted. // "ACTIVE" - Service identity has been created and can be used. State string `json:"state,omitempty"` // ForceSendFields is a list of field names (e.g. "Identity") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Identity") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GetServiceIdentityResponse) MarshalJSON() ([]byte, error) { type NoMethod GetServiceIdentityResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiService: `Service` is the root object of Google service // configuration schema. It describes basic information about a service, // such as the name and the title, and delegates other aspects to // sub-sections. Each sub-section is either a proto message or a // repeated proto message that configures a specific aspect, such as // auth. See each proto message definition for details. Example: type: // google.api.Service config_version: 3 name: calendar.googleapis.com // title: Google Calendar API apis: - name: google.calendar.v3.Calendar // authentication: providers: - id: google_calendar_auth jwks_uri: // https://www.googleapis.com/oauth2/v1/certs issuer: // https://securetoken.google.com rules: - selector: "*" requirements: // provider_id: google_calendar_auth type GoogleApiService struct { // Apis: A list of API interfaces exported by this service. Only the // `name` field of the google.protobuf.Api needs to be provided by the // configuration author, as the remaining fields will be derived from // the IDL during the normalization process. It is an error to specify // an API interface here which cannot be resolved against the associated // IDL files. Apis []*Api `json:"apis,omitempty"` // Authentication: Auth configuration. Authentication *Authentication `json:"authentication,omitempty"` // Backend: API backend configuration. Backend *Backend `json:"backend,omitempty"` // Billing: Billing configuration. Billing *Billing `json:"billing,omitempty"` // ConfigVersion: This field is obsolete. Its value must be set to `3`. ConfigVersion int64 `json:"configVersion,omitempty"` // Context: Context configuration. Context *Context `json:"context,omitempty"` // Control: Configuration for the service control plane. Control *Control `json:"control,omitempty"` // CustomError: Custom error configuration. CustomError *CustomError `json:"customError,omitempty"` // Documentation: Additional API documentation. Documentation *Documentation `json:"documentation,omitempty"` // Endpoints: Configuration for network endpoints. If this is empty, // then an endpoint with the same name as the service is automatically // generated to service all defined APIs. Endpoints []*Endpoint `json:"endpoints,omitempty"` // Enums: A list of all enum types included in this API service. Enums // referenced directly or indirectly by the `apis` are automatically // included. Enums which are not referenced but shall be included should // be listed here by name. Example: enums: - name: // google.someapi.v1.SomeEnum Enums []*Enum `json:"enums,omitempty"` // Http: HTTP configuration. Http *Http `json:"http,omitempty"` // Id: A unique ID for a specific instance of this message, typically // assigned by the client for tracking purpose. Must be no longer than // 63 characters and only lower case letters, digits, '.', '_' and '-' // are allowed. If empty, the server may choose to generate one instead. Id string `json:"id,omitempty"` // Logging: Logging configuration. Logging *Logging `json:"logging,omitempty"` // Logs: Defines the logs used by this service. Logs []*LogDescriptor `json:"logs,omitempty"` // Metrics: Defines the metrics used by this service. Metrics []*MetricDescriptor `json:"metrics,omitempty"` // MonitoredResources: Defines the monitored resources used by this // service. This is required by the Service.monitoring and // Service.logging configurations. MonitoredResources []*MonitoredResourceDescriptor `json:"monitoredResources,omitempty"` // Monitoring: Monitoring configuration. Monitoring *Monitoring `json:"monitoring,omitempty"` // Name: The service name, which is a DNS-like logical identifier for // the service, such as `calendar.googleapis.com`. The service name // typically goes through DNS verification to make sure the owner of the // service also owns the DNS name. Name string `json:"name,omitempty"` // ProducerProjectId: The Google project that owns this service. ProducerProjectId string `json:"producerProjectId,omitempty"` // Quota: Quota configuration. Quota *Quota `json:"quota,omitempty"` // SourceInfo: Output only. The source information for this // configuration if available. SourceInfo *SourceInfo `json:"sourceInfo,omitempty"` // SystemParameters: System parameter configuration. SystemParameters *SystemParameters `json:"systemParameters,omitempty"` // SystemTypes: A list of all proto message types included in this API // service. It serves similar purpose as [google.api.Service.types], // except that these types are not needed by user-defined APIs. // Therefore, they will not show up in the generated discovery doc. This // field should only be used to define system APIs in ESF. SystemTypes []*Type `json:"systemTypes,omitempty"` // Title: The product title for this service. Title string `json:"title,omitempty"` // Types: A list of all proto message types included in this API // service. Types referenced directly or indirectly by the `apis` are // automatically included. Messages which are not referenced but shall // be included, such as types used by the `google.protobuf.Any` type, // should be listed here by name. Example: types: - name: // google.protobuf.Int32 Types []*Type `json:"types,omitempty"` // Usage: Configuration controlling usage of this service. Usage *Usage `json:"usage,omitempty"` // ForceSendFields is a list of field names (e.g. "Apis") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Apis") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiService) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiService raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceIdentity: The per-product per-project service // identity for a service. Use this field to configure per-product // per-project service identity. Example of a service identity // configuration. usage: service_identity: - service_account_parent: // "projects/123456789" display_name: "Cloud XXX Service Agent" // description: "Used as the identity of Cloud XXX to access resources" type GoogleApiServiceIdentity struct { // Description: Optional. A user-specified opaque description of the // service account. Must be less than or equal to 256 UTF-8 bytes. Description string `json:"description,omitempty"` // DisplayName: Optional. A user-specified name for the service account. // Must be less than or equal to 100 UTF-8 bytes. DisplayName string `json:"displayName,omitempty"` // ServiceAccountParent: A service account project that hosts the // service accounts. An example name would be: `projects/123456789` ServiceAccountParent string `json:"serviceAccountParent,omitempty"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceIdentity) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceIdentity raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceusageV1OperationMetadata: The operation metadata // returned for the batchend services operation. type GoogleApiServiceusageV1OperationMetadata struct { // ResourceNames: The full name of the resources that this operation is // directly associated with. ResourceNames []string `json:"resourceNames,omitempty"` // ForceSendFields is a list of field names (e.g. "ResourceNames") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ResourceNames") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceusageV1OperationMetadata) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceusageV1OperationMetadata raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceusageV1Service: A service that is available for use // by the consumer. type GoogleApiServiceusageV1Service struct { // Config: The service configuration of the available service. Some // fields may be filtered out of the configuration in responses to the // `ListServices` method. These fields are present only in responses to // the `GetService` method. Config *GoogleApiServiceusageV1ServiceConfig `json:"config,omitempty"` // Name: The resource name of the consumer and service. A valid name // would be: - projects/123/services/serviceusage.googleapis.com Name string `json:"name,omitempty"` // Parent: The resource name of the consumer. A valid name would be: - // projects/123 Parent string `json:"parent,omitempty"` // State: Whether or not the service has been enabled for use by the // consumer. // // Possible values: // "STATE_UNSPECIFIED" - The default value, which indicates that the // enabled state of the service is unspecified or not meaningful. // Currently, all consumers other than projects (such as folders and // organizations) are always in this state. // "DISABLED" - The service cannot be used by this consumer. It has // either been explicitly disabled, or has never been enabled. // "ENABLED" - The service has been explicitly enabled for use by this // consumer. State string `json:"state,omitempty"` // ForceSendFields is a list of field names (e.g. "Config") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Config") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceusageV1Service) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceusageV1Service raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceusageV1ServiceConfig: The configuration of the // service. type GoogleApiServiceusageV1ServiceConfig struct { // Apis: A list of API interfaces exported by this service. Contains // only the names, versions, and method names of the interfaces. Apis []*Api `json:"apis,omitempty"` // Authentication: Auth configuration. Contains only the OAuth rules. Authentication *Authentication `json:"authentication,omitempty"` // Documentation: Additional API documentation. Contains only the // summary and the documentation URL. Documentation *Documentation `json:"documentation,omitempty"` // Endpoints: Configuration for network endpoints. Contains only the // names and aliases of the endpoints. Endpoints []*Endpoint `json:"endpoints,omitempty"` // MonitoredResources: Defines the monitored resources used by this // service. This is required by the Service.monitoring and // Service.logging configurations. MonitoredResources []*MonitoredResourceDescriptor `json:"monitoredResources,omitempty"` // Monitoring: Monitoring configuration. This should not include the // 'producer_destinations' field. Monitoring *Monitoring `json:"monitoring,omitempty"` // Name: The DNS address at which this service is available. An example // DNS address would be: `calendar.googleapis.com`. Name string `json:"name,omitempty"` // Quota: Quota configuration. Quota *Quota `json:"quota,omitempty"` // Title: The product title for this service. Title string `json:"title,omitempty"` // Usage: Configuration controlling usage of this service. Usage *Usage `json:"usage,omitempty"` // ForceSendFields is a list of field names (e.g. "Apis") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Apis") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceusageV1ServiceConfig) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceusageV1ServiceConfig raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceusageV1beta1GetServiceIdentityResponse: Response // message for getting service identity. type GoogleApiServiceusageV1beta1GetServiceIdentityResponse struct { // Identity: Service identity that service producer can use to access // consumer resources. If exists is true, it contains email and // unique_id. If exists is false, it contains pre-constructed email and // empty unique_id. Identity *GoogleApiServiceusageV1beta1ServiceIdentity `json:"identity,omitempty"` // State: Service identity state. // // Possible values: // "IDENTITY_STATE_UNSPECIFIED" - Default service identity state. This // value is used if the state is omitted. // "ACTIVE" - Service identity has been created and can be used. State string `json:"state,omitempty"` // ForceSendFields is a list of field names (e.g. "Identity") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Identity") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceusageV1beta1GetServiceIdentityResponse) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceusageV1beta1GetServiceIdentityResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleApiServiceusageV1beta1ServiceIdentity: Service identity for a // service. This is the identity that service producer should use to // access consumer resources. type GoogleApiServiceusageV1beta1ServiceIdentity struct { // Email: The email address of the service account that a service // producer would use to access consumer resources. Email string `json:"email,omitempty"` // UniqueId: The unique and stable id of the service account. // https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts#ServiceAccount UniqueId string `json:"uniqueId,omitempty"` // ForceSendFields is a list of field names (e.g. "Email") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Email") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleApiServiceusageV1beta1ServiceIdentity) MarshalJSON() ([]byte, error) { type NoMethod GoogleApiServiceusageV1beta1ServiceIdentity raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Http: Defines the HTTP configuration for an API service. It contains // a list of HttpRule, each specifying the mapping of an RPC method to // one or more HTTP REST API methods. type Http struct { // FullyDecodeReservedExpansion: When set to true, URL path parameters // will be fully URI-decoded except in cases of single segment matches // in reserved expansion, where "%2F" will be left encoded. The default // behavior is to not decode RFC 6570 reserved characters in multi // segment matches. FullyDecodeReservedExpansion bool `json:"fullyDecodeReservedExpansion,omitempty"` // Rules: A list of HTTP configuration rules that apply to individual // API methods. **NOTE:** All service configuration rules follow "last // one wins" order. Rules []*HttpRule `json:"rules,omitempty"` // ForceSendFields is a list of field names (e.g. // "FullyDecodeReservedExpansion") to unconditionally include in API // requests. By default, fields with empty values are omitted from API // requests. However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. // "FullyDecodeReservedExpansion") to include in API requests with the // JSON null value. By default, fields with empty values are omitted // from API requests. However, any field with an empty value appearing // in NullFields will be sent to the server as null. It is an error if a // field in this list has a non-empty value. This may be used to include // null fields in Patch requests. NullFields []string `json:"-"` } func (s *Http) MarshalJSON() ([]byte, error) { type NoMethod Http raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // HttpRule: # gRPC Transcoding gRPC Transcoding is a feature for // mapping between a gRPC method and one or more HTTP REST endpoints. It // allows developers to build a single API service that supports both // gRPC APIs and REST APIs. Many systems, including [Google // APIs](https://github.com/googleapis/googleapis), [Cloud // Endpoints](https://cloud.google.com/endpoints), [gRPC // Gateway](https://github.com/grpc-ecosystem/grpc-gateway), and // [Envoy](https://github.com/envoyproxy/envoy) proxy support this // feature and use it for large scale production services. `HttpRule` // defines the schema of the gRPC/REST mapping. The mapping specifies // how different portions of the gRPC request message are mapped to the // URL path, URL query parameters, and HTTP request body. It also // controls how the gRPC response message is mapped to the HTTP response // body. `HttpRule` is typically specified as an `google.api.http` // annotation on the gRPC method. Each mapping specifies a URL path // template and an HTTP method. The path template may refer to one or // more fields in the gRPC request message, as long as each field is a // non-repeated field with a primitive (non-message) type. The path // template controls how fields of the request message are mapped to the // URL path. Example: service Messaging { rpc // GetMessage(GetMessageRequest) returns (Message) { option // (google.api.http) = { get: "/v1/{name=messages/*}" }; } } message // GetMessageRequest { string name = 1; // Mapped to URL path. } message // Message { string text = 1; // The resource content. } This enables an // HTTP REST to gRPC mapping as below: HTTP | gRPC -----|----- `GET // /v1/messages/123456` | `GetMessage(name: "messages/123456")` Any // fields in the request message which are not bound by the path // template automatically become HTTP query parameters if there is no // HTTP request body. For example: service Messaging { rpc // GetMessage(GetMessageRequest) returns (Message) { option // (google.api.http) = { get:"/v1/messages/{message_id}" }; } } message // GetMessageRequest { message SubMessage { string subfield = 1; } // string message_id = 1; // Mapped to URL path. int64 revision = 2; // // Mapped to URL query parameter `revision`. SubMessage sub = 3; // // Mapped to URL query parameter `sub.subfield`. } This enables a HTTP // JSON to RPC mapping as below: HTTP | gRPC -----|----- `GET // /v1/messages/123456?revision=2&sub.subfield=foo` | // `GetMessage(message_id: "123456" revision: 2 sub: // SubMessage(subfield: "foo"))` Note that fields which are mapped to // URL query parameters must have a primitive type or a repeated // primitive type or a non-repeated message type. In the case of a // repeated type, the parameter can be repeated in the URL as // `...?param=A&param=B`. In the case of a message type, each field of // the message is mapped to a separate parameter, such as // `...?foo.a=A&foo.b=B&foo.c=C`. For HTTP methods that allow a request // body, the `body` field specifies the mapping. Consider a REST update // method on the message resource collection: service Messaging { rpc // UpdateMessage(UpdateMessageRequest) returns (Message) { option // (google.api.http) = { patch: "/v1/messages/{message_id}" body: // "message" }; } } message UpdateMessageRequest { string message_id = // 1; // mapped to the URL Message message = 2; // mapped to the body } // The following HTTP JSON to RPC mapping is enabled, where the // representation of the JSON in the request body is determined by // protos JSON encoding: HTTP | gRPC -----|----- `PATCH // /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: // "123456" message { text: "Hi!" })` The special name `*` can be used // in the body mapping to define that every field not bound by the path // template should be mapped to the request body. This enables the // following alternative definition of the update method: service // Messaging { rpc UpdateMessage(Message) returns (Message) { option // (google.api.http) = { patch: "/v1/messages/{message_id}" body: "*" }; // } } message Message { string message_id = 1; string text = 2; } The // following HTTP JSON to RPC mapping is enabled: HTTP | gRPC // -----|----- `PATCH /v1/messages/123456 { "text": "Hi!" }` | // `UpdateMessage(message_id: "123456" text: "Hi!")` Note that when // using `*` in the body mapping, it is not possible to have HTTP // parameters, as all fields not bound by the path end in the body. This // makes this option more rarely used in practice when defining REST // APIs. The common usage of `*` is in custom methods which don't use // the URL at all for transferring data. It is possible to define // multiple HTTP methods for one RPC by using the `additional_bindings` // option. Example: service Messaging { rpc // GetMessage(GetMessageRequest) returns (Message) { option // (google.api.http) = { get: "/v1/messages/{message_id}" // additional_bindings { get: // "/v1/users/{user_id}/messages/{message_id}" } }; } } message // GetMessageRequest { string message_id = 1; string user_id = 2; } This // enables the following two alternative HTTP JSON to RPC mappings: HTTP // | gRPC -----|----- `GET /v1/messages/123456` | // `GetMessage(message_id: "123456")` `GET /v1/users/me/messages/123456` // | `GetMessage(user_id: "me" message_id: "123456")` ## Rules for HTTP // mapping 1. Leaf request fields (recursive expansion nested messages // in the request message) are classified into three categories: - // Fields referred by the path template. They are passed via the URL // path. - Fields referred by the HttpRule.body. They are passed via the // HTTP request body. - All other fields are passed via the URL query // parameters, and the parameter name is the field path in the request // message. A repeated field can be represented as multiple query // parameters under the same name. 2. If HttpRule.body is "*", there is // no URL query parameter, all fields are passed via URL path and HTTP // request body. 3. If HttpRule.body is omitted, there is no HTTP // request body, all fields are passed via URL path and URL query // parameters. ### Path template syntax Template = "/" Segments [ Verb ] // ; Segments = Segment { "/" Segment } ; Segment = "*" | "**" | LITERAL // | Variable ; Variable = "{" FieldPath [ "=" Segments ] "}" ; // FieldPath = IDENT { "." IDENT } ; Verb = ":" LITERAL ; The syntax `*` // matches a single URL path segment. The syntax `**` matches zero or // more URL path segments, which must be the last part of the URL path // except the `Verb`. The syntax `Variable` matches part of the URL path // as specified by its template. A variable template must not contain // other variables. If a variable matches a single path segment, its // template may be omitted, e.g. `{var}` is equivalent to `{var=*}`. The // syntax `LITERAL` matches literal text in the URL path. If the // `LITERAL` contains any reserved character, such characters should be // percent-encoded before the matching. If a variable contains exactly // one path segment, such as "{var}" or "{var=*}", when such a // variable is expanded into a URL path on the client side, all // characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The server // side does the reverse decoding. Such variables show up in the // [Discovery // Document](https://developers.google.com/discovery/v1/reference/apis) // as `{var}`. If a variable contains multiple path segments, such as // "{var=foo/*}" or "{var=**}", when such a variable is expanded // into a URL path on the client side, all characters except // `[-_.~/0-9a-zA-Z]` are percent-encoded. The server side does the // reverse decoding, except "%2F" and "%2f" are left unchanged. Such // variables show up in the [Discovery // Document](https://developers.google.com/discovery/v1/reference/apis) // as `{+var}`. ## Using gRPC API Service Configuration gRPC API Service // Configuration (service config) is a configuration language for // configuring a gRPC service to become a user-facing product. The // service config is simply the YAML representation of the // `google.api.Service` proto message. As an alternative to annotating // your proto file, you can configure gRPC transcoding in your service // config YAML files. You do this by specifying a `HttpRule` that maps // the gRPC method to a REST endpoint, achieving the same effect as the // proto annotation. This can be particularly useful if you have a proto // that is reused in multiple services. Note that any transcoding // specified in the service config will override any matching // transcoding configuration in the proto. Example: http: rules: # // Selects a gRPC method and applies HttpRule to it. - selector: // example.v1.Messaging.GetMessage get: // /v1/messages/{message_id}/{sub.subfield} ## Special notes When gRPC // Transcoding is used to map a gRPC to JSON REST endpoints, the proto // to JSON conversion must follow the [proto3 // specification](https://developers.google.com/protocol-buffers/docs/pro // to3#json). While the single segment variable follows the semantics of // [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple // String Expansion, the multi segment variable **does not** follow RFC // 6570 Section 3.2.3 Reserved Expansion. The reason is that the // Reserved Expansion does not expand special characters like `?` and // `#`, which would lead to invalid URLs. As the result, gRPC // Transcoding uses a custom encoding for multi segment variables. The // path variables **must not** refer to any repeated or mapped field, // because client libraries are not capable of handling such variable // expansion. The path variables **must not** capture the leading "/" // character. The reason is that the most common use case "{var}" does // not capture the leading "/" character. For consistency, all path // variables must share the same behavior. Repeated message fields must // not be mapped to URL query parameters, because no client library can // support such complicated mapping. If an API needs to use a JSON array // for request or response body, it can map the request or response body // to a repeated field. However, some gRPC Transcoding implementations // may not support this feature. type HttpRule struct { // AdditionalBindings: Additional HTTP bindings for the selector. Nested // bindings must not contain an `additional_bindings` field themselves // (that is, the nesting may only be one level deep). AdditionalBindings []*HttpRule `json:"additionalBindings,omitempty"` // AllowHalfDuplex: When this flag is set to true, HTTP requests will be // allowed to invoke a half-duplex streaming method. AllowHalfDuplex bool `json:"allowHalfDuplex,omitempty"` // Body: The name of the request field whose value is mapped to the HTTP // request body, or `*` for mapping all request fields not captured by // the path pattern to the HTTP body, or omitted for not having any HTTP // request body. NOTE: the referred field must be present at the // top-level of the request message type. Body string `json:"body,omitempty"` // Custom: The custom pattern is used for specifying an HTTP method that // is not included in the `pattern` field, such as HEAD, or "*" to leave // the HTTP method unspecified for this rule. The wild-card rule is // useful for services that provide content to Web (HTML) clients. Custom *CustomHttpPattern `json:"custom,omitempty"` // Delete: Maps to HTTP DELETE. Used for deleting a resource. Delete string `json:"delete,omitempty"` // Get: Maps to HTTP GET. Used for listing and getting information about // resources. Get string `json:"get,omitempty"` // Patch: Maps to HTTP PATCH. Used for updating a resource. Patch string `json:"patch,omitempty"` // Post: Maps to HTTP POST. Used for creating a resource or performing // an action. Post string `json:"post,omitempty"` // Put: Maps to HTTP PUT. Used for replacing a resource. Put string `json:"put,omitempty"` // ResponseBody: Optional. The name of the response field whose value is // mapped to the HTTP response body. When omitted, the entire response // message will be used as the HTTP response body. NOTE: The referred // field must be present at the top-level of the response message type. ResponseBody string `json:"responseBody,omitempty"` // Selector: Selects a method to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. "AdditionalBindings") // to unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AdditionalBindings") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *HttpRule) MarshalJSON() ([]byte, error) { type NoMethod HttpRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ImportAdminOverridesResponse: Response message for // ImportAdminOverrides type ImportAdminOverridesResponse struct { // Overrides: The overrides that were created from the imported data. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ForceSendFields is a list of field names (e.g. "Overrides") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Overrides") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ImportAdminOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod ImportAdminOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ImportAdminQuotaPoliciesResponse: Response message for // ImportAdminQuotaPolicies type ImportAdminQuotaPoliciesResponse struct { // Policies: The policies that were created from the imported data. Policies []*AdminQuotaPolicy `json:"policies,omitempty"` // ForceSendFields is a list of field names (e.g. "Policies") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Policies") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ImportAdminQuotaPoliciesResponse) MarshalJSON() ([]byte, error) { type NoMethod ImportAdminQuotaPoliciesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ImportConsumerOverridesRequest: Request message for // ImportConsumerOverrides type ImportConsumerOverridesRequest struct { // Force: Whether to force the creation of the quota overrides. If // creating an override would cause the effective quota for the consumer // to decrease by more than 10 percent, the call is rejected, as a // safety measure to avoid accidentally decreasing quota too quickly. // Setting the force parameter to true ignores this restriction. Force bool `json:"force,omitempty"` // InlineSource: The import data is specified in the request message // itself InlineSource *OverrideInlineSource `json:"inlineSource,omitempty"` // ForceSendFields is a list of field names (e.g. "Force") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Force") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ImportConsumerOverridesRequest) MarshalJSON() ([]byte, error) { type NoMethod ImportConsumerOverridesRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ImportConsumerOverridesResponse: Response message for // ImportConsumerOverrides type ImportConsumerOverridesResponse struct { // Overrides: The overrides that were created from the imported data. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ForceSendFields is a list of field names (e.g. "Overrides") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Overrides") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ImportConsumerOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod ImportConsumerOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // JwtLocation: Specifies a location to extract JWT from an API request. type JwtLocation struct { // Header: Specifies HTTP header name to extract JWT token. Header string `json:"header,omitempty"` // Query: Specifies URL query parameter name to extract JWT token. Query string `json:"query,omitempty"` // ValuePrefix: The value prefix. The value format is // "value_prefix{token}" Only applies to "in" header type. Must be empty // for "in" query type. If not empty, the header value has to match // (case sensitive) this prefix. If not matched, JWT will not be // extracted. If matched, JWT will be extracted after the prefix is // removed. For example, for "Authorization: Bearer {JWT}", // value_prefix="Bearer " with a space at the end. ValuePrefix string `json:"valuePrefix,omitempty"` // ForceSendFields is a list of field names (e.g. "Header") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Header") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *JwtLocation) MarshalJSON() ([]byte, error) { type NoMethod JwtLocation raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LabelDescriptor: A description of a label. type LabelDescriptor struct { // Description: A human-readable description for the label. Description string `json:"description,omitempty"` // Key: The label key. Key string `json:"key,omitempty"` // ValueType: The type of data that can be assigned to the label. // // Possible values: // "STRING" - A variable-length string. This is the default. // "BOOL" - Boolean; true or false. // "INT64" - A 64-bit signed integer. ValueType string `json:"valueType,omitempty"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LabelDescriptor) MarshalJSON() ([]byte, error) { type NoMethod LabelDescriptor raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListAdminOverridesResponse: Response message for ListAdminOverrides. type ListAdminOverridesResponse struct { // NextPageToken: Token identifying which result to start with; returned // by a previous list call. NextPageToken string `json:"nextPageToken,omitempty"` // Overrides: Admin overrides on this limit. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListAdminOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod ListAdminOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListConsumerOverridesResponse: Response message for // ListConsumerOverrides. type ListConsumerOverridesResponse struct { // NextPageToken: Token identifying which result to start with; returned // by a previous list call. NextPageToken string `json:"nextPageToken,omitempty"` // Overrides: Consumer overrides on this limit. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListConsumerOverridesResponse) MarshalJSON() ([]byte, error) { type NoMethod ListConsumerOverridesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListConsumerQuotaMetricsResponse: Response message for // ListConsumerQuotaMetrics type ListConsumerQuotaMetricsResponse struct { // Metrics: Quota settings for the consumer, organized by quota metric. Metrics []*ConsumerQuotaMetric `json:"metrics,omitempty"` // NextPageToken: Token identifying which result to start with; returned // by a previous list call. NextPageToken string `json:"nextPageToken,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Metrics") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Metrics") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListConsumerQuotaMetricsResponse) MarshalJSON() ([]byte, error) { type NoMethod ListConsumerQuotaMetricsResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListOperationsResponse: The response message for // Operations.ListOperations. type ListOperationsResponse struct { // NextPageToken: The standard List next-page token. NextPageToken string `json:"nextPageToken,omitempty"` // Operations: A list of operations that matches the specified filter in // the request. Operations []*Operation `json:"operations,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListOperationsResponse) MarshalJSON() ([]byte, error) { type NoMethod ListOperationsResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListServicesResponse: Response message for the `ListServices` method. type ListServicesResponse struct { // NextPageToken: Token that can be passed to `ListServices` to resume a // paginated query. NextPageToken string `json:"nextPageToken,omitempty"` // Services: The available services for the requested project. Services []*Service `json:"services,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListServicesResponse) MarshalJSON() ([]byte, error) { type NoMethod ListServicesResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogDescriptor: A description of a log type. Example in YAML format: - // name: library.googleapis.com/activity_history description: The // history of borrowing and returning library items. display_name: // Activity labels: - key: /customer_id description: Identifier of a // library customer type LogDescriptor struct { // Description: A human-readable description of this log. This // information appears in the documentation and can contain details. Description string `json:"description,omitempty"` // DisplayName: The human-readable name for this log. This information // appears on the user interface and should be concise. DisplayName string `json:"displayName,omitempty"` // Labels: The set of labels that are available to describe a specific // log entry. Runtime requests that contain labels not specified here // are considered invalid. Labels []*LabelDescriptor `json:"labels,omitempty"` // Name: The name of the log. It must be less than 512 characters long // and can include the following characters: upper- and lower-case // alphanumeric characters [A-Za-z0-9], and punctuation characters // including slash, underscore, hyphen, period [/_-.]. Name string `json:"name,omitempty"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogDescriptor) MarshalJSON() ([]byte, error) { type NoMethod LogDescriptor raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Logging: Logging configuration of the service. The following example // shows how to configure logs to be sent to the producer and consumer // projects. In the example, the `activity_history` log is sent to both // the producer and consumer projects, whereas the `purchase_history` // log is only sent to the producer project. monitored_resources: - // type: library.googleapis.com/branch labels: - key: /city description: // The city where the library branch is located in. - key: /name // description: The name of the branch. logs: - name: activity_history // labels: - key: /customer_id - name: purchase_history logging: // producer_destinations: - monitored_resource: // library.googleapis.com/branch logs: - activity_history - // purchase_history consumer_destinations: - monitored_resource: // library.googleapis.com/branch logs: - activity_history type Logging struct { // ConsumerDestinations: Logging configurations for sending logs to the // consumer project. There can be multiple consumer destinations, each // one must have a different monitored resource type. A log can be used // in at most one consumer destination. ConsumerDestinations []*LoggingDestination `json:"consumerDestinations,omitempty"` // ProducerDestinations: Logging configurations for sending logs to the // producer project. There can be multiple producer destinations, each // one must have a different monitored resource type. A log can be used // in at most one producer destination. ProducerDestinations []*LoggingDestination `json:"producerDestinations,omitempty"` // ForceSendFields is a list of field names (e.g. // "ConsumerDestinations") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ConsumerDestinations") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *Logging) MarshalJSON() ([]byte, error) { type NoMethod Logging raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LoggingDestination: Configuration of a specific logging destination // (the producer project or the consumer project). type LoggingDestination struct { // Logs: Names of the logs to be sent to this destination. Each name // must be defined in the Service.logs section. If the log name is not a // domain scoped name, it will be automatically prefixed with the // service name followed by "/". Logs []string `json:"logs,omitempty"` // MonitoredResource: The monitored resource type. The type must be // defined in the Service.monitored_resources section. MonitoredResource string `json:"monitoredResource,omitempty"` // ForceSendFields is a list of field names (e.g. "Logs") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Logs") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LoggingDestination) MarshalJSON() ([]byte, error) { type NoMethod LoggingDestination raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Method: Method represents a method of an API interface. type Method struct { // Name: The simple name of this method. Name string `json:"name,omitempty"` // Options: Any metadata attached to the method. Options []*Option `json:"options,omitempty"` // RequestStreaming: If true, the request is streamed. RequestStreaming bool `json:"requestStreaming,omitempty"` // RequestTypeUrl: A URL of the input message type. RequestTypeUrl string `json:"requestTypeUrl,omitempty"` // ResponseStreaming: If true, the response is streamed. ResponseStreaming bool `json:"responseStreaming,omitempty"` // ResponseTypeUrl: The URL of the output message type. ResponseTypeUrl string `json:"responseTypeUrl,omitempty"` // Syntax: The source syntax of this method. // // Possible values: // "SYNTAX_PROTO2" - Syntax `proto2`. // "SYNTAX_PROTO3" - Syntax `proto3`. Syntax string `json:"syntax,omitempty"` // ForceSendFields is a list of field names (e.g. "Name") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Name") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Method) MarshalJSON() ([]byte, error) { type NoMethod Method raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // MetricDescriptor: Defines a metric type and its schema. Once a metric // descriptor is created, deleting or altering it stops data collection // and makes the metric type's existing data unusable. type MetricDescriptor struct { // Description: A detailed description of the metric, which can be used // in documentation. Description string `json:"description,omitempty"` // DisplayName: A concise name for the metric, which can be displayed in // user interfaces. Use sentence case without an ending period, for // example "Request count". This field is optional but it is recommended // to be set for any metrics associated with user-visible concepts, such // as Quota. DisplayName string `json:"displayName,omitempty"` // Labels: The set of labels that can be used to describe a specific // instance of this metric type. For example, the // `appengine.googleapis.com/http/server/response_latencies` metric type // has a label for the HTTP response code, `response_code`, so you can // look at latencies for successful responses or just for responses that // failed. Labels []*LabelDescriptor `json:"labels,omitempty"` // LaunchStage: Optional. The launch stage of the metric definition. // // Possible values: // "LAUNCH_STAGE_UNSPECIFIED" - Do not use this default value. // "UNIMPLEMENTED" - The feature is not yet implemented. Users can not // use it. // "PRELAUNCH" - Prelaunch features are hidden from users and are only // visible internally. // "EARLY_ACCESS" - Early Access features are limited to a closed // group of testers. To use these features, you must sign up in advance // and sign a Trusted Tester agreement (which includes confidentiality // provisions). These features may be unstable, changed in // backward-incompatible ways, and are not guaranteed to be released. // "ALPHA" - Alpha is a limited availability test for releases before // they are cleared for widespread use. By Alpha, all significant design // issues are resolved and we are in the process of verifying // functionality. Alpha customers need to apply for access, agree to // applicable terms, and have their projects allowlisted. Alpha releases // don’t have to be feature complete, no SLAs are provided, and there // are no technical support obligations, but they will be far enough // along that customers can actually use them in test environments or // for limited-use tests -- just like they would in normal production // cases. // "BETA" - Beta is the point at which we are ready to open a release // for any customer to use. There are no SLA or technical support // obligations in a Beta release. Products will be complete from a // feature perspective, but may have some open outstanding issues. Beta // releases are suitable for limited production use cases. // "GA" - GA features are open to all developers and are considered // stable and fully qualified for production use. // "DEPRECATED" - Deprecated features are scheduled to be shut down // and removed. For more information, see the “Deprecation Policy” // section of our [Terms of Service](https://cloud.google.com/terms/) // and the [Google Cloud Platform Subject to the Deprecation // Policy](https://cloud.google.com/terms/deprecation) documentation. LaunchStage string `json:"launchStage,omitempty"` // Metadata: Optional. Metadata which can be used to guide usage of the // metric. Metadata *MetricDescriptorMetadata `json:"metadata,omitempty"` // MetricKind: Whether the metric records instantaneous values, changes // to a value, etc. Some combinations of `metric_kind` and `value_type` // might not be supported. // // Possible values: // "METRIC_KIND_UNSPECIFIED" - Do not use this default value. // "GAUGE" - An instantaneous measurement of a value. // "DELTA" - The change in a value during a time interval. // "CUMULATIVE" - A value accumulated over a time interval. Cumulative // measurements in a time series should have the same start time and // increasing end times, until an event resets the cumulative value to // zero and sets a new start time for the following points. MetricKind string `json:"metricKind,omitempty"` // MonitoredResourceTypes: Read-only. If present, then a time series, // which is identified partially by a metric type and a // MonitoredResourceDescriptor, that is associated with this metric type // can only be associated with one of the monitored resource types // listed here. MonitoredResourceTypes []string `json:"monitoredResourceTypes,omitempty"` // Name: The resource name of the metric descriptor. Name string `json:"name,omitempty"` // Type: The metric type, including its DNS name prefix. The type is not // URL-encoded. All user-defined metric types have the DNS name // `custom.googleapis.com` or `external.googleapis.com`. Metric types // should use a natural hierarchical grouping. For example: // "custom.googleapis.com/invoice/paid/amount" // "external.googleapis.com/prometheus/up" // "appengine.googleapis.com/http/server/response_latencies" Type string `json:"type,omitempty"` // Unit: The units in which the metric value is reported. It is only // applicable if the `value_type` is `INT64`, `DOUBLE`, or // `DISTRIBUTION`. The `unit` defines the representation of the stored // metric values. Different systems may scale the values to be more // easily displayed (so a value of `0.02KBy` _might_ be displayed as // `20By`, and a value of `3523KBy` _might_ be displayed as `3.5MBy`). // However, if the `unit` is `KBy`, then the value of the metric is // always in thousands of bytes, no matter how it may be displayed.. If // you want a custom metric to record the exact number of CPU-seconds // used by a job, you can create an `INT64 CUMULATIVE` metric whose // `unit` is `s{CPU}` (or equivalently `1s{CPU}` or just `s`). If the // job uses 12,005 CPU-seconds, then the value is written as `12005`. // Alternatively, if you want a custom metric to record data in a more // granular way, you can create a `DOUBLE CUMULATIVE` metric whose // `unit` is `ks{CPU}`, and then write the value `12.005` (which is // `12005/1000`), or use `Kis{CPU}` and write `11.723` (which is // `12005/1024`). The supported units are a subset of [The Unified Code // for Units of Measure](http://unitsofmeasure.org/ucum.html) standard: // **Basic units (UNIT)** * `bit` bit * `By` byte * `s` second * `min` // minute * `h` hour * `d` day * `1` dimensionless **Prefixes (PREFIX)** // * `k` kilo (10^3) * `M` mega (10^6) * `G` giga (10^9) * `T` tera // (10^12) * `P` peta (10^15) * `E` exa (10^18) * `Z` zetta (10^21) * // `Y` yotta (10^24) * `m` milli (10^-3) * `u` micro (10^-6) * `n` nano // (10^-9) * `p` pico (10^-12) * `f` femto (10^-15) * `a` atto (10^-18) // * `z` zepto (10^-21) * `y` yocto (10^-24) * `Ki` kibi (2^10) * `Mi` // mebi (2^20) * `Gi` gibi (2^30) * `Ti` tebi (2^40) * `Pi` pebi (2^50) // **Grammar** The grammar also includes these connectors: * `/` // division or ratio (as an infix operator). For examples, `kBy/{email}` // or `MiBy/10ms` (although you should almost never have `/s` in a // metric `unit`; rates should always be computed at query time from the // underlying cumulative or delta value). * `.` multiplication or // composition (as an infix operator). For examples, `GBy.d` or // `k{watt}.h`. The grammar for a unit is as follows: Expression = // Component { "." Component } { "/" Component } ; Component = ( [ // PREFIX ] UNIT | "%" ) [ Annotation ] | Annotation | "1" ; Annotation // = "{" NAME "}" ; Notes: * `Annotation` is just a comment if it // follows a `UNIT`. If the annotation is used alone, then the unit is // equivalent to `1`. For examples, `{request}/s == 1/s`, // `By{transmitted}/s == By/s`. * `NAME` is a sequence of non-blank // printable ASCII characters not containing `{` or `}`. * `1` // represents a unitary [dimensionless // unit](https://en.wikipedia.org/wiki/Dimensionless_quantity) of 1, // such as in `1/s`. It is typically used when none of the basic units // are appropriate. For example, "new users per day" can be represented // as `1/d` or `{new-users}/d` (and a metric value `5` would mean "5 new // users). Alternatively, "thousands of page views per day" would be // represented as `1000/d` or `k1/d` or `k{page_views}/d` (and a metric // value of `5.3` would mean "5300 page views per day"). * `%` // represents dimensionless value of 1/100, and annotates values giving // a percentage (so the metric values are typically in the range of // 0..100, and a metric value `3` means "3 percent"). * `10^2.%` // indicates a metric contains a ratio, typically in the range 0..1, // that will be multiplied by 100 and displayed as a percentage (so a // metric value `0.03` means "3 percent"). Unit string `json:"unit,omitempty"` // ValueType: Whether the measurement is an integer, a floating-point // number, etc. Some combinations of `metric_kind` and `value_type` // might not be supported. // // Possible values: // "VALUE_TYPE_UNSPECIFIED" - Do not use this default value. // "BOOL" - The value is a boolean. This value type can be used only // if the metric kind is `GAUGE`. // "INT64" - The value is a signed 64-bit integer. // "DOUBLE" - The value is a double precision floating point number. // "STRING" - The value is a text string. This value type can be used // only if the metric kind is `GAUGE`. // "DISTRIBUTION" - The value is a `Distribution`. // "MONEY" - The value is money. ValueType string `json:"valueType,omitempty"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *MetricDescriptor) MarshalJSON() ([]byte, error) { type NoMethod MetricDescriptor raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // MetricDescriptorMetadata: Additional annotations that can be used to // guide the usage of a metric. type MetricDescriptorMetadata struct { // IngestDelay: The delay of data points caused by ingestion. Data // points older than this age are guaranteed to be ingested and // available to be read, excluding data loss due to errors. IngestDelay string `json:"ingestDelay,omitempty"` // LaunchStage: Deprecated. Must use the MetricDescriptor.launch_stage // instead. // // Possible values: // "LAUNCH_STAGE_UNSPECIFIED" - Do not use this default value. // "UNIMPLEMENTED" - The feature is not yet implemented. Users can not // use it. // "PRELAUNCH" - Prelaunch features are hidden from users and are only // visible internally. // "EARLY_ACCESS" - Early Access features are limited to a closed // group of testers. To use these features, you must sign up in advance // and sign a Trusted Tester agreement (which includes confidentiality // provisions). These features may be unstable, changed in // backward-incompatible ways, and are not guaranteed to be released. // "ALPHA" - Alpha is a limited availability test for releases before // they are cleared for widespread use. By Alpha, all significant design // issues are resolved and we are in the process of verifying // functionality. Alpha customers need to apply for access, agree to // applicable terms, and have their projects allowlisted. Alpha releases // don’t have to be feature complete, no SLAs are provided, and there // are no technical support obligations, but they will be far enough // along that customers can actually use them in test environments or // for limited-use tests -- just like they would in normal production // cases. // "BETA" - Beta is the point at which we are ready to open a release // for any customer to use. There are no SLA or technical support // obligations in a Beta release. Products will be complete from a // feature perspective, but may have some open outstanding issues. Beta // releases are suitable for limited production use cases. // "GA" - GA features are open to all developers and are considered // stable and fully qualified for production use. // "DEPRECATED" - Deprecated features are scheduled to be shut down // and removed. For more information, see the “Deprecation Policy” // section of our [Terms of Service](https://cloud.google.com/terms/) // and the [Google Cloud Platform Subject to the Deprecation // Policy](https://cloud.google.com/terms/deprecation) documentation. LaunchStage string `json:"launchStage,omitempty"` // SamplePeriod: The sampling period of metric data points. For metrics // which are written periodically, consecutive data points are stored at // this time interval, excluding data loss due to errors. Metrics with a // higher granularity have a smaller sampling period. SamplePeriod string `json:"samplePeriod,omitempty"` // ForceSendFields is a list of field names (e.g. "IngestDelay") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "IngestDelay") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *MetricDescriptorMetadata) MarshalJSON() ([]byte, error) { type NoMethod MetricDescriptorMetadata raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // MetricRule: Bind API methods to metrics. Binding a method to a metric // causes that metric's configured quota behaviors to apply to the // method call. type MetricRule struct { // MetricCosts: Metrics to update when the selected methods are called, // and the associated cost applied to each metric. The key of the map is // the metric name, and the values are the amount increased for the // metric against which the quota limits are defined. The value must not // be negative. MetricCosts map[string]string `json:"metricCosts,omitempty"` // Selector: Selects the methods to which this rule applies. Refer to // selector for syntax details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. "MetricCosts") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "MetricCosts") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *MetricRule) MarshalJSON() ([]byte, error) { type NoMethod MetricRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Mixin: Declares an API Interface to be included in this interface. // The including interface must redeclare all the methods from the // included interface, but documentation and options are inherited as // follows: - If after comment and whitespace stripping, the // documentation string of the redeclared method is empty, it will be // inherited from the original method. - Each annotation belonging to // the service config (http, visibility) which is not set in the // redeclared method will be inherited. - If an http annotation is // inherited, the path pattern will be modified as follows. Any version // prefix will be replaced by the version of the including interface // plus the root path if specified. Example of a simple mixin: package // google.acl.v1; service AccessControl { // Get the underlying ACL // object. rpc GetAcl(GetAclRequest) returns (Acl) { option // (google.api.http).get = "/v1/{resource=**}:getAcl"; } } package // google.storage.v2; service Storage { // rpc GetAcl(GetAclRequest) // returns (Acl); // Get a data record. rpc GetData(GetDataRequest) // returns (Data) { option (google.api.http).get = "/v2/{resource=**}"; // } } Example of a mixin configuration: apis: - name: // google.storage.v2.Storage mixins: - name: google.acl.v1.AccessControl // The mixin construct implies that all methods in `AccessControl` are // also declared with same name and request/response types in `Storage`. // A documentation generator or annotation processor will see the // effective `Storage.GetAcl` method after inheriting documentation and // annotations as follows: service Storage { // Get the underlying ACL // object. rpc GetAcl(GetAclRequest) returns (Acl) { option // (google.api.http).get = "/v2/{resource=**}:getAcl"; } ... } Note how // the version in the path pattern changed from `v1` to `v2`. If the // `root` field in the mixin is specified, it should be a relative path // under which inherited HTTP paths are placed. Example: apis: - name: // google.storage.v2.Storage mixins: - name: google.acl.v1.AccessControl // root: acls This implies the following inherited HTTP annotation: // service Storage { // Get the underlying ACL object. rpc // GetAcl(GetAclRequest) returns (Acl) { option (google.api.http).get = // "/v2/acls/{resource=**}:getAcl"; } ... } type Mixin struct { // Name: The fully qualified name of the interface which is included. Name string `json:"name,omitempty"` // Root: If non-empty specifies a path under which inherited HTTP paths // are rooted. Root string `json:"root,omitempty"` // ForceSendFields is a list of field names (e.g. "Name") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Name") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Mixin) MarshalJSON() ([]byte, error) { type NoMethod Mixin raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // MonitoredResourceDescriptor: An object that describes the schema of a // MonitoredResource object using a type name and a set of labels. For // example, the monitored resource descriptor for Google Compute Engine // VM instances has a type of "gce_instance" and specifies the use of // the labels "instance_id" and "zone" to identify particular VM // instances. Different APIs can support different monitored resource // types. APIs generally provide a `list` method that returns the // monitored resource descriptors used by the API. type MonitoredResourceDescriptor struct { // Description: Optional. A detailed description of the monitored // resource type that might be used in documentation. Description string `json:"description,omitempty"` // DisplayName: Optional. A concise name for the monitored resource type // that might be displayed in user interfaces. It should be a Title // Cased Noun Phrase, without any article or other determiners. For // example, "Google Cloud SQL Database". DisplayName string `json:"displayName,omitempty"` // Labels: Required. A set of labels used to describe instances of this // monitored resource type. For example, an individual Google Cloud SQL // database is identified by values for the labels "database_id" and // "zone". Labels []*LabelDescriptor `json:"labels,omitempty"` // LaunchStage: Optional. The launch stage of the monitored resource // definition. // // Possible values: // "LAUNCH_STAGE_UNSPECIFIED" - Do not use this default value. // "UNIMPLEMENTED" - The feature is not yet implemented. Users can not // use it. // "PRELAUNCH" - Prelaunch features are hidden from users and are only // visible internally. // "EARLY_ACCESS" - Early Access features are limited to a closed // group of testers. To use these features, you must sign up in advance // and sign a Trusted Tester agreement (which includes confidentiality // provisions). These features may be unstable, changed in // backward-incompatible ways, and are not guaranteed to be released. // "ALPHA" - Alpha is a limited availability test for releases before // they are cleared for widespread use. By Alpha, all significant design // issues are resolved and we are in the process of verifying // functionality. Alpha customers need to apply for access, agree to // applicable terms, and have their projects allowlisted. Alpha releases // don’t have to be feature complete, no SLAs are provided, and there // are no technical support obligations, but they will be far enough // along that customers can actually use them in test environments or // for limited-use tests -- just like they would in normal production // cases. // "BETA" - Beta is the point at which we are ready to open a release // for any customer to use. There are no SLA or technical support // obligations in a Beta release. Products will be complete from a // feature perspective, but may have some open outstanding issues. Beta // releases are suitable for limited production use cases. // "GA" - GA features are open to all developers and are considered // stable and fully qualified for production use. // "DEPRECATED" - Deprecated features are scheduled to be shut down // and removed. For more information, see the “Deprecation Policy” // section of our [Terms of Service](https://cloud.google.com/terms/) // and the [Google Cloud Platform Subject to the Deprecation // Policy](https://cloud.google.com/terms/deprecation) documentation. LaunchStage string `json:"launchStage,omitempty"` // Name: Optional. The resource name of the monitored resource // descriptor: // "projects/{project_id}/monitoredResourceDescriptors/{type}" where // {type} is the value of the `type` field in this object and // {project_id} is a project ID that provides API-specific context for // accessing the type. APIs that do not use project information can use // the resource name format "monitoredResourceDescriptors/{type}". Name string `json:"name,omitempty"` // Type: Required. The monitored resource type. For example, the type // "cloudsql_database" represents databases in Google Cloud SQL. Type string `json:"type,omitempty"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *MonitoredResourceDescriptor) MarshalJSON() ([]byte, error) { type NoMethod MonitoredResourceDescriptor raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Monitoring: Monitoring configuration of the service. The example // below shows how to configure monitored resources and metrics for // monitoring. In the example, a monitored resource and two metrics are // defined. The `library.googleapis.com/book/returned_count` metric is // sent to both producer and consumer projects, whereas the // `library.googleapis.com/book/num_overdue` metric is only sent to the // consumer project. monitored_resources: - type: // library.googleapis.com/Branch display_name: "Library Branch" // description: "A branch of a library." launch_stage: GA labels: - key: // resource_container description: "The Cloud container (ie. project id) // for the Branch." - key: location description: "The location of the // library branch." - key: branch_id description: "The id of the // branch." metrics: - name: library.googleapis.com/book/returned_count // display_name: "Books Returned" description: "The count of books that // have been returned." launch_stage: GA metric_kind: DELTA value_type: // INT64 unit: "1" labels: - key: customer_id description: "The id of // the customer." - name: library.googleapis.com/book/num_overdue // display_name: "Books Overdue" description: "The current number of // overdue books." launch_stage: GA metric_kind: GAUGE value_type: INT64 // unit: "1" labels: - key: customer_id description: "The id of the // customer." monitoring: producer_destinations: - monitored_resource: // library.googleapis.com/Branch metrics: - // library.googleapis.com/book/returned_count consumer_destinations: - // monitored_resource: library.googleapis.com/Branch metrics: - // library.googleapis.com/book/returned_count - // library.googleapis.com/book/num_overdue type Monitoring struct { // ConsumerDestinations: Monitoring configurations for sending metrics // to the consumer project. There can be multiple consumer destinations. // A monitored resource type may appear in multiple monitoring // destinations if different aggregations are needed for different sets // of metrics associated with that monitored resource type. A monitored // resource and metric pair may only be used once in the Monitoring // configuration. ConsumerDestinations []*MonitoringDestination `json:"consumerDestinations,omitempty"` // ProducerDestinations: Monitoring configurations for sending metrics // to the producer project. There can be multiple producer destinations. // A monitored resource type may appear in multiple monitoring // destinations if different aggregations are needed for different sets // of metrics associated with that monitored resource type. A monitored // resource and metric pair may only be used once in the Monitoring // configuration. ProducerDestinations []*MonitoringDestination `json:"producerDestinations,omitempty"` // ForceSendFields is a list of field names (e.g. // "ConsumerDestinations") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ConsumerDestinations") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *Monitoring) MarshalJSON() ([]byte, error) { type NoMethod Monitoring raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // MonitoringDestination: Configuration of a specific monitoring // destination (the producer project or the consumer project). type MonitoringDestination struct { // Metrics: Types of the metrics to report to this monitoring // destination. Each type must be defined in Service.metrics section. Metrics []string `json:"metrics,omitempty"` // MonitoredResource: The monitored resource type. The type must be // defined in Service.monitored_resources section. MonitoredResource string `json:"monitoredResource,omitempty"` // ForceSendFields is a list of field names (e.g. "Metrics") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Metrics") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *MonitoringDestination) MarshalJSON() ([]byte, error) { type NoMethod MonitoringDestination raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // OAuthRequirements: OAuth scopes are a way to define data and // permissions on data. For example, there are scopes defined for // "Read-only access to Google Calendar" and "Access to Cloud Platform". // Users can consent to a scope for an application, giving it permission // to access that data on their behalf. OAuth scope specifications // should be fairly coarse grained; a user will need to see and // understand the text description of what your scope means. In most // cases: use one or at most two OAuth scopes for an entire family of // products. If your product has multiple APIs, you should probably be // sharing the OAuth scope across all of those APIs. When you need finer // grained OAuth consent screens: talk with your product management // about how developers will use them in practice. Please note that even // though each of the canonical scopes is enough for a request to be // accepted and passed to the backend, a request can still fail due to // the backend requiring additional scopes or permissions. type OAuthRequirements struct { // CanonicalScopes: The list of publicly documented OAuth scopes that // are allowed access. An OAuth token containing any of these scopes // will be accepted. Example: canonical_scopes: // https://www.googleapis.com/auth/calendar, // https://www.googleapis.com/auth/calendar.read CanonicalScopes string `json:"canonicalScopes,omitempty"` // ForceSendFields is a list of field names (e.g. "CanonicalScopes") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "CanonicalScopes") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *OAuthRequirements) MarshalJSON() ([]byte, error) { type NoMethod OAuthRequirements raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Operation: This resource represents a long-running operation that is // the result of a network API call. type Operation struct { // Done: If the value is `false`, it means the operation is still in // progress. If `true`, the operation is completed, and either `error` // or `response` is available. Done bool `json:"done,omitempty"` // Error: The error result of the operation in case of failure or // cancellation. Error *Status `json:"error,omitempty"` // Metadata: Service-specific metadata associated with the operation. It // typically contains progress information and common metadata such as // create time. Some services might not provide such metadata. Any // method that returns a long-running operation should document the // metadata type, if any. Metadata googleapi.RawMessage `json:"metadata,omitempty"` // Name: The server-assigned name, which is only unique within the same // service that originally returns it. If you use the default HTTP // mapping, the `name` should be a resource name ending with // `operations/{unique_id}`. Name string `json:"name,omitempty"` // Response: The normal response of the operation in case of success. If // the original method returns no data on success, such as `Delete`, the // response is `google.protobuf.Empty`. If the original method is // standard `Get`/`Create`/`Update`, the response should be the // resource. For other methods, the response should have the type // `XxxResponse`, where `Xxx` is the original method name. For example, // if the original method name is `TakeSnapshot()`, the inferred // response type is `TakeSnapshotResponse`. Response googleapi.RawMessage `json:"response,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Done") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Done") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Operation) MarshalJSON() ([]byte, error) { type NoMethod Operation raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // OperationMetadata: The operation metadata returned for the batchend // services operation. type OperationMetadata struct { // ResourceNames: The full name of the resources that this operation is // directly associated with. ResourceNames []string `json:"resourceNames,omitempty"` // ForceSendFields is a list of field names (e.g. "ResourceNames") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "ResourceNames") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *OperationMetadata) MarshalJSON() ([]byte, error) { type NoMethod OperationMetadata raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Option: A protocol buffer option, which can be attached to a message, // field, enumeration, etc. type Option struct { // Name: The option's name. For protobuf built-in options (options // defined in descriptor.proto), this is the short name. For example, // "map_entry". For custom options, it should be the fully-qualified // name. For example, "google.api.http". Name string `json:"name,omitempty"` // Value: The option's value packed in an Any message. If the value is a // primitive, the corresponding wrapper type defined in // google/protobuf/wrappers.proto should be used. If the value is an // enum, it should be stored as an int32 value using the // google.protobuf.Int32Value type. Value googleapi.RawMessage `json:"value,omitempty"` // ForceSendFields is a list of field names (e.g. "Name") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Name") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Option) MarshalJSON() ([]byte, error) { type NoMethod Option raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // OverrideInlineSource: Import data embedded in the request message type OverrideInlineSource struct { // Overrides: The overrides to create. Each override must have a value // for 'metric' and 'unit', to specify which metric and which limit the // override should be applied to. The 'name' field of the override does // not need to be set; it is ignored. Overrides []*QuotaOverride `json:"overrides,omitempty"` // ForceSendFields is a list of field names (e.g. "Overrides") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Overrides") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *OverrideInlineSource) MarshalJSON() ([]byte, error) { type NoMethod OverrideInlineSource raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Page: Represents a documentation page. A page can contain subpages to // represent nested documentation set structure. type Page struct { // Content: The Markdown content of the page. You can use (== include // {path} ==) to include content from a Markdown file. Content string `json:"content,omitempty"` // Name: The name of the page. It will be used as an identity of the // page to generate URI of the page, text of the link to this page in // navigation, etc. The full page name (start from the root page name to // this page concatenated with `.`) can be used as reference to the page // in your documentation. For example: pages: - name: Tutorial content: // (== include tutorial.md ==) subpages: - name: Java content: (== // include tutorial_java.md ==) You can reference `Java` page using // Markdown reference link syntax: `Java`. Name string `json:"name,omitempty"` // Subpages: Subpages of this page. The order of subpages specified here // will be honored in the generated docset. Subpages []*Page `json:"subpages,omitempty"` // ForceSendFields is a list of field names (e.g. "Content") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Content") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Page) MarshalJSON() ([]byte, error) { type NoMethod Page raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Quota: Quota configuration helps to achieve fairness and budgeting in // service usage. The metric based quota configuration works this way: - // The service configuration defines a set of metrics. - For API calls, // the quota.metric_rules maps methods to metrics with corresponding // costs. - The quota.limits defines limits on the metrics, which will // be used for quota checks at runtime. An example quota configuration // in yaml format: quota: limits: - name: apiWriteQpsPerProject metric: // library.googleapis.com/write_calls unit: "1/min/{project}" # rate // limit for consumer projects values: STANDARD: 10000 # The metric // rules bind all methods to the read_calls metric, # except for the // UpdateBook and DeleteBook methods. These two methods # are mapped to // the write_calls metric, with the UpdateBook method # consuming at // twice rate as the DeleteBook method. metric_rules: - selector: "*" // metric_costs: library.googleapis.com/read_calls: 1 - selector: // google.example.library.v1.LibraryService.UpdateBook metric_costs: // library.googleapis.com/write_calls: 2 - selector: // google.example.library.v1.LibraryService.DeleteBook metric_costs: // library.googleapis.com/write_calls: 1 Corresponding Metric // definition: metrics: - name: library.googleapis.com/read_calls // display_name: Read requests metric_kind: DELTA value_type: INT64 - // name: library.googleapis.com/write_calls display_name: Write requests // metric_kind: DELTA value_type: INT64 type Quota struct { // Limits: List of `QuotaLimit` definitions for the service. Limits []*QuotaLimit `json:"limits,omitempty"` // MetricRules: List of `MetricRule` definitions, each one mapping a // selected method to one or more metrics. MetricRules []*MetricRule `json:"metricRules,omitempty"` // ForceSendFields is a list of field names (e.g. "Limits") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Limits") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Quota) MarshalJSON() ([]byte, error) { type NoMethod Quota raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // QuotaBucket: A quota bucket is a quota provisioning unit for a // specific set of dimensions. type QuotaBucket struct { // AdminOverride: Admin override on this quota bucket. AdminOverride *QuotaOverride `json:"adminOverride,omitempty"` // ConsumerOverride: Consumer override on this quota bucket. ConsumerOverride *QuotaOverride `json:"consumerOverride,omitempty"` // DefaultLimit: The default limit of this quota bucket, as specified by // the service configuration. DefaultLimit int64 `json:"defaultLimit,omitempty,string"` // Dimensions: The dimensions of this quota bucket. If this map is // empty, this is the global bucket, which is the default quota value // applied to all requests that do not have a more specific override. If // this map is nonempty, the default limit, effective limit, and quota // overrides apply only to requests that have the dimensions given in // the map. For example, if the map has key "region" and value // "us-east-1", then the specified effective limit is only effective in // that region, and the specified overrides apply only in that region. Dimensions map[string]string `json:"dimensions,omitempty"` // EffectiveLimit: The effective limit of this quota bucket. Equal to // default_limit if there are no overrides. EffectiveLimit int64 `json:"effectiveLimit,omitempty,string"` // ProducerOverride: Producer override on this quota bucket. ProducerOverride *QuotaOverride `json:"producerOverride,omitempty"` // ForceSendFields is a list of field names (e.g. "AdminOverride") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AdminOverride") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *QuotaBucket) MarshalJSON() ([]byte, error) { type NoMethod QuotaBucket raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // QuotaLimit: `QuotaLimit` defines a specific limit that applies over a // specified duration for a limit type. There can be at most one limit // for a duration and limit type combination defined within a // `QuotaGroup`. type QuotaLimit struct { // DefaultLimit: Default number of tokens that can be consumed during // the specified duration. This is the number of tokens assigned when a // client application developer activates the service for his/her // project. Specifying a value of 0 will block all requests. This can be // used if you are provisioning quota to selected consumers and blocking // others. Similarly, a value of -1 will indicate an unlimited quota. No // other negative values are allowed. Used by group-based quotas only. DefaultLimit int64 `json:"defaultLimit,omitempty,string"` // Description: Optional. User-visible, extended description for this // quota limit. Should be used only when more context is needed to // understand this limit than provided by the limit's display name (see: // `display_name`). Description string `json:"description,omitempty"` // DisplayName: User-visible display name for this limit. Optional. If // not set, the UI will provide a default display name based on the // quota configuration. This field can be used to override the default // display name generated from the configuration. DisplayName string `json:"displayName,omitempty"` // Duration: Duration of this limit in textual notation. Must be "100s" // or "1d". Used by group-based quotas only. Duration string `json:"duration,omitempty"` // FreeTier: Free tier value displayed in the Developers Console for // this limit. The free tier is the number of tokens that will be // subtracted from the billed amount when billing is enabled. This field // can only be set on a limit with duration "1d", in a billable group; // it is invalid on any other limit. If this field is not set, it // defaults to 0, indicating that there is no free tier for this // service. Used by group-based quotas only. FreeTier int64 `json:"freeTier,omitempty,string"` // MaxLimit: Maximum number of tokens that can be consumed during the // specified duration. Client application developers can override the // default limit up to this maximum. If specified, this value cannot be // set to a value less than the default limit. If not specified, it is // set to the default limit. To allow clients to apply overrides with no // upper bound, set this to -1, indicating unlimited maximum quota. Used // by group-based quotas only. MaxLimit int64 `json:"maxLimit,omitempty,string"` // Metric: The name of the metric this quota limit applies to. The quota // limits with the same metric will be checked together during runtime. // The metric must be defined within the service config. Metric string `json:"metric,omitempty"` // Name: Name of the quota limit. The name must be provided, and it must // be unique within the service. The name can only include alphanumeric // characters as well as '-'. The maximum length of the limit name is 64 // characters. Name string `json:"name,omitempty"` // Unit: Specify the unit of the quota limit. It uses the same syntax as // Metric.unit. The supported unit kinds are determined by the quota // backend system. Here are some examples: * "1/min/{project}" for quota // per minute per project. Note: the order of unit components is // insignificant. The "1" at the beginning is required to follow the // metric unit syntax. Unit string `json:"unit,omitempty"` // Values: Tiered limit values. You must specify this as a key:value // pair, with an integer value that is the maximum number of requests // allowed for the specified unit. Currently only STANDARD is supported. Values map[string]string `json:"values,omitempty"` // ForceSendFields is a list of field names (e.g. "DefaultLimit") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "DefaultLimit") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *QuotaLimit) MarshalJSON() ([]byte, error) { type NoMethod QuotaLimit raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // QuotaOverride: A quota override type QuotaOverride struct { // AdminOverrideAncestor: The resource name of the ancestor that // requested the override. For example: "organizations/12345" or // "folders/67890". Used by admin overrides only. AdminOverrideAncestor string `json:"adminOverrideAncestor,omitempty"` // Dimensions: If this map is nonempty, then this override applies only // to specific values for dimensions defined in the limit unit. For // example, an override on a limit with the unit 1/{project}/{region} // could contain an entry with the key "region" and the value // "us-east-1"; the override is only applied to quota consumed in that // region. This map has the following restrictions: * Keys that are not // defined in the limit's unit are not valid keys. Any string appearing // in {brackets} in the unit (besides {project} or {user}) is a defined // key. * "project" is not a valid key; the project is already specified // in the parent resource name. * "user" is not a valid key; the API // does not support quota overrides that apply only to a specific user. // * If "region" appears as a key, its value must be a valid Cloud // region. * If "zone" appears as a key, its value must be a valid Cloud // zone. * If any valid key other than "region" or "zone" appears in the // map, then all valid keys other than "region" or "zone" must also // appear in the map. Dimensions map[string]string `json:"dimensions,omitempty"` // Metric: The name of the metric to which this override applies. An // example name would be: `compute.googleapis.com/cpus` Metric string `json:"metric,omitempty"` // Name: The resource name of the override. This name is generated by // the server when the override is created. Example names would be: // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/com // pute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4 // a3f2c1d` // `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/com // pute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverride // s/4a3f2c1d` The resource name is intended to be opaque and should not // be parsed for its component strings, since its representation could // change in the future. Name string `json:"name,omitempty"` // OverrideValue: The overriding quota limit value. Can be any // nonnegative integer, or -1 (unlimited quota). OverrideValue int64 `json:"overrideValue,omitempty,string"` // Unit: The limit unit of the limit to which this override applies. An // example unit would be: `1/{project}/{region}` Note that `{project}` // and `{region}` are not placeholders in this example; the literal // characters `{` and `}` occur in the string. Unit string `json:"unit,omitempty"` // ForceSendFields is a list of field names (e.g. // "AdminOverrideAncestor") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AdminOverrideAncestor") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *QuotaOverride) MarshalJSON() ([]byte, error) { type NoMethod QuotaOverride raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Service: A service that is available for use by the consumer. type Service struct { // Config: The service configuration of the available service. Some // fields may be filtered out of the configuration in responses to the // `ListServices` method. These fields are present only in responses to // the `GetService` method. Config *ServiceConfig `json:"config,omitempty"` // Name: The resource name of the consumer and service. A valid name // would be: - projects/123/services/serviceusage.googleapis.com Name string `json:"name,omitempty"` // Parent: The resource name of the consumer. A valid name would be: - // projects/123 Parent string `json:"parent,omitempty"` // State: Whether or not the service has been enabled for use by the // consumer. // // Possible values: // "STATE_UNSPECIFIED" - The default value, which indicates that the // enabled state of the service is unspecified or not meaningful. // Currently, all consumers other than projects (such as folders and // organizations) are always in this state. // "DISABLED" - The service cannot be used by this consumer. It has // either been explicitly disabled, or has never been enabled. // "ENABLED" - The service has been explicitly enabled for use by this // consumer. State string `json:"state,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Config") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Config") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Service) MarshalJSON() ([]byte, error) { type NoMethod Service raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ServiceConfig: The configuration of the service. type ServiceConfig struct { // Apis: A list of API interfaces exported by this service. Contains // only the names, versions, and method names of the interfaces. Apis []*Api `json:"apis,omitempty"` // Authentication: Auth configuration. Contains only the OAuth rules. Authentication *Authentication `json:"authentication,omitempty"` // Documentation: Additional API documentation. Contains only the // summary and the documentation URL. Documentation *Documentation `json:"documentation,omitempty"` // Endpoints: Configuration for network endpoints. Contains only the // names and aliases of the endpoints. Endpoints []*Endpoint `json:"endpoints,omitempty"` // MonitoredResources: Defines the monitored resources used by this // service. This is required by the Service.monitoring and // Service.logging configurations. MonitoredResources []*MonitoredResourceDescriptor `json:"monitoredResources,omitempty"` // Monitoring: Monitoring configuration. This should not include the // 'producer_destinations' field. Monitoring *Monitoring `json:"monitoring,omitempty"` // Name: The DNS address at which this service is available. An example // DNS address would be: `calendar.googleapis.com`. Name string `json:"name,omitempty"` // Quota: Quota configuration. Quota *Quota `json:"quota,omitempty"` // Title: The product title for this service. Title string `json:"title,omitempty"` // Usage: Configuration controlling usage of this service. Usage *Usage `json:"usage,omitempty"` // ForceSendFields is a list of field names (e.g. "Apis") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Apis") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ServiceConfig) MarshalJSON() ([]byte, error) { type NoMethod ServiceConfig raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ServiceIdentity: Service identity for a service. This is the identity // that service producer should use to access consumer resources. type ServiceIdentity struct { // Email: The email address of the service account that a service // producer would use to access consumer resources. Email string `json:"email,omitempty"` // UniqueId: The unique and stable id of the service account. // https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts#ServiceAccount UniqueId string `json:"uniqueId,omitempty"` // ForceSendFields is a list of field names (e.g. "Email") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Email") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ServiceIdentity) MarshalJSON() ([]byte, error) { type NoMethod ServiceIdentity raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SourceContext: `SourceContext` represents information about the // source of a protobuf element, like the file in which it is defined. type SourceContext struct { // FileName: The path-qualified name of the .proto file that contained // the associated protobuf element. For example: // "google/protobuf/source_context.proto". FileName string `json:"fileName,omitempty"` // ForceSendFields is a list of field names (e.g. "FileName") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "FileName") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SourceContext) MarshalJSON() ([]byte, error) { type NoMethod SourceContext raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SourceInfo: Source information used to create a Service Config type SourceInfo struct { // SourceFiles: All files used during config generation. SourceFiles []googleapi.RawMessage `json:"sourceFiles,omitempty"` // ForceSendFields is a list of field names (e.g. "SourceFiles") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "SourceFiles") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SourceInfo) MarshalJSON() ([]byte, error) { type NoMethod SourceInfo raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Status: The `Status` type defines a logical error model that is // suitable for different programming environments, including REST APIs // and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each // `Status` message contains three pieces of data: error code, error // message, and error details. You can find out more about this error // model and how to work with it in the [API Design // Guide](https://cloud.google.com/apis/design/errors). type Status struct { // Code: The status code, which should be an enum value of // google.rpc.Code. Code int64 `json:"code,omitempty"` // Details: A list of messages that carry the error details. There is a // common set of message types for APIs to use. Details []googleapi.RawMessage `json:"details,omitempty"` // Message: A developer-facing error message, which should be in // English. Any user-facing error message should be localized and sent // in the google.rpc.Status.details field, or localized by the client. Message string `json:"message,omitempty"` // ForceSendFields is a list of field names (e.g. "Code") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Code") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Status) MarshalJSON() ([]byte, error) { type NoMethod Status raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SystemParameter: Define a parameter's name and location. The // parameter may be passed as either an HTTP header or a URL query // parameter, and if both are passed the behavior is // implementation-dependent. type SystemParameter struct { // HttpHeader: Define the HTTP header name to use for the parameter. It // is case insensitive. HttpHeader string `json:"httpHeader,omitempty"` // Name: Define the name of the parameter, such as "api_key" . It is // case sensitive. Name string `json:"name,omitempty"` // UrlQueryParameter: Define the URL query parameter name to use for the // parameter. It is case sensitive. UrlQueryParameter string `json:"urlQueryParameter,omitempty"` // ForceSendFields is a list of field names (e.g. "HttpHeader") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "HttpHeader") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SystemParameter) MarshalJSON() ([]byte, error) { type NoMethod SystemParameter raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SystemParameterRule: Define a system parameter rule mapping system // parameter definitions to methods. type SystemParameterRule struct { // Parameters: Define parameters. Multiple names may be defined for a // parameter. For a given method call, only one of them should be used. // If multiple names are used the behavior is implementation-dependent. // If none of the specified names are present the behavior is // parameter-dependent. Parameters []*SystemParameter `json:"parameters,omitempty"` // Selector: Selects the methods to which this rule applies. Use '*' to // indicate all methods in all APIs. Refer to selector for syntax // details. Selector string `json:"selector,omitempty"` // ForceSendFields is a list of field names (e.g. "Parameters") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Parameters") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SystemParameterRule) MarshalJSON() ([]byte, error) { type NoMethod SystemParameterRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SystemParameters: ### System parameter configuration A system // parameter is a special kind of parameter defined by the API system, // not by an individual API. It is typically mapped to an HTTP header // and/or a URL query parameter. This configuration specifies which // methods change the names of the system parameters. type SystemParameters struct { // Rules: Define system parameters. The parameters defined here will // override the default parameters implemented by the system. If this // field is missing from the service config, default system parameters // will be used. Default system parameters and names is // implementation-dependent. Example: define api key for all methods // system_parameters rules: - selector: "*" parameters: - name: api_key // url_query_parameter: api_key Example: define 2 api key names for a // specific method. system_parameters rules: - selector: "/ListShelves" // parameters: - name: api_key http_header: Api-Key1 - name: api_key // http_header: Api-Key2 **NOTE:** All service configuration rules // follow "last one wins" order. Rules []*SystemParameterRule `json:"rules,omitempty"` // ForceSendFields is a list of field names (e.g. "Rules") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Rules") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SystemParameters) MarshalJSON() ([]byte, error) { type NoMethod SystemParameters raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Type: A protocol buffer message type. type Type struct { // Fields: The list of fields. Fields []*Field `json:"fields,omitempty"` // Name: The fully qualified message name. Name string `json:"name,omitempty"` // Oneofs: The list of types appearing in `oneof` definitions in this // type. Oneofs []string `json:"oneofs,omitempty"` // Options: The protocol buffer options. Options []*Option `json:"options,omitempty"` // SourceContext: The source context. SourceContext *SourceContext `json:"sourceContext,omitempty"` // Syntax: The source syntax. // // Possible values: // "SYNTAX_PROTO2" - Syntax `proto2`. // "SYNTAX_PROTO3" - Syntax `proto3`. Syntax string `json:"syntax,omitempty"` // ForceSendFields is a list of field names (e.g. "Fields") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Fields") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Type) MarshalJSON() ([]byte, error) { type NoMethod Type raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Usage: Configuration controlling usage of a service. type Usage struct { // ProducerNotificationChannel: The full resource name of a channel used // for sending notifications to the service producer. Google Service // Management currently only supports [Google Cloud // Pub/Sub](https://cloud.google.com/pubsub) as a notification channel. // To use Google Cloud Pub/Sub as the channel, this must be the name of // a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format // documented in https://cloud.google.com/pubsub/docs/overview. ProducerNotificationChannel string `json:"producerNotificationChannel,omitempty"` // Requirements: Requirements that must be satisfied before a consumer // project can use the service. Each requirement is of the form /; for // example 'serviceusage.googleapis.com/billing-enabled'. Requirements []string `json:"requirements,omitempty"` // Rules: A list of usage rules that apply to individual API methods. // **NOTE:** All service configuration rules follow "last one wins" // order. Rules []*UsageRule `json:"rules,omitempty"` // ServiceIdentity: The configuration of a per-product per-project // service identity. ServiceIdentity *GoogleApiServiceIdentity `json:"serviceIdentity,omitempty"` // ForceSendFields is a list of field names (e.g. // "ProducerNotificationChannel") to unconditionally include in API // requests. By default, fields with empty values are omitted from API // requests. However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. // "ProducerNotificationChannel") to include in API requests with the // JSON null value. By default, fields with empty values are omitted // from API requests. However, any field with an empty value appearing // in NullFields will be sent to the server as null. It is an error if a // field in this list has a non-empty value. This may be used to include // null fields in Patch requests. NullFields []string `json:"-"` } func (s *Usage) MarshalJSON() ([]byte, error) { type NoMethod Usage raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // UsageRule: Usage configuration rules for the service. NOTE: Under // development. Use this rule to configure unregistered calls for the // service. Unregistered calls are calls that do not contain consumer // project identity. (Example: calls that do not contain an API key). By // default, API methods do not allow unregistered calls, and each method // call must be identified by a consumer project identity. Use this rule // to allow/disallow unregistered calls. Example of an API that wants to // allow unregistered calls for entire service. usage: rules: - // selector: "*" allow_unregistered_calls: true Example of a method that // wants to allow unregistered calls. usage: rules: - selector: // "google.example.library.v1.LibraryService.CreateBook" // allow_unregistered_calls: true type UsageRule struct { // AllowUnregisteredCalls: If true, the selected method allows // unregistered calls, e.g. calls that don't identify any user or // application. AllowUnregisteredCalls bool `json:"allowUnregisteredCalls,omitempty"` // Selector: Selects the methods to which this rule applies. Use '*' to // indicate all methods in all APIs. Refer to selector for syntax // details. Selector string `json:"selector,omitempty"` // SkipServiceControl: If true, the selected method should skip service // control and the control plane features, such as quota and billing, // will not be available. This flag is used by Google Cloud Endpoints to // bypass checks for internal methods, such as service health check // methods. SkipServiceControl bool `json:"skipServiceControl,omitempty"` // ForceSendFields is a list of field names (e.g. // "AllowUnregisteredCalls") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AllowUnregisteredCalls") // to include in API requests with the JSON null value. By default, // fields with empty values are omitted from API requests. However, any // field with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *UsageRule) MarshalJSON() ([]byte, error) { type NoMethod UsageRule raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // method id "serviceusage.operations.get": type OperationsGetCall struct { s *APIService name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Gets the latest state of a long-running operation. Clients can // use this method to poll the operation result at intervals as // recommended by the API service. func (r *OperationsService) Get(name string) *OperationsGetCall { c := &OperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *OperationsGetCall) Fields(s ...googleapi.Field) *OperationsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *OperationsGetCall) IfNoneMatch(entityTag string) *OperationsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *OperationsGetCall) Context(ctx context.Context) *OperationsGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *OperationsGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *OperationsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.operations.get" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *OperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.", // "flatPath": "v1beta1/operations/{operationsId}", // "httpMethod": "GET", // "id": "serviceusage.operations.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "The name of the operation resource.", // "location": "path", // "pattern": "^operations/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.operations.list": type OperationsListCall struct { s *APIService urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Lists operations that match the specified filter in the // request. If the server doesn't support this method, it returns // `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to // override the binding to use different resource name schemes, such as // `users/*/operations`. To override the binding, API services can add a // binding such as "/v1/{name=users/*}/operations" to their service // configuration. For backwards compatibility, the default name includes // the operations collection id, however overriding users must ensure // the name binding is the parent resource, without the operations // collection id. func (r *OperationsService) List() *OperationsListCall { c := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} return c } // Filter sets the optional parameter "filter": The standard list // filter. func (c *OperationsListCall) Filter(filter string) *OperationsListCall { c.urlParams_.Set("filter", filter) return c } // Name sets the optional parameter "name": The name of the operation's // parent resource. func (c *OperationsListCall) Name(name string) *OperationsListCall { c.urlParams_.Set("name", name) return c } // PageSize sets the optional parameter "pageSize": The standard list // page size. func (c *OperationsListCall) PageSize(pageSize int64) *OperationsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": The standard list // page token. func (c *OperationsListCall) PageToken(pageToken string) *OperationsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *OperationsListCall) Fields(s ...googleapi.Field) *OperationsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *OperationsListCall) IfNoneMatch(entityTag string) *OperationsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *OperationsListCall) Context(ctx context.Context) *OperationsListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *OperationsListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *OperationsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/operations") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.operations.list" call. // Exactly one of *ListOperationsResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListOperationsResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *OperationsListCall) Do(opts ...googleapi.CallOption) (*ListOperationsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListOperationsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `\"/v1/{name=users/*}/operations\"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.", // "flatPath": "v1beta1/operations", // "httpMethod": "GET", // "id": "serviceusage.operations.list", // "parameterOrder": [], // "parameters": { // "filter": { // "description": "The standard list filter.", // "location": "query", // "type": "string" // }, // "name": { // "description": "The name of the operation's parent resource.", // "location": "query", // "type": "string" // }, // "pageSize": { // "description": "The standard list page size.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "The standard list page token.", // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/operations", // "response": { // "$ref": "ListOperationsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *OperationsListCall) Pages(ctx context.Context, f func(*ListOperationsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "serviceusage.services.batchEnable": type ServicesBatchEnableCall struct { s *APIService parent string batchenableservicesrequest *BatchEnableServicesRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // BatchEnable: Enable multiple services on a project. The operation is // atomic: if enabling any service fails, then the entire batch fails, // and no state changes occur. Operation func (r *ServicesService) BatchEnable(parent string, batchenableservicesrequest *BatchEnableServicesRequest) *ServicesBatchEnableCall { c := &ServicesBatchEnableCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent c.batchenableservicesrequest = batchenableservicesrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesBatchEnableCall) Fields(s ...googleapi.Field) *ServicesBatchEnableCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesBatchEnableCall) Context(ctx context.Context) *ServicesBatchEnableCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesBatchEnableCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesBatchEnableCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchenableservicesrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/services:batchEnable") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.batchEnable" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesBatchEnableCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Enable multiple services on a project. The operation is atomic: if enabling any service fails, then the entire batch fails, and no state changes occur. Operation", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services:batchEnable", // "httpMethod": "POST", // "id": "serviceusage.services.batchEnable", // "parameterOrder": [ // "parent" // ], // "parameters": { // "parent": { // "description": "Parent to enable services on. An example name would be: `projects/123` where `123` is the project number (not project ID). The `BatchEnableServices` method currently only supports projects.", // "location": "path", // "pattern": "^[^/]+/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/services:batchEnable", // "request": { // "$ref": "BatchEnableServicesRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.disable": type ServicesDisableCall struct { s *APIService name string disableservicerequest *DisableServiceRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Disable: Disable a service so that it can no longer be used with a // project. This prevents unintended usage that may cause unexpected // billing charges or security leaks. It is not valid to call the // disable method on a service that is not currently enabled. Callers // will receive a `FAILED_PRECONDITION` status if the target service is // not currently enabled. Operation func (r *ServicesService) Disable(name string, disableservicerequest *DisableServiceRequest) *ServicesDisableCall { c := &ServicesDisableCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.disableservicerequest = disableservicerequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesDisableCall) Fields(s ...googleapi.Field) *ServicesDisableCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesDisableCall) Context(ctx context.Context) *ServicesDisableCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesDisableCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesDisableCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.disableservicerequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:disable") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.disable" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesDisableCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Disable a service so that it can no longer be used with a project. This prevents unintended usage that may cause unexpected billing charges or security leaks. It is not valid to call the disable method on a service that is not currently enabled. Callers will receive a `FAILED_PRECONDITION` status if the target service is not currently enabled. Operation", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}:disable", // "httpMethod": "POST", // "id": "serviceusage.services.disable", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Name of the consumer and service to disable the service on. The enable and disable methods currently only support projects. An example name would be: `projects/123/services/serviceusage.googleapis.com` where `123` is the project number (not project ID).", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:disable", // "request": { // "$ref": "DisableServiceRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.enable": type ServicesEnableCall struct { s *APIService name string enableservicerequest *EnableServiceRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Enable: Enable a service so that it can be used with a project. // Operation func (r *ServicesService) Enable(name string, enableservicerequest *EnableServiceRequest) *ServicesEnableCall { c := &ServicesEnableCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.enableservicerequest = enableservicerequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesEnableCall) Fields(s ...googleapi.Field) *ServicesEnableCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesEnableCall) Context(ctx context.Context) *ServicesEnableCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesEnableCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesEnableCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.enableservicerequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:enable") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.enable" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesEnableCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Enable a service so that it can be used with a project. Operation", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}:enable", // "httpMethod": "POST", // "id": "serviceusage.services.enable", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Name of the consumer and service to enable the service on. The `EnableService` and `DisableService` methods currently only support projects. Enabling a service requires that the service is public or is shared with the user enabling the service. An example name would be: `projects/123/services/serviceusage.googleapis.com` where `123` is the project number (not project ID).", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:enable", // "request": { // "$ref": "EnableServiceRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.generateServiceIdentity": type ServicesGenerateServiceIdentityCall struct { s *APIService parent string urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // GenerateServiceIdentity: Generate service identity for service. func (r *ServicesService) GenerateServiceIdentity(parent string) *ServicesGenerateServiceIdentityCall { c := &ServicesGenerateServiceIdentityCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesGenerateServiceIdentityCall) Fields(s ...googleapi.Field) *ServicesGenerateServiceIdentityCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesGenerateServiceIdentityCall) Context(ctx context.Context) *ServicesGenerateServiceIdentityCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesGenerateServiceIdentityCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesGenerateServiceIdentityCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}:generateServiceIdentity") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.generateServiceIdentity" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesGenerateServiceIdentityCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Generate service identity for service.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}:generateServiceIdentity", // "httpMethod": "POST", // "id": "serviceusage.services.generateServiceIdentity", // "parameterOrder": [ // "parent" // ], // "parameters": { // "parent": { // "description": "Name of the consumer and service to generate an identity for. The `GenerateServiceIdentity` methods currently only support projects. An example name would be: `projects/123/services/example.googleapis.com` where `123` is the project number.", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}:generateServiceIdentity", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.get": type ServicesGetCall struct { s *APIService name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Returns the service configuration and enabled state for a given // service. func (r *ServicesService) Get(name string) *ServicesGetCall { c := &ServicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesGetCall) Fields(s ...googleapi.Field) *ServicesGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesGetCall) IfNoneMatch(entityTag string) *ServicesGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesGetCall) Context(ctx context.Context) *ServicesGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.get" call. // Exactly one of *Service or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Service.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ServicesGetCall) Do(opts ...googleapi.CallOption) (*Service, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Service{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Returns the service configuration and enabled state for a given service.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}", // "httpMethod": "GET", // "id": "serviceusage.services.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Name of the consumer and service to get the `ConsumerState` for. An example name would be: `projects/123/services/serviceusage.googleapis.com` where `123` is the project number (not project ID).", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "Service" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // method id "serviceusage.services.list": type ServicesListCall struct { s *APIService parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: List all services available to the specified project, and the // current state of those services with respect to the project. The list // includes all public services, all services for which the calling user // has the `servicemanagement.services.bind` permission, and all // services that have already been enabled on the project. The list can // be filtered to only include services in a specific state, for example // to only include services enabled on the project. func (r *ServicesService) List(parent string) *ServicesListCall { c := &ServicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // Filter sets the optional parameter "filter": Only list services that // conform to the given filter. The allowed filter strings are // `state:ENABLED` and `state:DISABLED`. func (c *ServicesListCall) Filter(filter string) *ServicesListCall { c.urlParams_.Set("filter", filter) return c } // PageSize sets the optional parameter "pageSize": Requested size of // the next page of data. Requested page size cannot exceed 200. If not // set, the default page size is 50. func (c *ServicesListCall) PageSize(pageSize int64) *ServicesListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": Token identifying // which result to start with, which is returned by a previous list // call. func (c *ServicesListCall) PageToken(pageToken string) *ServicesListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesListCall) Fields(s ...googleapi.Field) *ServicesListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesListCall) IfNoneMatch(entityTag string) *ServicesListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesListCall) Context(ctx context.Context) *ServicesListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/services") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.list" call. // Exactly one of *ListServicesResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListServicesResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesListCall) Do(opts ...googleapi.CallOption) (*ListServicesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListServicesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "List all services available to the specified project, and the current state of those services with respect to the project. The list includes all public services, all services for which the calling user has the `servicemanagement.services.bind` permission, and all services that have already been enabled on the project. The list can be filtered to only include services in a specific state, for example to only include services enabled on the project.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services", // "httpMethod": "GET", // "id": "serviceusage.services.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "filter": { // "description": "Only list services that conform to the given filter. The allowed filter strings are `state:ENABLED` and `state:DISABLED`.", // "location": "query", // "type": "string" // }, // "pageSize": { // "description": "Requested size of the next page of data. Requested page size cannot exceed 200. If not set, the default page size is 50.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Token identifying which result to start with, which is returned by a previous list call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "Parent to search for services on. An example name would be: `projects/123` where `123` is the project number (not project ID).", // "location": "path", // "pattern": "^[^/]+/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/services", // "response": { // "$ref": "ListServicesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ServicesListCall) Pages(ctx context.Context, f func(*ListServicesResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "serviceusage.services.consumerQuotaMetrics.get": type ServicesConsumerQuotaMetricsGetCall struct { s *APIService name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Retrieves a summary of quota information for a specific quota // metric func (r *ServicesConsumerQuotaMetricsService) Get(name string) *ServicesConsumerQuotaMetricsGetCall { c := &ServicesConsumerQuotaMetricsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // View sets the optional parameter "view": Specifies the level of // detail for quota information in the response. // // Possible values: // "QUOTA_VIEW_UNSPECIFIED" - No quota view specified. Requests that // do not specify a quota view will typically default to the BASIC view. // "BASIC" - Only buckets with overrides are shown in the response. // "FULL" - Include per-location buckets even if they do not have // overrides. When the view is FULL, and a limit has regional or zonal // quota, the limit will include buckets for all regions or zones that // could support overrides, even if none are currently present. In some // cases this will cause the response to become very large; callers that // do not need this extra information should use the BASIC view instead. func (c *ServicesConsumerQuotaMetricsGetCall) View(view string) *ServicesConsumerQuotaMetricsGetCall { c.urlParams_.Set("view", view) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsGetCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesConsumerQuotaMetricsGetCall) IfNoneMatch(entityTag string) *ServicesConsumerQuotaMetricsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsGetCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.get" call. // Exactly one of *ConsumerQuotaMetric or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ConsumerQuotaMetric.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsGetCall) Do(opts ...googleapi.CallOption) (*ConsumerQuotaMetric, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ConsumerQuotaMetric{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Retrieves a summary of quota information for a specific quota metric", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}", // "httpMethod": "GET", // "id": "serviceusage.services.consumerQuotaMetrics.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "The resource name of the quota limit. An example name would be: projects/123/services/serviceusage.googleapis.com/quotas/metrics/serviceusage.googleapis.com%2Fmutate_requests", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+$", // "required": true, // "type": "string" // }, // "view": { // "description": "Specifies the level of detail for quota information in the response.", // "enum": [ // "QUOTA_VIEW_UNSPECIFIED", // "BASIC", // "FULL" // ], // "enumDescriptions": [ // "No quota view specified. Requests that do not specify a quota view will typically default to the BASIC view.", // "Only buckets with overrides are shown in the response.", // "Include per-location buckets even if they do not have overrides. When the view is FULL, and a limit has regional or zonal quota, the limit will include buckets for all regions or zones that could support overrides, even if none are currently present. In some cases this will cause the response to become very large; callers that do not need this extra information should use the BASIC view instead." // ], // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "ConsumerQuotaMetric" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.importConsumerOverrides": type ServicesConsumerQuotaMetricsImportConsumerOverridesCall struct { s *APIService parent string importconsumeroverridesrequest *ImportConsumerOverridesRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // ImportConsumerOverrides: Create or update multiple consumer overrides // atomically, all on the same consumer, but on many different metrics // or limits. The name field in the quota override message should not be // set. func (r *ServicesConsumerQuotaMetricsService) ImportConsumerOverrides(parent string, importconsumeroverridesrequest *ImportConsumerOverridesRequest) *ServicesConsumerQuotaMetricsImportConsumerOverridesCall { c := &ServicesConsumerQuotaMetricsImportConsumerOverridesCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent c.importconsumeroverridesrequest = importconsumeroverridesrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsImportConsumerOverridesCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsImportConsumerOverridesCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsImportConsumerOverridesCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsImportConsumerOverridesCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsImportConsumerOverridesCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsImportConsumerOverridesCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.importconsumeroverridesrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/consumerQuotaMetrics:importConsumerOverrides") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.importConsumerOverrides" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsImportConsumerOverridesCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Create or update multiple consumer overrides atomically, all on the same consumer, but on many different metrics or limits. The name field in the quota override message should not be set.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics:importConsumerOverrides", // "httpMethod": "POST", // "id": "serviceusage.services.consumerQuotaMetrics.importConsumerOverrides", // "parameterOrder": [ // "parent" // ], // "parameters": { // "parent": { // "description": "The resource name of the consumer. An example name would be: `projects/123/services/compute.googleapis.com`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/consumerQuotaMetrics:importConsumerOverrides", // "request": { // "$ref": "ImportConsumerOverridesRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.list": type ServicesConsumerQuotaMetricsListCall struct { s *APIService parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Retrieves a summary of all quota information visible to the // service consumer, organized by service metric. Each metric includes // information about all of its defined limits. Each limit includes the // limit configuration (quota unit, preciseness, default value), the // current effective limit value, and all of the overrides applied to // the limit. func (r *ServicesConsumerQuotaMetricsService) List(parent string) *ServicesConsumerQuotaMetricsListCall { c := &ServicesConsumerQuotaMetricsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // PageSize sets the optional parameter "pageSize": Requested size of // the next page of data. func (c *ServicesConsumerQuotaMetricsListCall) PageSize(pageSize int64) *ServicesConsumerQuotaMetricsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": Token identifying // which result to start with; returned by a previous list call. func (c *ServicesConsumerQuotaMetricsListCall) PageToken(pageToken string) *ServicesConsumerQuotaMetricsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // View sets the optional parameter "view": Specifies the level of // detail for quota information in the response. // // Possible values: // "QUOTA_VIEW_UNSPECIFIED" - No quota view specified. Requests that // do not specify a quota view will typically default to the BASIC view. // "BASIC" - Only buckets with overrides are shown in the response. // "FULL" - Include per-location buckets even if they do not have // overrides. When the view is FULL, and a limit has regional or zonal // quota, the limit will include buckets for all regions or zones that // could support overrides, even if none are currently present. In some // cases this will cause the response to become very large; callers that // do not need this extra information should use the BASIC view instead. func (c *ServicesConsumerQuotaMetricsListCall) View(view string) *ServicesConsumerQuotaMetricsListCall { c.urlParams_.Set("view", view) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsListCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesConsumerQuotaMetricsListCall) IfNoneMatch(entityTag string) *ServicesConsumerQuotaMetricsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsListCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/consumerQuotaMetrics") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.list" call. // Exactly one of *ListConsumerQuotaMetricsResponse or error will be // non-nil. Any non-2xx status code is an error. Response headers are in // either *ListConsumerQuotaMetricsResponse.ServerResponse.Header or (if // a response was returned at all) in error.(*googleapi.Error).Header. // Use googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsListCall) Do(opts ...googleapi.CallOption) (*ListConsumerQuotaMetricsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListConsumerQuotaMetricsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Retrieves a summary of all quota information visible to the service consumer, organized by service metric. Each metric includes information about all of its defined limits. Each limit includes the limit configuration (quota unit, preciseness, default value), the current effective limit value, and all of the overrides applied to the limit.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics", // "httpMethod": "GET", // "id": "serviceusage.services.consumerQuotaMetrics.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "pageSize": { // "description": "Requested size of the next page of data.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Token identifying which result to start with; returned by a previous list call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "Parent of the quotas resource. Some example names would be: projects/123/services/serviceconsumermanagement.googleapis.com folders/345/services/serviceconsumermanagement.googleapis.com organizations/456/services/serviceconsumermanagement.googleapis.com", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+$", // "required": true, // "type": "string" // }, // "view": { // "description": "Specifies the level of detail for quota information in the response.", // "enum": [ // "QUOTA_VIEW_UNSPECIFIED", // "BASIC", // "FULL" // ], // "enumDescriptions": [ // "No quota view specified. Requests that do not specify a quota view will typically default to the BASIC view.", // "Only buckets with overrides are shown in the response.", // "Include per-location buckets even if they do not have overrides. When the view is FULL, and a limit has regional or zonal quota, the limit will include buckets for all regions or zones that could support overrides, even if none are currently present. In some cases this will cause the response to become very large; callers that do not need this extra information should use the BASIC view instead." // ], // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/{+parent}/consumerQuotaMetrics", // "response": { // "$ref": "ListConsumerQuotaMetricsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ServicesConsumerQuotaMetricsListCall) Pages(ctx context.Context, f func(*ListConsumerQuotaMetricsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "serviceusage.services.consumerQuotaMetrics.limits.get": type ServicesConsumerQuotaMetricsLimitsGetCall struct { s *APIService name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Retrieves a summary of quota information for a specific quota // limit. func (r *ServicesConsumerQuotaMetricsLimitsService) Get(name string) *ServicesConsumerQuotaMetricsLimitsGetCall { c := &ServicesConsumerQuotaMetricsLimitsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // View sets the optional parameter "view": Specifies the level of // detail for quota information in the response. // // Possible values: // "QUOTA_VIEW_UNSPECIFIED" - No quota view specified. Requests that // do not specify a quota view will typically default to the BASIC view. // "BASIC" - Only buckets with overrides are shown in the response. // "FULL" - Include per-location buckets even if they do not have // overrides. When the view is FULL, and a limit has regional or zonal // quota, the limit will include buckets for all regions or zones that // could support overrides, even if none are currently present. In some // cases this will cause the response to become very large; callers that // do not need this extra information should use the BASIC view instead. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) View(view string) *ServicesConsumerQuotaMetricsLimitsGetCall { c.urlParams_.Set("view", view) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) IfNoneMatch(entityTag string) *ServicesConsumerQuotaMetricsLimitsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.get" call. // Exactly one of *ConsumerQuotaLimit or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ConsumerQuotaLimit.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsGetCall) Do(opts ...googleapi.CallOption) (*ConsumerQuotaLimit, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ConsumerQuotaLimit{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Retrieves a summary of quota information for a specific quota limit.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}", // "httpMethod": "GET", // "id": "serviceusage.services.consumerQuotaMetrics.limits.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "The resource name of the quota limit. Use the quota limit resource name returned by previous ListConsumerQuotaMetrics and GetConsumerQuotaMetric API calls.", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+$", // "required": true, // "type": "string" // }, // "view": { // "description": "Specifies the level of detail for quota information in the response.", // "enum": [ // "QUOTA_VIEW_UNSPECIFIED", // "BASIC", // "FULL" // ], // "enumDescriptions": [ // "No quota view specified. Requests that do not specify a quota view will typically default to the BASIC view.", // "Only buckets with overrides are shown in the response.", // "Include per-location buckets even if they do not have overrides. When the view is FULL, and a limit has regional or zonal quota, the limit will include buckets for all regions or zones that could support overrides, even if none are currently present. In some cases this will cause the response to become very large; callers that do not need this extra information should use the BASIC view instead." // ], // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "ConsumerQuotaLimit" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.create": type ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall struct { s *APIService parent string quotaoverride *QuotaOverride urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Create: Creates an admin override. An admin override is applied by an // administrator of a parent folder or parent organization of the // consumer receiving the override. An admin override is intended to // limit the amount of quota the consumer can use out of the total quota // pool allocated to all children of the folder or organization. func (r *ServicesConsumerQuotaMetricsLimitsAdminOverridesService) Create(parent string, quotaoverride *QuotaOverride) *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall { c := &ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent c.quotaoverride = quotaoverride return c } // Force sets the optional parameter "force": Whether to force the // creation of the quota override. If creating an override would cause // the effective quota for the consumer to decrease by more than 10 // percent, the call is rejected, as a safety measure to avoid // accidentally decreasing quota too quickly. Setting the force // parameter to true ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.quotaoverride) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/adminOverrides") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.create" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Creates an admin override. An admin override is applied by an administrator of a parent folder or parent organization of the consumer receiving the override. An admin override is intended to limit the amount of quota the consumer can use out of the total quota pool allocated to all children of the folder or organization.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/adminOverrides", // "httpMethod": "POST", // "id": "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.create", // "parameterOrder": [ // "parent" // ], // "parameters": { // "force": { // "description": "Whether to force the creation of the quota override. If creating an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "parent": { // "description": "The resource name of the parent quota limit, returned by a ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/adminOverrides", // "request": { // "$ref": "QuotaOverride" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.delete": type ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall struct { s *APIService name string urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Delete: Deletes an admin override. func (r *ServicesConsumerQuotaMetricsLimitsAdminOverridesService) Delete(name string) *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall { c := &ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Force sets the optional parameter "force": Whether to force the // deletion of the quota override. If deleting an override would cause // the effective quota for the consumer to decrease by more than 10 // percent, the call is rejected, as a safety measure to avoid // accidentally decreasing quota too quickly. Setting the force // parameter to true ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("DELETE", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.delete" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Deletes an admin override.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/adminOverrides/{adminOverridesId}", // "httpMethod": "DELETE", // "id": "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.delete", // "parameterOrder": [ // "name" // ], // "parameters": { // "force": { // "description": "Whether to force the deletion of the quota override. If deleting an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "name": { // "description": "The resource name of the override to delete. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4a3f2c1d`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+/adminOverrides/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.list": type ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall struct { s *APIService parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Lists all admin overrides on this limit. func (r *ServicesConsumerQuotaMetricsLimitsAdminOverridesService) List(parent string) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c := &ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // PageSize sets the optional parameter "pageSize": Requested size of // the next page of data. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) PageSize(pageSize int64) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": Token identifying // which result to start with; returned by a previous list call. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) PageToken(pageToken string) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) IfNoneMatch(entityTag string) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/adminOverrides") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.list" call. // Exactly one of *ListAdminOverridesResponse or error will be non-nil. // Any non-2xx status code is an error. Response headers are in either // *ListAdminOverridesResponse.ServerResponse.Header or (if a response // was returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) Do(opts ...googleapi.CallOption) (*ListAdminOverridesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListAdminOverridesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Lists all admin overrides on this limit.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/adminOverrides", // "httpMethod": "GET", // "id": "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "pageSize": { // "description": "Requested size of the next page of data.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Token identifying which result to start with; returned by a previous list call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "The resource name of the parent quota limit, returned by a ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/adminOverrides", // "response": { // "$ref": "ListAdminOverridesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesListCall) Pages(ctx context.Context, f func(*ListAdminOverridesResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.patch": type ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall struct { s *APIService name string quotaoverride *QuotaOverride urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Patch: Updates an admin override. func (r *ServicesConsumerQuotaMetricsLimitsAdminOverridesService) Patch(name string, quotaoverride *QuotaOverride) *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall { c := &ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.quotaoverride = quotaoverride return c } // Force sets the optional parameter "force": Whether to force the // update of the quota override. If updating an override would cause the // effective quota for the consumer to decrease by more than 10 percent, // the call is rejected, as a safety measure to avoid accidentally // decreasing quota too quickly. Setting the force parameter to true // ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // UpdateMask sets the optional parameter "updateMask": Update only the // specified fields of the override. If unset, all fields will be // updated. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) UpdateMask(updateMask string) *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall { c.urlParams_.Set("updateMask", updateMask) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.quotaoverride) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("PATCH", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.patch" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsAdminOverridesPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Updates an admin override.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/adminOverrides/{adminOverridesId}", // "httpMethod": "PATCH", // "id": "serviceusage.services.consumerQuotaMetrics.limits.adminOverrides.patch", // "parameterOrder": [ // "name" // ], // "parameters": { // "force": { // "description": "Whether to force the update of the quota override. If updating an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "name": { // "description": "The resource name of the override to update. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/adminOverrides/4a3f2c1d`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+/adminOverrides/[^/]+$", // "required": true, // "type": "string" // }, // "updateMask": { // "description": "Update only the specified fields of the override. If unset, all fields will be updated.", // "format": "google-fieldmask", // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "request": { // "$ref": "QuotaOverride" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.create": type ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall struct { s *APIService parent string quotaoverride *QuotaOverride urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Create: Creates a consumer override. A consumer override is applied // to the consumer on its own authority to limit its own quota usage. // Consumer overrides cannot be used to grant more quota than would be // allowed by admin overrides, producer overrides, or the default limit // of the service. func (r *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService) Create(parent string, quotaoverride *QuotaOverride) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall { c := &ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent c.quotaoverride = quotaoverride return c } // Force sets the optional parameter "force": Whether to force the // creation of the quota override. If creating an override would cause // the effective quota for the consumer to decrease by more than 10 // percent, the call is rejected, as a safety measure to avoid // accidentally decreasing quota too quickly. Setting the force // parameter to true ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.quotaoverride) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/consumerOverrides") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.create" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Creates a consumer override. A consumer override is applied to the consumer on its own authority to limit its own quota usage. Consumer overrides cannot be used to grant more quota than would be allowed by admin overrides, producer overrides, or the default limit of the service.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/consumerOverrides", // "httpMethod": "POST", // "id": "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.create", // "parameterOrder": [ // "parent" // ], // "parameters": { // "force": { // "description": "Whether to force the creation of the quota override. If creating an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "parent": { // "description": "The resource name of the parent quota limit, returned by a ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/consumerOverrides", // "request": { // "$ref": "QuotaOverride" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.delete": type ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall struct { s *APIService name string urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Delete: Deletes a consumer override. func (r *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService) Delete(name string) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall { c := &ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Force sets the optional parameter "force": Whether to force the // deletion of the quota override. If deleting an override would cause // the effective quota for the consumer to decrease by more than 10 // percent, the call is rejected, as a safety measure to avoid // accidentally decreasing quota too quickly. Setting the force // parameter to true ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("DELETE", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.delete" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a consumer override.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/consumerOverrides/{consumerOverridesId}", // "httpMethod": "DELETE", // "id": "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.delete", // "parameterOrder": [ // "name" // ], // "parameters": { // "force": { // "description": "Whether to force the deletion of the quota override. If deleting an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "name": { // "description": "The resource name of the override to delete. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverrides/4a3f2c1d`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+/consumerOverrides/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } } // method id "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.list": type ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall struct { s *APIService parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Lists all consumer overrides on this limit. func (r *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService) List(parent string) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c := &ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // PageSize sets the optional parameter "pageSize": Requested size of // the next page of data. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) PageSize(pageSize int64) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": Token identifying // which result to start with; returned by a previous list call. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) PageToken(pageToken string) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) IfNoneMatch(entityTag string) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/consumerOverrides") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.list" call. // Exactly one of *ListConsumerOverridesResponse or error will be // non-nil. Any non-2xx status code is an error. Response headers are in // either *ListConsumerOverridesResponse.ServerResponse.Header or (if a // response was returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) Do(opts ...googleapi.CallOption) (*ListConsumerOverridesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListConsumerOverridesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Lists all consumer overrides on this limit.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/consumerOverrides", // "httpMethod": "GET", // "id": "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "pageSize": { // "description": "Requested size of the next page of data.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Token identifying which result to start with; returned by a previous list call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "The resource name of the parent quota limit, returned by a ListConsumerQuotaMetrics or GetConsumerQuotaMetric call. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/consumerOverrides", // "response": { // "$ref": "ListConsumerOverridesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesListCall) Pages(ctx context.Context, f func(*ListConsumerOverridesResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.patch": type ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall struct { s *APIService name string quotaoverride *QuotaOverride urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // Patch: Updates a consumer override. func (r *ServicesConsumerQuotaMetricsLimitsConsumerOverridesService) Patch(name string, quotaoverride *QuotaOverride) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall { c := &ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.quotaoverride = quotaoverride return c } // Force sets the optional parameter "force": Whether to force the // update of the quota override. If updating an override would cause the // effective quota for the consumer to decrease by more than 10 percent, // the call is rejected, as a safety measure to avoid accidentally // decreasing quota too quickly. Setting the force parameter to true // ignores this restriction. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) Force(force bool) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall { c.urlParams_.Set("force", fmt.Sprint(force)) return c } // UpdateMask sets the optional parameter "updateMask": Update only the // specified fields of the override. If unset, all fields will be // updated. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) UpdateMask(updateMask string) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall { c.urlParams_.Set("updateMask", updateMask) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) Fields(s ...googleapi.Field) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) Context(ctx context.Context) *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.quotaoverride) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("PATCH", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.patch" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ServicesConsumerQuotaMetricsLimitsConsumerOverridesPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Updates a consumer override.", // "flatPath": "v1beta1/{v1beta1Id}/{v1beta1Id1}/services/{servicesId}/consumerQuotaMetrics/{consumerQuotaMetricsId}/limits/{limitsId}/consumerOverrides/{consumerOverridesId}", // "httpMethod": "PATCH", // "id": "serviceusage.services.consumerQuotaMetrics.limits.consumerOverrides.patch", // "parameterOrder": [ // "name" // ], // "parameters": { // "force": { // "description": "Whether to force the update of the quota override. If updating an override would cause the effective quota for the consumer to decrease by more than 10 percent, the call is rejected, as a safety measure to avoid accidentally decreasing quota too quickly. Setting the force parameter to true ignores this restriction.", // "location": "query", // "type": "boolean" // }, // "name": { // "description": "The resource name of the override to update. An example name would be: `projects/123/services/compute.googleapis.com/consumerQuotaMetrics/compute.googleapis.com%2Fcpus/limits/%2Fproject%2Fregion/consumerOverrides/4a3f2c1d`", // "location": "path", // "pattern": "^[^/]+/[^/]+/services/[^/]+/consumerQuotaMetrics/[^/]+/limits/[^/]+/consumerOverrides/[^/]+$", // "required": true, // "type": "string" // }, // "updateMask": { // "description": "Update only the specified fields of the override. If unset, all fields will be updated.", // "format": "google-fieldmask", // "location": "query", // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "request": { // "$ref": "QuotaOverride" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/service.management" // ] // } }
{ rs := &OperationsService{s: s} return rs }
db_test.go
package integration import ( "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stellar/go/historyarchive" horizoncmd "github.com/stellar/go/services/horizon/cmd" "github.com/stellar/go/services/horizon/internal/db2/schema" "github.com/stellar/go/services/horizon/internal/test/integration" "github.com/stellar/go/support/db" "github.com/stellar/go/support/db/dbtest" "github.com/stellar/go/txnbuild" ) func initializeDBIntegrationTest(t *testing.T) (itest *integration.Test, reachedLedger int32) { itest = integration.NewTest(t, protocol15Config) master := itest.Master() tt := assert.New(t) // Initialize the database with some ledgers including some transactions we submit op := txnbuild.Payment{ Destination: master.Address(), Amount: "10", Asset: txnbuild.NativeAsset{}, } // TODO: should we enforce certain number of ledgers to be ingested? for i := 0; i < 8; i++ { txResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &op) reachedLedger = txResp.Ledger } root, err := itest.Client().Root() tt.NoError(err) tt.LessOrEqual(reachedLedger, root.HorizonSequence) return } func TestReingestDB(t *testing.T) { itest, reachedLedger := initializeDBIntegrationTest(t) tt := assert.New(t) // Create a fresh Horizon database newDB := dbtest.Postgres(t) // TODO: Unfortunately Horizon's ingestion System leaves open sessions behind,leading to // a "database is being accessed by other users" error when trying to drop it // defer newDB.Close() freshHorizonPostgresURL := newDB.DSN horizonConfig := itest.GetHorizonConfig() horizonConfig.DatabaseURL = freshHorizonPostgresURL // Initialize the DB schema dbConn, err := db.Open("postgres", freshHorizonPostgresURL) defer dbConn.Close() _, err = schema.Migrate(dbConn.DB.DB, schema.MigrateUp, 0) tt.NoError(err) // cap reachedLedger to the nearest checkpoint ledger because reingest range cannot ingest past the most // recent checkpoint ledger when using captive core toLedger := uint32(reachedLedger) archive, err := historyarchive.Connect(horizonConfig.HistoryArchiveURLs[0], historyarchive.ConnectOptions{ NetworkPassphrase: horizonConfig.NetworkPassphrase, CheckpointFrequency: horizonConfig.CheckpointFrequency, }) tt.NoError(err) // make sure a full checkpoint has elapsed otherwise there will be nothing to reingest var latestCheckpoint uint32 publishedFirstCheckpoint := func() bool { has, requestErr := archive.GetRootHAS() tt.NoError(requestErr) latestCheckpoint = has.CurrentLedger return latestCheckpoint > 1 } tt.Eventually(publishedFirstCheckpoint, 10*time.Second, time.Second) if toLedger > latestCheckpoint { toLedger = latestCheckpoint } horizonConfig.CaptiveCoreConfigAppendPath = filepath.Join( filepath.Dir(horizonConfig.CaptiveCoreConfigAppendPath), "captive-core-reingest-range-integration-tests.cfg", ) // Reingest into the DB err = horizoncmd.RunDBReingestRange(1, toLedger, false, 1, horizonConfig) tt.NoError(err) } func TestResumeFromInitializedDB(t *testing.T) { itest, reachedLedger := initializeDBIntegrationTest(t) tt := assert.New(t)
oldDBURL := itest.GetHorizonConfig().DatabaseURL itestConfig := protocol15Config itestConfig.PostgresURL = oldDBURL itest.RestartHorizon() successfullyResumed := func() bool { root, err := itest.Client().Root() tt.NoError(err) // It must be able to reach the ledger and surpass it const ledgersPastStopPoint = 4 return root.HorizonSequence > (reachedLedger + ledgersPastStopPoint) } tt.Eventually(successfullyResumed, 1*time.Minute, 1*time.Second) }
// Stop the integration test, and restart it with the same database
simple_id_tracker.rs
use crate::common::rocksdb_operations::{db_write_options, open_db_with_cf}; use crate::entry::entry_point::OperationResult; use crate::id_tracker::points_iterator::PointsIterator; use crate::id_tracker::IdTracker; use crate::types::{ExtendedPointId, PointIdType, PointOffsetType, SeqNumberType}; use bincode; use rocksdb::{IteratorMode, DB}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::path::Path; use uuid::Uuid; /// Point Id type used for storing ids internally /// Should be serializable by `bincode`, therefore is not untagged. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] enum StoredPointId { NumId(u64), Uuid(Uuid), String(String), } impl From<&ExtendedPointId> for StoredPointId { fn from(point_id: &ExtendedPointId) -> Self { match point_id { ExtendedPointId::NumId(idx) => StoredPointId::NumId(*idx), ExtendedPointId::Uuid(uuid) => StoredPointId::Uuid(*uuid), } } } impl From<StoredPointId> for ExtendedPointId { fn from(point_id: StoredPointId) -> Self { match point_id { StoredPointId::NumId(idx) => ExtendedPointId::NumId(idx), StoredPointId::Uuid(uuid) => ExtendedPointId::Uuid(uuid), StoredPointId::String(_str) => unimplemented!(), } } } #[inline] fn stored_to_external_id(point_id: StoredPointId) -> PointIdType { point_id.into() } #[inline] fn external_to_stored_id(point_id: &PointIdType) -> StoredPointId { point_id.into() } const MAPPING_CF: &str = "mapping"; const VERSIONS_CF: &str = "versions"; pub struct SimpleIdTracker { internal_to_external: HashMap<PointOffsetType, PointIdType>, external_to_internal: BTreeMap<PointIdType, PointOffsetType>, external_to_version: HashMap<PointIdType, SeqNumberType>, max_internal_id: PointOffsetType, store: DB, } impl SimpleIdTracker { pub fn open(path: &Path) -> OperationResult<Self> { let store = open_db_with_cf(path, &[MAPPING_CF, VERSIONS_CF])?; let mut internal_to_external: HashMap<PointOffsetType, PointIdType> = Default::default(); let mut external_to_internal: BTreeMap<PointIdType, PointOffsetType> = Default::default(); let mut external_to_version: HashMap<PointIdType, SeqNumberType> = Default::default(); let mut max_internal_id = 0; for (key, val) in store.iterator_cf(store.cf_handle(MAPPING_CF).unwrap(), IteratorMode::Start) { let external_id = Self::restore_key(&key); let internal_id: PointOffsetType = bincode::deserialize(&val).unwrap(); internal_to_external.insert(internal_id, external_id); external_to_internal.insert(external_id, internal_id); max_internal_id = max_internal_id.max(internal_id); } for (key, val) in store.iterator_cf(store.cf_handle(VERSIONS_CF).unwrap(), IteratorMode::Start) { let external_id = Self::restore_key(&key); let version: SeqNumberType = bincode::deserialize(&val).unwrap(); external_to_version.insert(external_id, version); } Ok(SimpleIdTracker { internal_to_external, external_to_internal, external_to_version, max_internal_id, store, }) } fn store_key(external_id: &PointIdType) -> Vec<u8> { bincode::serialize(&external_to_stored_id(external_id)).unwrap() } fn restore_key(data: &[u8]) -> PointIdType { let stored_external_id: StoredPointId = bincode::deserialize(data).unwrap(); stored_to_external_id(stored_external_id) } } impl IdTracker for SimpleIdTracker { fn version(&self, external_id: PointIdType) -> Option<SeqNumberType> { self.external_to_version.get(&external_id).copied() } fn set_version( &mut self, external_id: PointIdType, version: SeqNumberType, ) -> OperationResult<()> { self.external_to_version.insert(external_id, version); self.store.put_cf_opt( self.store.cf_handle(VERSIONS_CF).unwrap(), Self::store_key(&external_id), bincode::serialize(&version).unwrap(), &db_write_options(), )?; Ok(()) } fn internal_id(&self, external_id: PointIdType) -> Option<PointOffsetType> { self.external_to_internal.get(&external_id).copied() } fn external_id(&self, internal_id: PointOffsetType) -> Option<PointIdType> { self.internal_to_external.get(&internal_id).copied() } fn set_link( &mut self, external_id: PointIdType, internal_id: PointOffsetType, ) -> OperationResult<()> { self.external_to_internal.insert(external_id, internal_id); self.internal_to_external.insert(internal_id, external_id); self.max_internal_id = self.max_internal_id.max(internal_id); self.store.put_cf_opt( self.store.cf_handle(MAPPING_CF).unwrap(), Self::store_key(&external_id), bincode::serialize(&internal_id).unwrap(), &db_write_options(), )?; Ok(()) } fn drop(&mut self, external_id: PointIdType) -> OperationResult<()> { self.external_to_version.remove(&external_id); let internal_id = self.external_to_internal.remove(&external_id); match internal_id { Some(x) => self.internal_to_external.remove(&x), None => None, }; self.store.delete_cf( self.store.cf_handle(MAPPING_CF).unwrap(), Self::store_key(&external_id), )?; self.store.delete_cf( self.store.cf_handle(VERSIONS_CF).unwrap(), Self::store_key(&external_id), )?; Ok(()) } fn iter_external(&self) -> Box<dyn Iterator<Item = PointIdType> + '_> { Box::new(self.external_to_internal.keys().copied()) } fn iter_internal(&self) -> Box<dyn Iterator<Item = PointOffsetType> + '_> { Box::new(self.internal_to_external.keys().copied()) } fn iter_from( &self, external_id: Option<PointIdType>, ) -> Box<dyn Iterator<Item = (PointIdType, PointOffsetType)> + '_> { let range = match external_id { None => self.external_to_internal.range(..), Some(offset) => self.external_to_internal.range(offset..), }; Box::new(range.map(|(key, value)| (*key, *value))) } fn flush(&self) -> OperationResult<()> { self.store .flush_cf(self.store.cf_handle(MAPPING_CF).unwrap())?; self.store .flush_cf(self.store.cf_handle(VERSIONS_CF).unwrap())?; Ok(self.store.flush()?) } } impl PointsIterator for SimpleIdTracker { fn points_count(&self) -> usize
fn iter_ids(&self) -> Box<dyn Iterator<Item = PointOffsetType> + '_> { self.iter_internal() } fn max_id(&self) -> PointOffsetType { self.max_internal_id } } #[cfg(test)] mod tests { use super::*; use itertools::Itertools; use serde::de::DeserializeOwned; use tempdir::TempDir; fn check_bincode_serialization< T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug, >( record: T, ) { let binary_entity = bincode::serialize(&record).expect("serialization ok"); let de_record: T = bincode::deserialize(&binary_entity).expect("deserialization ok"); assert_eq!(record, de_record); } #[test] fn test_serializaton() { check_bincode_serialization(StoredPointId::NumId(123)); check_bincode_serialization(StoredPointId::Uuid(Uuid::from_u128(123_u128))); check_bincode_serialization(StoredPointId::String("hello".to_string())); } #[test] fn test_iterator() { let dir = TempDir::new("storage_dir").unwrap(); let mut id_tracker = SimpleIdTracker::open(dir.path()).unwrap(); id_tracker.set_link(200.into(), 0).unwrap(); id_tracker.set_link(100.into(), 1).unwrap(); id_tracker.set_link(150.into(), 2).unwrap(); id_tracker.set_link(120.into(), 3).unwrap(); id_tracker.set_link(180.into(), 4).unwrap(); id_tracker.set_link(110.into(), 5).unwrap(); id_tracker.set_link(115.into(), 6).unwrap(); id_tracker.set_link(190.into(), 7).unwrap(); id_tracker.set_link(177.into(), 8).unwrap(); id_tracker.set_link(118.into(), 9).unwrap(); let first_four = id_tracker.iter_from(None).take(4).collect_vec(); assert_eq!(first_four.len(), 4); assert_eq!(first_four[0].0, 100.into()); let last = id_tracker.iter_from(Some(first_four[3].0)).collect_vec(); assert_eq!(last.len(), 7); } }
{ self.internal_to_external.len() }
org_users.go
package api import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" ) // POST /api/org/users func AddOrgUserToCurrentOrg(c *m.ReqContext, cmd m.AddOrgUserCommand) Response { cmd.OrgId = c.OrgId return addOrgUserHelper(cmd) } // POST /api/orgs/:orgId/users func AddOrgUser(c *m.ReqContext, cmd m.AddOrgUserCommand) Response { cmd.OrgId = c.ParamsInt64(":orgId") return addOrgUserHelper(cmd) } func addOrgUserHelper(cmd m.AddOrgUserCommand) Response { if !cmd.Role.IsValid() { return Error(400, "Invalid role specified", nil) } userQuery := m.GetUserByLoginQuery{LoginOrEmail: cmd.LoginOrEmail} err := bus.Dispatch(&userQuery) if err != nil { return Error(404, "User not found", nil) } userToAdd := userQuery.Result cmd.UserId = userToAdd.Id if err := bus.Dispatch(&cmd); err != nil { if err == m.ErrOrgUserAlreadyAdded { return Error(409, "User is already member of this organization", nil) } return Error(500, "Could not add user to organization", err) } return Success("User added to organization") } // GET /api/org/users func GetOrgUsersForCurrentOrg(c *m.ReqContext) Response { return getOrgUsersHelper(c.OrgId, c.Query("query"), c.QueryInt("limit")) } // GET /api/orgs/:orgId/users func GetOrgUsers(c *m.ReqContext) Response { return getOrgUsersHelper(c.ParamsInt64(":orgId"), "", 0) } func getOrgUsersHelper(orgID int64, query string, limit int) Response { q := m.GetOrgUsersQuery{ OrgId: orgID, Query: query, Limit: limit, } if err := bus.Dispatch(&q); err != nil { return Error(500, "Failed to get account user", err) } for _, user := range q.Result { user.AvatarUrl = dtos.GetGravatarUrl(user.Email) } return JSON(200, q.Result) } // PATCH /api/org/users/:userId func UpdateOrgUserForCurrentOrg(c *m.ReqContext, cmd m.UpdateOrgUserCommand) Response { cmd.OrgId = c.OrgId cmd.UserId = c.ParamsInt64(":userId") return updateOrgUserHelper(cmd) } // PATCH /api/orgs/:orgId/users/:userId func UpdateOrgUser(c *m.ReqContext, cmd m.UpdateOrgUserCommand) Response
func updateOrgUserHelper(cmd m.UpdateOrgUserCommand) Response { if !cmd.Role.IsValid() { return Error(400, "Invalid role specified", nil) } if err := bus.Dispatch(&cmd); err != nil { if err == m.ErrLastOrgAdmin { return Error(400, "Cannot change role so that there is no organization admin left", nil) } return Error(500, "Failed update org user", err) } return Success("Organization user updated") } // DELETE /api/org/users/:userId func RemoveOrgUserForCurrentOrg(c *m.ReqContext) Response { return removeOrgUserHelper(&m.RemoveOrgUserCommand{ UserId: c.ParamsInt64(":userId"), OrgId: c.OrgId, ShouldDeleteOrphanedUser: true, }) } // DELETE /api/orgs/:orgId/users/:userId func RemoveOrgUser(c *m.ReqContext) Response { return removeOrgUserHelper(&m.RemoveOrgUserCommand{ UserId: c.ParamsInt64(":userId"), OrgId: c.ParamsInt64(":orgId"), }) } func removeOrgUserHelper(cmd *m.RemoveOrgUserCommand) Response { if err := bus.Dispatch(cmd); err != nil { if err == m.ErrLastOrgAdmin { return Error(400, "Cannot remove last organization admin", nil) } return Error(500, "Failed to remove user from organization", err) } if cmd.UserWasDeleted { return Success("User deleted") } return Success("User removed from organization") }
{ cmd.OrgId = c.ParamsInt64(":orgId") cmd.UserId = c.ParamsInt64(":userId") return updateOrgUserHelper(cmd) }
generics.ts
export const printObject = (argument:any) => console.log(argument); export function genericFunction<T>(argument:T):T { return argument;
} export const GenericFunctionArrow = <T>(argument:T) => argument;
file-parser.kubernetes.fixtures.ts
import { EngineType, IacFileData, IacFileParsed, } from '../../../../src/cli/commands/test/iac/local-execution/types'; import { IacProjectType } from '../../../../src/lib/iac/constants'; const kubernetesYamlFileContent = ` apiVersion: v1 kind: Pod metadata: name: myapp-pod spec: containers: - name: whatever securityContext: privileged: true `; const kubernetesJson = { apiVersion: 'v1', kind: 'Pod', metadata: { name: 'myapp-pod', }, spec: { containers: [ { name: 'whatever', securityContext: { privileged: true,
}, }; const kubernetesJsonFileContent = JSON.stringify(kubernetesJson); const multipleKubernetesYamlsFileContent = ` apiVersion: v1 kind: Pod metadata: name: myapp-pod spec: containers: - name: whatever securityContext: privileged: true --- # Empty doc --- apiVersion: v1 kind: Pod metadata: name: myapp-pod spec: containers: - name: whatever securityContext: privileged: true --- # An ignored, unrecognised config type foo: bar `; const kubernetesYamlInvalidFileContent = ` apiVersionXYZ: v1 kind: Pod metadata: name: myapp-pod spec: containers: - name: whatever securityContext: privileged: true `; const invalidJsonFile = '{ "foo": "bar"'; const invalidYamlFile = ` foo: "bar `; const unrecognisedYamlFile = ` foo: bar `; const semanticYamlWithDuplicateKeyFile = ` apiVersion: v1 kind: Pod metadata: name: myapp-pod spec: containers: something: here metadata: another: thing `; const semanticYamlErrorFileJSON = { apiVersion: 'v1', kind: 'Pod', metadata: { another: 'thing', //in a case of a duplicate key, the last one will be the one used when parsed }, spec: { containers: null, something: 'here', }, }; const yamlWithInsufficientIndentationFile = ` Resources: Denied: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "AWS": "arn:aws:iam::123456789012:root" }, "Effect": "Allow", "Sid": "" } ] } `; const yamlWithInsufficientIndentationFileJSON = { Resources: { Denied: { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Version: '2012-10-17', Statement: [ { Action: 'sts:AssumeRole', Principal: { AWS: 'arn:aws:iam::123456789012:root', }, Effect: 'Allow', Sid: '', }, ], }, }, }, }, }; export const kubernetesYamlFileDataStub: IacFileData = { fileContent: kubernetesYamlFileContent, filePath: 'dont-care', fileType: 'yml', }; export const kubernetesJsonFileDataStub: IacFileData = { fileContent: kubernetesJsonFileContent, filePath: 'dont-care', fileType: 'json', }; export const multipleKubernetesYamlsFileDataStub: IacFileData = { fileContent: multipleKubernetesYamlsFileContent, filePath: 'dont-care', fileType: 'yml', }; export const kubernetesYamlInvalidFileDataStub: IacFileData = { fileContent: kubernetesYamlInvalidFileContent, filePath: 'dont-care', fileType: 'yml', }; export const invalidJsonFileDataStub: IacFileData = { fileContent: invalidJsonFile, filePath: 'path/to/file', fileType: 'json', }; export const invalidYamlFileDataStub: IacFileData = { fileContent: invalidYamlFile, filePath: 'dont-care', fileType: 'yml', }; export const unrecognisedYamlDataStub: IacFileData = { fileContent: unrecognisedYamlFile, filePath: 'file.yml', fileType: 'yml', }; export const duplicateKeyYamlErrorFileDataStub: IacFileData = { fileContent: semanticYamlWithDuplicateKeyFile, filePath: 'dont-care', fileType: 'yml', }; export const expectedDuplicateKeyYamlErrorFileParsingResult: IacFileParsed = { ...duplicateKeyYamlErrorFileDataStub, docId: 0, projectType: IacProjectType.K8S, engineType: EngineType.Kubernetes, jsonContent: semanticYamlErrorFileJSON, }; export const insufficientIndentationYamlErrorFileDataStub: IacFileData = { fileContent: yamlWithInsufficientIndentationFile, filePath: 'dont-care', fileType: 'yml', }; export const expectedInsufficientIndentationYamlErrorFileParsingResult: IacFileParsed = { ...insufficientIndentationYamlErrorFileDataStub, docId: 0, projectType: IacProjectType.CLOUDFORMATION, engineType: EngineType.CloudFormation, jsonContent: yamlWithInsufficientIndentationFileJSON, }; export const expectedKubernetesYamlParsingResult: IacFileParsed = { ...kubernetesYamlFileDataStub, docId: 0, projectType: IacProjectType.K8S, engineType: EngineType.Kubernetes, jsonContent: kubernetesJson, }; export const expectedKubernetesJsonParsingResult: IacFileParsed = { ...kubernetesJsonFileDataStub, docId: undefined, projectType: IacProjectType.K8S, engineType: EngineType.Kubernetes, jsonContent: kubernetesJson, }; export const expectedMultipleKubernetesYamlsParsingResult: IacFileParsed = { ...multipleKubernetesYamlsFileDataStub, docId: 0, projectType: IacProjectType.K8S, engineType: EngineType.Kubernetes, jsonContent: kubernetesJson, };
}, }, ],
get_public_get_index_responses.go
// Code generated by go-swagger; DO NOT EDIT. package operations // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" models "github.com/tuanito/go-deribit/models" ) // GetPublicGetIndexReader is a Reader for the GetPublicGetIndex structure. type GetPublicGetIndexReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetPublicGetIndexReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetPublicGetIndexOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewGetPublicGetIndexOK creates a GetPublicGetIndexOK with default headers values func NewGetPublicGetIndexOK() *GetPublicGetIndexOK
/*GetPublicGetIndexOK handles this case with default header values. foo */ type GetPublicGetIndexOK struct { Payload *models.PublicIndexResponse } func (o *GetPublicGetIndexOK) Error() string { return fmt.Sprintf("[GET /public/get_index][%d] getPublicGetIndexOK %+v", 200, o.Payload) } func (o *GetPublicGetIndexOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.PublicIndexResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
{ return &GetPublicGetIndexOK{} }
configmap.go
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config // import "go.opentelemetry.io/collector/config" import ( "fmt" "io" "io/ioutil" "reflect" "github.com/knadh/koanf" "github.com/knadh/koanf/maps" "github.com/knadh/koanf/parsers/yaml" "github.com/knadh/koanf/providers/confmap" "github.com/knadh/koanf/providers/file" "github.com/knadh/koanf/providers/rawbytes" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" ) const ( // KeyDelimiter is used as the default key delimiter in the default koanf instance. KeyDelimiter = "::" ) // NewMap creates a new empty config.Map instance. func NewMap() *Map { return &Map{k: koanf.New(KeyDelimiter)} } // NewMapFromFile creates a new config.Map by reading the given file. func NewMapFromFile(fileName string) (*Map, error) { // Read yaml config from file. p := NewMap() if err := p.k.Load(file.Provider(fileName), yaml.Parser()); err != nil { return nil, fmt.Errorf("unable to read the file %v: %w", fileName, err) } return p, nil } // NewMapFromBuffer creates a new config.Map by reading the given yaml buffer. func NewMapFromBuffer(buf io.Reader) (*Map, error) { content, err := ioutil.ReadAll(buf) if err != nil { return nil, err } p := NewMap() if err := p.k.Load(rawbytes.Provider(content), yaml.Parser()); err != nil { return nil, err } return p, nil } // NewMapFromStringMap creates a config.Map from a map[string]interface{}. func NewMapFromStringMap(data map[string]interface{}) *Map { p := NewMap() // Cannot return error because the koanf instance is empty. _ = p.k.Load(confmap.Provider(data, KeyDelimiter), nil) return p } // Map represents the raw configuration map for the OpenTelemetry Collector. // The config.Map can be unmarshalled into the Collector's config using the "configunmarshaler" package. type Map struct { k *koanf.Koanf } // AllKeys returns all keys holding a value, regardless of where they are set. // Nested keys are returned with a KeyDelimiter separator. func (l *Map) AllKeys() []string { return l.k.Keys() } // Unmarshal unmarshalls the config into a struct. // Tags on the fields of the structure must be properly set. func (l *Map) Unmarshal(rawVal interface{}) error { decoder, err := mapstructure.NewDecoder(decoderConfig(rawVal)) if err != nil
return decoder.Decode(l.ToStringMap()) } // UnmarshalExact unmarshalls the config into a struct, erroring if a field is nonexistent. func (l *Map) UnmarshalExact(rawVal interface{}) error { dc := decoderConfig(rawVal) dc.ErrorUnused = true decoder, err := mapstructure.NewDecoder(dc) if err != nil { return err } return decoder.Decode(l.ToStringMap()) } // Get can retrieve any value given the key to use. func (l *Map) Get(key string) interface{} { return l.k.Get(key) } // Set sets the value for the key. func (l *Map) Set(key string, value interface{}) { // koanf doesn't offer a direct setting mechanism so merging is required. merged := koanf.New(KeyDelimiter) _ = merged.Load(confmap.Provider(map[string]interface{}{key: value}, KeyDelimiter), nil) // TODO (issue 4467): return this error on `Set`. _ = l.k.Merge(merged) } // IsSet checks to see if the key has been set in any of the data locations. // IsSet is case-insensitive for a key. func (l *Map) IsSet(key string) bool { return l.k.Exists(key) } // Merge merges the input given configuration into the existing config. // Note that the given map may be modified. func (l *Map) Merge(in *Map) error { return l.k.Merge(in.k) } // Sub returns new Parser instance representing a sub-config of this instance. // It returns an error is the sub-config is not a map (use Get()) and an empty Parser if // none exists. func (l *Map) Sub(key string) (*Map, error) { data := l.Get(key) if data == nil { return NewMap(), nil } if reflect.TypeOf(data).Kind() == reflect.Map { return NewMapFromStringMap(cast.ToStringMap(data)), nil } return nil, fmt.Errorf("unexpected sub-config value kind for key:%s value:%v kind:%v)", key, data, reflect.TypeOf(data).Kind()) } // ToStringMap creates a map[string]interface{} from a Parser. func (l *Map) ToStringMap() map[string]interface{} { return maps.Unflatten(l.k.All(), KeyDelimiter) } // decoderConfig returns a default mapstructure.DecoderConfig capable of parsing time.Duration // and weakly converting config field values to primitive types. It also ensures that maps // whose values are nil pointer structs resolved to the zero value of the target struct (see // expandNilStructPointers). A decoder created from this mapstructure.DecoderConfig will decode // its contents to the result argument. func decoderConfig(result interface{}) *mapstructure.DecoderConfig { return &mapstructure.DecoderConfig{ Result: result, Metadata: nil, TagName: "mapstructure", WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( expandNilStructPointersFunc, stringToSliceHookFunc, mapStringToMapComponentIDHookFunc, stringToTimeDurationHookFunc, textUnmarshallerHookFunc, ), } } var ( stringToSliceHookFunc = mapstructure.StringToSliceHookFunc(",") stringToTimeDurationHookFunc = mapstructure.StringToTimeDurationHookFunc() textUnmarshallerHookFunc = mapstructure.TextUnmarshallerHookFunc() componentIDType = reflect.TypeOf(NewComponentID("foo")) ) // In cases where a config has a mapping of something to a struct pointers // we want nil values to resolve to a pointer to the zero value of the // underlying struct just as we want nil values of a mapping of something // to a struct to resolve to the zero value of that struct. // // e.g. given a config type: // type Config struct { Thing *SomeStruct `mapstructure:"thing"` } // // and yaml of: // config: // thing: // // we want an unmarshaled Config to be equivalent to // Config{Thing: &SomeStruct{}} instead of Config{Thing: nil} var expandNilStructPointersFunc = func(from reflect.Value, to reflect.Value) (interface{}, error) { // ensure we are dealing with map to map comparison if from.Kind() == reflect.Map && to.Kind() == reflect.Map { toElem := to.Type().Elem() // ensure that map values are pointers to a struct // (that may be nil and require manual setting w/ zero value) if toElem.Kind() == reflect.Ptr && toElem.Elem().Kind() == reflect.Struct { fromRange := from.MapRange() for fromRange.Next() { fromKey := fromRange.Key() fromValue := fromRange.Value() // ensure that we've run into a nil pointer instance if fromValue.IsNil() { newFromValue := reflect.New(toElem.Elem()) from.SetMapIndex(fromKey, newFromValue) } } } } return from.Interface(), nil } // mapStringToMapComponentIDHookFunc returns a DecodeHookFunc that converts a map[string]interface{} to // map[ComponentID]interface{}. // This is needed in combination since the ComponentID.UnmarshalText may produce equal IDs for different strings, // and an error needs to be returned in that case, otherwise the last equivalent ID overwrites the previous one. var mapStringToMapComponentIDHookFunc = func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.Map || f.Key().Kind() != reflect.String { return data, nil } if t.Kind() != reflect.Map || t.Key() != componentIDType { return data, nil } m := make(map[ComponentID]interface{}) for k, v := range data.(map[string]interface{}) { id, err := NewComponentIDFromString(k) if err != nil { return nil, err } if _, ok := m[id]; ok { return nil, fmt.Errorf("duplicate name %q after trimming spaces %v", k, id) } m[id] = v } return m, nil }
{ return err }
FindArgumentStatistics.js
// COPYRIGHT © 2021 Esri
// // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: [email protected] // // See http://js.arcgis.com/3.36/esri/copyright.txt for details. define({toolDefine:"查找参数统计信息",outputLayerName:"${layername}_argumentStatistics",dimensionLabel:"选择将根据其提取统计数据的维度。",variablesLabel:"选择要分析的变量",variablesListLabel:"变量 [维度信息](描述)",statisticsTypeLabel:"选择统计数据类型",multipleOccurrenceValueLabel:"指定多个出现值(可选)",minValueLabel:"指定最小值",maxValueLabel:"指定最大值",argumentMinLabel:"最小值参数",argumentMaxLabel:"最大值参数",argumentMedianLabel:"中值参数",durationLabel:"持续时间",dimensionDefinitionLabel:"选择维度定义",intervalKeywordLabel:"选择间隔关键字",all:"全部",intervalKeyword:"间隔关键字",hourly:"每小时",daily:"每天",weekly:"每周",monthly:"每月",quarterly:"季度",yearly:"每年",recurringDaily:"每天循环",recurringWeekly:"每周循环",recurringMonthly:"每月循环",recurringQuarterly:"每季度循环",ignoreNodataLabel:"忽略计算中的缺失值",ignore:"忽略",analysisLayerLabel:"选择要分析的多维或多波段影像图层",itemDescription:"通过查找参数统计信息生成的分析影像服务",itemTags:"栅格分析结果,查找参数统计信息,${layername}",itemSnippet:"通过查找参数统计信息生成的分析影像服务"});
// // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions.
variables_0.js
[ ['block_190',['block',['../classsrc_1_1python__code_1_1_code_block_1_1_code_block.html#aa8192a9843145248474724f29fadffef',1,'src::python_code::CodeBlock::CodeBlock']]] ];
var searchData=
json-editor.min.js
/*! JSON Editor v0.7.23 - JSON Schema -> HTML Editor * By Jeremy Dorn - https://github.com/jdorn/json-editor/ * Released under the MIT license *
a.refreshValue(),a.onChange(!0)}),a.controls.appendChild(this.add_row_button),this.delete_last_row_button=this.getButton("Último "+this.getItemTitle(),"delete","Excluir Último "+this.getItemTitle()),this.delete_last_row_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation();var c=a.getValue(),d=null;a.rows.length>1&&a.rows[a.rows.length-1].tab===a.active_tab&&(d=a.rows[a.rows.length-2].tab),c.pop(),a.setValue(c),d&&(a.active_tab=d,a.refreshTabs()),a.onChange(!0)}),a.controls.appendChild(this.delete_last_row_button),this.remove_all_rows_button=this.getButton("Todos","delete","Excluir Todos"),this.remove_all_rows_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.setValue([]),a.onChange(!0)}),a.controls.appendChild(this.remove_all_rows_button),a.tabs&&(this.add_row_button.style.width="100%",this.add_row_button.style.textAlign="left",this.add_row_button.style.marginBottom="3px",this.delete_last_row_button.style.width="100%",this.delete_last_row_button.style.textAlign="left",this.delete_last_row_button.style.marginBottom="3px",this.remove_all_rows_button.style.width="100%",this.remove_all_rows_button.style.textAlign="left",this.remove_all_rows_button.style.marginBottom="3px")},showValidationErrors:function(a){var b=this,c=[],e=[];if(d(a,function(a,d){d.path===b.path?c.push(d):e.push(d)}),this.error_holder)if(c.length){this.error_holder.innerHTML="",this.error_holder.style.display="",d(c,function(a,c){b.error_holder.appendChild(b.theme.getErrorMessage(c.message))})}else this.error_holder.style.display="none";d(this.rows,function(a,b){b.showValidationErrors(e)})}}),f.defaults.editors.table=f.defaults.editors.array.extend({register:function(){if(this._super(),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].register()},unregister:function(){if(this._super(),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].unregister()},getNumColumns:function(){return Math.max(Math.min(12,this.width),3)},preBuild:function(){var a=this.jsoneditor.expandRefs(this.schema.items||{});this.item_title=a.title||"row",this.item_default=a["default"]||null,this.item_has_child_editors=a.properties||a.items,this.width=12,this._super()},build:function(){var a=this;this.table=this.theme.getTable(),this.container.appendChild(this.table),this.thead=this.theme.getTableHead(),this.table.appendChild(this.thead),this.header_row=this.theme.getTableRow(),this.thead.appendChild(this.header_row),this.row_holder=this.theme.getTableBody(),this.table.appendChild(this.row_holder);var b=this.getElementEditor(0,!0);if(this.item_default=b.getDefault(),this.width=b.getNumColumns()+2,this.options.compact?(this.panel=document.createElement("div"),this.container.appendChild(this.panel)):(this.title=this.theme.getHeader(this.getTitle()),this.container.appendChild(this.title),this.title_controls=this.theme.getHeaderButtonHolder(),this.title.appendChild(this.title_controls),this.schema.description&&(this.description=this.theme.getDescription(this.schema.description),this.container.appendChild(this.description)),this.panel=this.theme.getIndentedPanel(),this.container.appendChild(this.panel),this.error_holder=document.createElement("div"),this.panel.appendChild(this.error_holder)),this.panel.appendChild(this.table),this.controls=this.theme.getButtonHolder(),this.panel.appendChild(this.controls),this.item_has_child_editors)for(var c=b.getChildEditors(),d=b.property_order||Object.keys(c),e=0;e<d.length;e++){var f=a.theme.getTableHeaderCell(c[d[e]].getTitle());c[d[e]].options.hidden&&(f.style.display="none"),a.header_row.appendChild(f)}else a.header_row.appendChild(a.theme.getTableHeaderCell(this.item_title));b.destroy(),this.row_holder.innerHTML="",this.controls_header_cell=a.theme.getTableHeaderCell(" "),a.header_row.appendChild(this.controls_header_cell),this.addControls()},onChildEditorChange:function(a){this.refreshValue(),this._super()},getItemDefault:function(){return c({},{"default":this.item_default})["default"]},getItemTitle:function(){return this.item_title},getElementEditor:function(a,b){var d=c({},this.schema.items),e=this.jsoneditor.getEditorClass(d,this.jsoneditor),f=this.row_holder.appendChild(this.theme.getTableRow()),g=f;this.item_has_child_editors||(g=this.theme.getTableCell(),f.appendChild(g));var h=this.jsoneditor.createEditor(e,{jsoneditor:this.jsoneditor,schema:d,container:g,path:this.path+"."+a,parent:this,compact:!0,table_row:!0});return h.preBuild(),b||(h.build(),h.postBuild(),h.controls_cell=f.appendChild(this.theme.getTableCell()),h.row=f,h.table_controls=this.theme.getButtonHolder(),h.controls_cell.appendChild(h.table_controls),h.table_controls.style.margin=0,h.table_controls.style.padding=0),h},destroy:function(){this.innerHTML="",this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.row_holder&&this.row_holder.parentNode&&this.row_holder.parentNode.removeChild(this.row_holder),this.table&&this.table.parentNode&&this.table.parentNode.removeChild(this.table),this.panel&&this.panel.parentNode&&this.panel.parentNode.removeChild(this.panel),this.rows=this.title=this.description=this.row_holder=this.table=this.panel=null,this._super()},setValue:function(a,b){if(a=a||[],this.schema.minItems)for(;a.length<this.schema.minItems;)a.push(this.getItemDefault());this.schema.maxItems&&a.length>this.schema.maxItems&&(a=a.slice(0,this.schema.maxItems));var c=JSON.stringify(a);if(c!==this.serialized){var e=!1,f=this;d(a,function(a,b){f.rows[a]?f.rows[a].setValue(b):(f.addRow(b),e=!0)});for(var g=a.length;g<f.rows.length;g++){var h=f.rows[g].container;f.item_has_child_editors||f.rows[g].row.parentNode.removeChild(f.rows[g].row),f.rows[g].destroy(),h.parentNode&&h.parentNode.removeChild(h),f.rows[g]=null,e=!0}f.rows=f.rows.slice(0,a.length),f.refreshValue(),(e||b)&&f.refreshRowButtons(),f.onChange()}},refreshRowButtons:function(){var a=this,b=this.schema.minItems&&this.schema.minItems>=this.rows.length,c=!1;d(this.rows,function(d,e){e.movedown_button&&(d===a.rows.length-1?e.movedown_button.style.display="none":(c=!0,e.movedown_button.style.display="")),e.delete_button&&(b?e.delete_button.style.display="none":(c=!0,e.delete_button.style.display="")),e.moveup_button&&(c=!0)}),d(this.rows,function(a,b){c?b.controls_cell.style.display="":b.controls_cell.style.display="none"}),c?this.controls_header_cell.style.display="":this.controls_header_cell.style.display="none";var e=!1;this.value.length?1===this.value.length||this.hide_delete_buttons?(this.table.style.display="",this.remove_all_rows_button.style.display="none",b||this.hide_delete_buttons?this.delete_last_row_button.style.display="none":(this.delete_last_row_button.style.display="",e=!0)):(this.table.style.display="",b||this.hide_delete_buttons?(this.delete_last_row_button.style.display="none",this.remove_all_rows_button.style.display="none"):(this.delete_last_row_button.style.display="",this.remove_all_rows_button.style.display="",e=!0)):(this.delete_last_row_button.style.display="none",this.remove_all_rows_button.style.display="none",this.table.style.display="none"),this.schema.maxItems&&this.schema.maxItems<=this.rows.length||this.hide_add_button?this.add_row_button.style.display="none":(this.add_row_button.style.display="",e=!0),e?this.controls.style.display="":this.controls.style.display="none"},refreshValue:function(){var a=this;this.value=[],d(this.rows,function(b,c){a.value[b]=c.getValue()}),this.serialized=JSON.stringify(this.value)},addRow:function(a){var b=this,c=this.rows.length;b.rows[c]=this.getElementEditor(c);var e=b.rows[c].table_controls;this.hide_delete_buttons||(b.rows[c].delete_button=this.getButton("","delete","Excluir"),b.rows[c].delete_button.className+=" delete",b.rows[c].delete_button.setAttribute("data-i",c),b.rows[c].delete_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var c=1*this.getAttribute("data-i"),e=b.getValue(),f=[];d(e,function(a,b){a!==c&&f.push(b)}),b.setValue(f),b.onChange(!0)}),e.appendChild(b.rows[c].delete_button)),c&&!this.hide_move_buttons&&(b.rows[c].moveup_button=this.getButton("","moveup","Mover para cima"),b.rows[c].moveup_button.className+=" moveup",b.rows[c].moveup_button.setAttribute("data-i",c),b.rows[c].moveup_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var c=1*this.getAttribute("data-i");if(!(0>=c)){var d=b.getValue(),e=d[c-1];d[c-1]=d[c],d[c]=e,b.setValue(d),b.onChange(!0)}}),e.appendChild(b.rows[c].moveup_button)),this.hide_move_buttons||(b.rows[c].movedown_button=this.getButton("","movedown","Mover para baixo"),b.rows[c].movedown_button.className+=" movedown",b.rows[c].movedown_button.setAttribute("data-i",c),b.rows[c].movedown_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var c=1*this.getAttribute("data-i"),d=b.getValue();if(!(c>=d.length-1)){var e=d[c+1];d[c+1]=d[c],d[c]=e,b.setValue(d),b.onChange(!0)}}),e.appendChild(b.rows[c].movedown_button)),a&&b.rows[c].setValue(a)},addControls:function(){var a=this;this.collapsed=!1,this.toggle_button=this.getButton("","collapse","Collapse"),this.title_controls&&(this.title_controls.appendChild(this.toggle_button),this.toggle_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.collapsed?(a.collapsed=!1,a.panel.style.display="",a.setButtonText(this,"","collapse","Collapse")):(a.collapsed=!0,a.panel.style.display="none",a.setButtonText(this,"","expand","Expand"))}),this.options.collapsed&&e(this.toggle_button,"click"),this.schema.options&&"undefined"!=typeof this.schema.options.disable_collapse?this.schema.options.disable_collapse&&(this.toggle_button.style.display="none"):this.jsoneditor.options.disable_collapse&&(this.toggle_button.style.display="none")),this.add_row_button=this.getButton(this.getItemTitle(),"add","Add "+this.getItemTitle()),this.add_row_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.addRow(),a.refreshValue(),a.refreshRowButtons(),a.onChange(!0)}),a.controls.appendChild(this.add_row_button),this.delete_last_row_button=this.getButton("Último "+this.getItemTitle(),"delete","Excluir Último "+this.getItemTitle()),this.delete_last_row_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation();var c=a.getValue();c.pop(),a.setValue(c),a.onChange(!0)}),a.controls.appendChild(this.delete_last_row_button),this.remove_all_rows_button=this.getButton("Todos","delete","Excluir Todos"),this.remove_all_rows_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.setValue([]),a.onChange(!0)}),a.controls.appendChild(this.remove_all_rows_button)}}),f.defaults.editors.multiple=f.AbstractEditor.extend({register:function(){if(this.editors){for(var a=0;a<this.editors.length;a++)this.editors[a]&&this.editors[a].unregister();this.editors[this.type]&&this.editors[this.type].register()}this._super()},unregister:function(){if(this._super(),this.editors)for(var a=0;a<this.editors.length;a++)this.editors[a]&&this.editors[a].unregister()},getNumColumns:function(){return this.editors[this.type]?Math.max(this.editors[this.type].getNumColumns(),4):4},enable:function(){if(this.editors)for(var a=0;a<this.editors.length;a++)this.editors[a]&&this.editors[a].enable();this.switcher.disabled=!1,this._super()},disable:function(){if(this.editors)for(var a=0;a<this.editors.length;a++)this.editors[a]&&this.editors[a].disable();this.switcher.disabled=!0,this._super()},switchEditor:function(a){var b=this;this.editors[a]||this.buildChildEditor(a),b.type=a,b.register();var c=b.getValue();d(b.editors,function(a,d){d&&(b.type===a?(b.keep_values&&d.setValue(c,!0),d.container.style.display=""):d.container.style.display="none")}),b.refreshValue(),b.refreshHeaderText()},buildChildEditor:function(a){var b=this,d=this.types[a],e=b.theme.getChildEditorHolder();b.editor_holder.appendChild(e);var f;"string"==typeof d?(f=c({},b.schema),f.type=d):(f=c({},b.schema,d),f=b.jsoneditor.expandRefs(f),d.required&&Array.isArray(d.required)&&b.schema.required&&Array.isArray(b.schema.required)&&(f.required=b.schema.required.concat(d.required)));var g=b.jsoneditor.getEditorClass(f);b.editors[a]=b.jsoneditor.createEditor(g,{jsoneditor:b.jsoneditor,schema:f,container:e,path:b.path,parent:b,required:!0}),b.editors[a].preBuild(),b.editors[a].build(),b.editors[a].postBuild(),b.editors[a].header&&(b.editors[a].header.style.display="none"),b.editors[a].option=b.switcher_options[a],e.addEventListener("change_header_text",function(){b.refreshHeaderText()}),a!==b.type&&(e.style.display="none")},preBuild:function(){if(this.types=[],this.type=0,this.editors=[],this.validators=[],this.keep_values=!0,"undefined"!=typeof this.jsoneditor.options.keep_oneof_values&&(this.keep_values=this.jsoneditor.options.keep_oneof_values),"undefined"!=typeof this.options.keep_oneof_values&&(this.keep_values=this.options.keep_oneof_values),this.schema.oneOf)this.oneOf=!0,this.types=this.schema.oneOf,d(this.types,function(a,b){}),delete this.schema.oneOf;else{if(this.schema.type&&"any"!==this.schema.type)Array.isArray(this.schema.type)?this.types=this.schema.type:this.types=[this.schema.type];else if(this.types=["string","number","integer","boolean","object","array","null"],this.schema.disallow){var a=this.schema.disallow;"object"==typeof a&&Array.isArray(a)||(a=[a]);var b=[];d(this.types,function(c,d){-1===a.indexOf(d)&&b.push(d)}),this.types=b}delete this.schema.type}this.display_text=this.getDisplayText(this.types)},build:function(){var a=this,b=this.container;this.header=this.label=this.theme.getFormInputLabel(this.getTitle()),this.container.appendChild(this.header),this.switcher=this.theme.getSwitcher(this.display_text),b.appendChild(this.switcher),this.switcher.addEventListener("change",function(b){b.preventDefault(),b.stopPropagation(),a.switchEditor(a.display_text.indexOf(this.value)),a.onChange(!0)}),this.editor_holder=document.createElement("div"),b.appendChild(this.editor_holder);var e={};a.jsoneditor.options.custom_validators&&(e.custom_validators=a.jsoneditor.options.custom_validators),this.switcher_options=this.theme.getSwitcherOptions(this.switcher),d(this.types,function(b,d){a.editors[b]=!1;var g;"string"==typeof d?(g=c({},a.schema),g.type=d):(g=c({},a.schema,d),d.required&&Array.isArray(d.required)&&a.schema.required&&Array.isArray(a.schema.required)&&(g.required=a.schema.required.concat(d.required))),a.validators[b]=new f.Validator(a.jsoneditor,g,e)}),this.switchEditor(0)},onChildEditorChange:function(a){this.editors[this.type]&&(this.refreshValue(),this.refreshHeaderText()),this._super()},refreshHeaderText:function(){var a=this.getDisplayText(this.types);d(this.switcher_options,function(b,c){c.textContent=a[b]})},refreshValue:function(){this.value=this.editors[this.type].getValue()},setValue:function(a,b){var c=this;d(this.validators,function(b,d){return d.validate(a).length?void 0:(c.type=b,c.switcher.value=c.display_text[b],!1)}),this.switchEditor(this.type),this.editors[this.type].setValue(a,b),this.refreshValue(),c.onChange()},destroy:function(){d(this.editors,function(a,b){b&&b.destroy()}),this.editor_holder&&this.editor_holder.parentNode&&this.editor_holder.parentNode.removeChild(this.editor_holder),this.switcher&&this.switcher.parentNode&&this.switcher.parentNode.removeChild(this.switcher),this._super()},showValidationErrors:function(a){var b=this;this.oneOf?d(this.editors,function(e,f){if(f){var g=b.path+".oneOf["+e+"]",h=[];d(a,function(a,d){if(d.path.substr(0,g.length)===g){var e=c({},d);e.path=b.path+e.path.substr(g.length),h.push(e)}}),f.showValidationErrors(h)}}):d(this.editors,function(b,c){c&&c.showValidationErrors(a)})}}),f.defaults.editors["enum"]=f.AbstractEditor.extend({getNumColumns:function(){return 4},build:function(){this.container;this.title=this.header=this.label=this.theme.getFormInputLabel(this.getTitle()),this.container.appendChild(this.title),this.options.enum_titles=this.options.enum_titles||[],this["enum"]=this.schema["enum"],this.selected=0,this.select_options=[],this.html_values=[];for(var a=this,b=0;b<this["enum"].length;b++)this.select_options[b]=this.options.enum_titles[b]||"Value "+(b+1),this.html_values[b]=this.getHTML(this["enum"][b]);this.switcher=this.theme.getSwitcher(this.select_options),this.container.appendChild(this.switcher),this.display_area=this.theme.getIndentedPanel(),this.container.appendChild(this.display_area),this.options.hide_display&&(this.display_area.style.display="none"),this.switcher.addEventListener("change",function(){a.selected=a.select_options.indexOf(this.value),a.value=a["enum"][a.selected],a.refreshValue(),a.onChange(!0)}),this.value=this["enum"][0],this.refreshValue(),1===this["enum"].length&&(this.switcher.style.display="none")},refreshValue:function(){var a=this;a.selected=-1;var b=JSON.stringify(this.value);return d(this["enum"],function(c,d){return b===JSON.stringify(d)?(a.selected=c,!1):void 0}),a.selected<0?void a.setValue(a["enum"][0]):(this.switcher.value=this.select_options[this.selected],void(this.display_area.innerHTML=this.html_values[this.selected]))},enable:function(){this.always_disabled||(this.switcher.disabled=!1),this._super()},disable:function(){this.switcher.disabled=!0,this._super()},getHTML:function(a){var b=this;if(null===a)return"<em>null</em>";if("object"==typeof a){var c="";return d(a,function(d,e){var f=b.getHTML(e);Array.isArray(a)||(f="<div><em>"+d+"</em>: "+f+"</div>"),c+="<li>"+f+"</li>"}),c=Array.isArray(a)?"<ol>"+c+"</ol>":"<ul style='margin-top:0;margin-bottom:0;padding-top:0;padding-bottom:0;'>"+c+"</ul>"}return"boolean"==typeof a?a?"true":"false":"string"==typeof a?a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"):a},setValue:function(a){this.value!==a&&(this.value=a,this.refreshValue(),this.onChange())},destroy:function(){this.display_area&&this.display_area.parentNode&&this.display_area.parentNode.removeChild(this.display_area),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.switcher&&this.switcher.parentNode&&this.switcher.parentNode.removeChild(this.switcher),this._super()}}),f.defaults.editors.select=f.AbstractEditor.extend({setValue:function(a,b){a=this.typecast(a||"");var c=a;this.enum_values.indexOf(c)<0&&(c=this.enum_values[0]),this.value!==c&&(this.input.value=this.enum_options[this.enum_values.indexOf(c)],this.select2&&this.select2.select2("val",this.input.value),this.value=c,this.onChange())},register:function(){this._super(),this.input&&this.input.setAttribute("name",this.formname)},unregister:function(){this._super(),this.input&&this.input.removeAttribute("name")},getNumColumns:function(){if(!this.enum_options)return 3;for(var a=this.getTitle().length,b=0;b<this.enum_options.length;b++)a=Math.max(a,this.enum_options[b].length+4);return Math.min(12,Math.max(a/7,2))},typecast:function(a){return"boolean"===this.schema.type?!!a:"number"===this.schema.type?1*a:"integer"===this.schema.type?Math.floor(1*a):""+a},getValue:function(){return this.value},preBuild:function(){var a=this;if(this.input_type="select",this.enum_options=[],this.enum_values=[],this.enum_display=[],this.schema["enum"]){var b=this.schema.options&&this.schema.options.enum_titles||[];d(this.schema["enum"],function(c,d){a.enum_options[c]=""+d,a.enum_display[c]=""+(b[c]||d),a.enum_values[c]=a.typecast(d)}),this.isRequired()||(a.enum_display.unshift(" "),a.enum_options.unshift("undefined"),a.enum_values.unshift(void 0))}else if("boolean"===this.schema.type)a.enum_display=this.schema.options&&this.schema.options.enum_titles||["true","false"],a.enum_options=["1",""],a.enum_values=[!0,!1],this.isRequired()||(a.enum_display.unshift(" "),a.enum_options.unshift("undefined"),a.enum_values.unshift(void 0));else{if(!this.schema.enumSource)throw"'select' editor requires the enum property to be set.";if(this.enumSource=[],this.enum_display=[],this.enum_options=[],this.enum_values=[],Array.isArray(this.schema.enumSource))for(h=0;h<this.schema.enumSource.length;h++)"string"==typeof this.schema.enumSource[h]?this.enumSource[h]={source:this.schema.enumSource[h]}:Array.isArray(this.schema.enumSource[h])?this.enumSource[h]=this.schema.enumSource[h]:this.enumSource[h]=c({},this.schema.enumSource[h]);else this.schema.enumValue?this.enumSource=[{source:this.schema.enumSource,value:this.schema.enumValue}]:this.enumSource=[{source:this.schema.enumSource}];for(h=0;h<this.enumSource.length;h++)this.enumSource[h].value&&(this.enumSource[h].value=this.jsoneditor.compileTemplate(this.enumSource[h].value,this.template_engine)),this.enumSource[h].title&&(this.enumSource[h].title=this.jsoneditor.compileTemplate(this.enumSource[h].title,this.template_engine)),this.enumSource[h].filter&&(this.enumSource[h].filter=this.jsoneditor.compileTemplate(this.enumSource[h].filter,this.template_engine))}},build:function(){var a=this;this.options.compact||(this.header=this.label=this.theme.getFormInputLabel(this.getTitle())),this.schema.description&&(this.description=this.theme.getFormInputDescription(this.schema.description)),this.options.compact&&(this.container.className+=" compact"),this.input=this.theme.getSelectInput(this.enum_options),this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display),(this.schema.readOnly||this.schema.readonly)&&(this.always_disabled=!0,this.input.disabled=!0),this.input.addEventListener("change",function(b){b.preventDefault(),b.stopPropagation(),a.onInputChange()}),this.control=this.theme.getFormControl(this.label,this.input,this.description),this.container.appendChild(this.control),this.value=this.enum_values[0]},onInputChange:function(){var a,b=this.input.value;a=-1===this.enum_options.indexOf(b)?this.enum_values[0]:this.enum_values[this.enum_options.indexOf(b)],a!==this.value&&(this.value=a,this.onChange(!0))},setupSelect2:function(){if(window.jQuery&&window.jQuery.fn&&window.jQuery.fn.select2&&(this.enum_options.length>2||this.enum_options.length&&this.enumSource)){var a=c({},f.plugins.select2);this.schema.options&&this.schema.options.select2_options&&(a=c(a,this.schema.options.select2_options)),this.select2=window.jQuery(this.input).select2(a);var b=this;this.select2.on("select2-blur",function(){b.input.value=b.select2.select2("val"),b.onInputChange()}),this.select2.on("change",function(){b.input.value=b.select2.select2("val"),b.onInputChange()})}else this.select2=null},postBuild:function(){this._super(),this.theme.afterInputReady(this.input),this.setupSelect2()},onWatchedFieldChange:function(){var a,b;if(this.enumSource){a=this.getWatchedFieldValues();for(var c=[],d=[],e=0;e<this.enumSource.length;e++)if(Array.isArray(this.enumSource[e]))c=c.concat(this.enumSource[e]),d=d.concat(this.enumSource[e]);else{var f=[];if(f=Array.isArray(this.enumSource[e].source)?this.enumSource[e].source:a[this.enumSource[e].source]){if(this.enumSource[e].slice&&(f=Array.prototype.slice.apply(f,this.enumSource[e].slice)),this.enumSource[e].filter){var g=[];for(b=0;b<f.length;b++)this.enumSource[e].filter({i:b,item:f[b],watched:a})&&g.push(f[b]);f=g}var h=[],i=[];for(b=0;b<f.length;b++){var j=f[b];this.enumSource[e].value?i[b]=this.enumSource[e].value({i:b,item:j}):i[b]=f[b],this.enumSource[e].title?h[b]=this.enumSource[e].title({i:b,item:j}):h[b]=i[b]}c=c.concat(i),d=d.concat(h)}}var k=this.value;this.theme.setSelectOptions(this.input,c,d),this.enum_options=c,this.enum_display=d,this.enum_values=c,this.select2&&this.select2.select2("destroy"),-1!==c.indexOf(k)?(this.input.value=k,this.value=k):(this.input.value=c[0],this.value=c[0]||"",this.parent?this.parent.onChildEditorChange(this):this.jsoneditor.onChange(),this.jsoneditor.notifyWatchers(this.path)),this.setupSelect2()}this._super()},enable:function(){this.always_disabled||(this.input.disabled=!1,this.select2&&this.select2.select2("enable",!0)),this._super()},disable:function(){this.input.disabled=!0,this.select2&&this.select2.select2("enable",!1),this._super()},destroy:function(){this.label&&this.label.parentNode&&this.label.parentNode.removeChild(this.label),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this.select2&&(this.select2.select2("destroy"),this.select2=null),this._super()}}),f.defaults.editors.selectize=f.AbstractEditor.extend({setValue:function(a,b){a=this.typecast(a||"");var c=a;this.enum_values.indexOf(c)<0&&(c=this.enum_values[0]),this.value!==c&&(this.input.value=this.enum_options[this.enum_values.indexOf(c)],this.selectize&&this.selectize[0].selectize.addItem(c),this.value=c,this.onChange())},register:function(){this._super(),this.input&&this.input.setAttribute("name",this.formname)},unregister:function(){this._super(),this.input&&this.input.removeAttribute("name")},getNumColumns:function(){if(!this.enum_options)return 3;for(var a=this.getTitle().length,b=0;b<this.enum_options.length;b++)a=Math.max(a,this.enum_options[b].length+4);return Math.min(12,Math.max(a/7,2))},typecast:function(a){return"boolean"===this.schema.type?!!a:"number"===this.schema.type?1*a:"integer"===this.schema.type?Math.floor(1*a):""+a},getValue:function(){return this.value},preBuild:function(){var a=this;if(this.input_type="select",this.enum_options=[],this.enum_values=[],this.enum_display=[],this.schema["enum"]){var b=this.schema.options&&this.schema.options.enum_titles||[];d(this.schema["enum"],function(c,d){a.enum_options[c]=""+d,a.enum_display[c]=""+(b[c]||d),a.enum_values[c]=a.typecast(d)})}else if("boolean"===this.schema.type)a.enum_display=this.schema.options&&this.schema.options.enum_titles||["true","false"],a.enum_options=["1","0"],a.enum_values=[!0,!1];else{if(!this.schema.enumSource)throw"'select' editor requires the enum property to be set.";if(this.enumSource=[],this.enum_display=[],this.enum_options=[],this.enum_values=[],Array.isArray(this.schema.enumSource))for(h=0;h<this.schema.enumSource.length;h++)"string"==typeof this.schema.enumSource[h]?this.enumSource[h]={source:this.schema.enumSource[h]}:Array.isArray(this.schema.enumSource[h])?this.enumSource[h]=this.schema.enumSource[h]:this.enumSource[h]=c({},this.schema.enumSource[h]);else this.schema.enumValue?this.enumSource=[{source:this.schema.enumSource,value:this.schema.enumValue}]:this.enumSource=[{source:this.schema.enumSource}];for(h=0;h<this.enumSource.length;h++)this.enumSource[h].value&&(this.enumSource[h].value=this.jsoneditor.compileTemplate(this.enumSource[h].value,this.template_engine)),this.enumSource[h].title&&(this.enumSource[h].title=this.jsoneditor.compileTemplate(this.enumSource[h].title,this.template_engine)),this.enumSource[h].filter&&(this.enumSource[h].filter=this.jsoneditor.compileTemplate(this.enumSource[h].filter,this.template_engine))}},build:function(){var a=this;this.options.compact||(this.header=this.label=this.theme.getFormInputLabel(this.getTitle())),this.schema.description&&(this.description=this.theme.getFormInputDescription(this.schema.description)),this.options.compact&&(this.container.className+=" compact"),this.input=this.theme.getSelectInput(this.enum_options),this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display),(this.schema.readOnly||this.schema.readonly)&&(this.always_disabled=!0,this.input.disabled=!0),this.input.addEventListener("change",function(b){b.preventDefault(),b.stopPropagation(),a.onInputChange()}),this.control=this.theme.getFormControl(this.label,this.input,this.description),this.container.appendChild(this.control),this.value=this.enum_values[0]},onInputChange:function(){var a=this.input.value,b=a;-1===this.enum_options.indexOf(a)&&(b=this.enum_options[0]),this.value=this.enum_values[this.enum_options.indexOf(a)],this.onChange(!0)},setupSelectize:function(){var a=this;if(window.jQuery&&window.jQuery.fn&&window.jQuery.fn.selectize&&(this.enum_options.length>=2||this.enum_options.length&&this.enumSource)){var b=c({},f.plugins.selectize);this.schema.options&&this.schema.options.selectize_options&&(b=c(b,this.schema.options.selectize_options)),this.selectize=window.jQuery(this.input).selectize(c(b,{create:!0,onChange:function(){a.onInputChange()}}))}else this.selectize=null},postBuild:function(){this._super(),this.theme.afterInputReady(this.input),this.setupSelectize()},onWatchedFieldChange:function(){var a,b;if(this.enumSource){a=this.getWatchedFieldValues();for(var c=[],d=[],e=0;e<this.enumSource.length;e++)if(Array.isArray(this.enumSource[e]))c=c.concat(this.enumSource[e]),d=d.concat(this.enumSource[e]);else if(a[this.enumSource[e].source]){var f=a[this.enumSource[e].source];if(this.enumSource[e].slice&&(f=Array.prototype.slice.apply(f,this.enumSource[e].slice)),this.enumSource[e].filter){var g=[];for(b=0;b<f.length;b++)this.enumSource[e].filter({i:b,item:f[b]})&&g.push(f[b]);f=g}var h=[],i=[];for(b=0;b<f.length;b++){var j=f[b];this.enumSource[e].value?i[b]=this.enumSource[e].value({i:b,item:j}):i[b]=f[b],this.enumSource[e].title?h[b]=this.enumSource[e].title({i:b,item:j}):h[b]=i[b]}c=c.concat(i),d=d.concat(h)}var k=this.value;this.theme.setSelectOptions(this.input,c,d),this.enum_options=c,this.enum_display=d,this.enum_values=c,-1!==c.indexOf(k)?(this.input.value=k,this.value=k):(this.input.value=c[0],this.value=c[0]||"",this.parent?this.parent.onChildEditorChange(this):this.jsoneditor.onChange(),this.jsoneditor.notifyWatchers(this.path)),this.selectize?this.updateSelectizeOptions(c):this.setupSelectize(),this._super()}},updateSelectizeOptions:function(a){var b=this.selectize[0].selectize,c=this;b.off(),b.clearOptions();for(var d in a)b.addOption({value:a[d],text:a[d]});b.addItem(this.value),b.on("change",function(){c.onInputChange()})},enable:function(){this.always_disabled||(this.input.disabled=!1,this.selectize&&this.selectize[0].selectize.unlock()),this._super()},disable:function(){this.input.disabled=!0,this.selectize&&this.selectize[0].selectize.lock(),this._super()},destroy:function(){this.label&&this.label.parentNode&&this.label.parentNode.removeChild(this.label),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this.selectize&&(this.selectize[0].selectize.destroy(),this.selectize=null),this._super()}}),f.defaults.editors.multiselect=f.AbstractEditor.extend({preBuild:function(){this._super(),this.select_options={},this.select_values={};var a=this.jsoneditor.expandRefs(this.schema.items||{}),b=a["enum"]||[];for(this.option_keys=[],h=0;h<b.length;h++)this.sanitize(b[h])===b[h]&&(this.option_keys.push(b[h]+""),this.select_values[b[h]+""]=b[h])},build:function(){var a,b=this;if(this.options.compact||(this.header=this.label=this.theme.getFormInputLabel(this.getTitle())),this.schema.description&&(this.description=this.theme.getFormInputDescription(this.schema.description)),!this.schema.format&&this.option_keys.length<8||"checkbox"===this.schema.format){for(this.input_type="checkboxes",this.inputs={},this.controls={},a=0;a<this.option_keys.length;a++){this.inputs[this.option_keys[a]]=this.theme.getCheckbox(),this.select_options[this.option_keys[a]]=this.inputs[this.option_keys[a]];var c=this.theme.getCheckboxLabel(this.option_keys[a]);this.controls[this.option_keys[a]]=this.theme.getFormControl(c,this.inputs[this.option_keys[a]])}this.control=this.theme.getMultiCheckboxHolder(this.controls,this.label,this.description)}else{for(this.input_type="select",this.input=this.theme.getSelectInput(this.option_keys),this.input.multiple=!0,this.input.size=Math.min(10,this.option_keys.length),a=0;a<this.option_keys.length;a++)this.select_options[this.option_keys[a]]=this.input.children[a];(this.schema.readOnly||this.schema.readonly)&&(this.always_disabled=!0,this.input.disabled=!0),this.control=this.theme.getFormControl(this.label,this.input,this.description)}this.container.appendChild(this.control), this.control.addEventListener("change",function(c){c.preventDefault(),c.stopPropagation();var d=[];for(a=0;a<b.option_keys.length;a++)(b.select_options[b.option_keys[a]].selected||b.select_options[b.option_keys[a]].checked)&&d.push(b.select_values[b.option_keys[a]]);b.updateValue(d),b.onChange(!0)})},setValue:function(a,b){var c;for(a=a||[],"object"!=typeof a?a=[a]:Array.isArray(a)||(a=[]),c=0;c<a.length;c++)"string"!=typeof a[c]&&(a[c]+="");for(c in this.select_options)this.select_options.hasOwnProperty(c)&&(this.select_options[c]["select"===this.input_type?"selected":"checked"]=-1!==a.indexOf(c));this.updateValue(a),this.onChange()},setupSelect2:function(){if(window.jQuery&&window.jQuery.fn&&window.jQuery.fn.select2){var a=window.jQuery.extend({},f.plugins.select2);this.schema.options&&this.schema.options.select2_options&&(a=c(a,this.schema.options.select2_options)),this.select2=window.jQuery(this.input).select2(a);var b=this;this.select2.on("select2-blur",function(){var a=b.select2.select2("val");b.value=a,b.onChange(!0)})}else this.select2=null},onInputChange:function(){this.value=this.input.value,this.onChange(!0)},postBuild:function(){this._super(),this.setupSelect2()},register:function(){this._super(),this.input&&this.input.setAttribute("name",this.formname)},unregister:function(){this._super(),this.input&&this.input.removeAttribute("name")},getNumColumns:function(){var a=this.getTitle().length;for(var b in this.select_values)this.select_values.hasOwnProperty(b)&&(a=Math.max(a,(this.select_values[b]+"").length+4));return Math.min(12,Math.max(a/7,2))},updateValue:function(a){for(var b=!1,c=[],d=0;d<a.length;d++)if(this.select_options[a[d]+""]){var e=this.sanitize(this.select_values[a[d]]);c.push(e),e!==a[d]&&(b=!0)}else b=!0;return this.value=c,this.select2&&this.select2.select2("val",this.value),b},sanitize:function(a){return"number"===this.schema.items.type?1*a:"integer"===this.schema.items.type?Math.floor(1*a):""+a},enable:function(){if(!this.always_disabled){if(this.input)this.input.disabled=!1;else if(this.inputs)for(var a in this.inputs)this.inputs.hasOwnProperty(a)&&(this.inputs[a].disabled=!1);this.select2&&this.select2.select2("enable",!0)}this._super()},disable:function(){if(this.input)this.input.disabled=!0;else if(this.inputs)for(var a in this.inputs)this.inputs.hasOwnProperty(a)&&(this.inputs[a].disabled=!0);this.select2&&this.select2.select2("enable",!1),this._super()},destroy:function(){this.select2&&(this.select2.select2("destroy"),this.select2=null),this._super()}}),f.defaults.editors.base64=f.AbstractEditor.extend({getNumColumns:function(){return 4},build:function(){var a=this;if(this.title=this.header=this.label=this.theme.getFormInputLabel(this.getTitle()),this.input=this.theme.getFormInputField("hidden"),this.container.appendChild(this.input),!this.schema.readOnly&&!this.schema.readonly){if(!window.FileReader)throw"FileReader required for base64 editor";this.uploader=this.theme.getFormInputField("file"),this.uploader.addEventListener("change",function(b){if(b.preventDefault(),b.stopPropagation(),this.files&&this.files.length){var c=new FileReader;c.onload=function(b){a.value=b.target.result,a.refreshPreview(),a.onChange(!0),c=null},c.readAsDataURL(this.files[0])}})}this.preview=this.theme.getFormInputDescription(this.schema.description),this.container.appendChild(this.preview),this.control=this.theme.getFormControl(this.label,this.uploader||this.input,this.preview),this.container.appendChild(this.control)},refreshPreview:function(){if(this.last_preview!==this.value&&(this.last_preview=this.value,this.preview.innerHTML="",this.value)){var a=this.value.match(/^data:([^;,]+)[;,]/);if(a&&(a=a[1]),a){if(this.preview.innerHTML="<strong>Type:</strong> "+a+", <strong>Size:</strong> "+Math.floor((this.value.length-this.value.split(",")[0].length-1)/1.33333)+" bytes","image"===a.substr(0,5)){this.preview.innerHTML+="<br>";var b=document.createElement("img");b.style.maxWidth="100%",b.style.maxHeight="100px",b.src=this.value,this.preview.appendChild(b)}}else this.preview.innerHTML="<em>Invalid data URI</em>"}},enable:function(){this.uploader&&(this.uploader.disabled=!1),this._super()},disable:function(){this.uploader&&(this.uploader.disabled=!0),this._super()},setValue:function(a){this.value!==a&&(this.value=a,this.input.value=this.value,this.refreshPreview(),this.onChange())},destroy:function(){this.preview&&this.preview.parentNode&&this.preview.parentNode.removeChild(this.preview),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this.uploader&&this.uploader.parentNode&&this.uploader.parentNode.removeChild(this.uploader),this._super()}}),f.defaults.editors.upload=f.AbstractEditor.extend({getNumColumns:function(){return 4},build:function(){var a=this;if(this.title=this.header=this.label=this.theme.getFormInputLabel(this.getTitle()),this.input=this.theme.getFormInputField("hidden"),this.container.appendChild(this.input),!this.schema.readOnly&&!this.schema.readonly){if(!this.jsoneditor.options.upload)throw"Upload handler required for upload editor";this.uploader=this.theme.getFormInputField("file"),this.uploader.addEventListener("change",function(b){if(b.preventDefault(),b.stopPropagation(),this.files&&this.files.length){var c=new FileReader;c.onload=function(b){a.preview_value=b.target.result,a.refreshPreview(),a.onChange(!0),c=null},c.readAsDataURL(this.files[0])}})}var b=this.schema.description;b||(b=""),this.preview=this.theme.getFormInputDescription(b),this.container.appendChild(this.preview),this.control=this.theme.getFormControl(this.label,this.uploader||this.input,this.preview),this.container.appendChild(this.control)},refreshPreview:function(){if(this.last_preview!==this.preview_value&&(this.last_preview=this.preview_value,this.preview.innerHTML="",this.preview_value)){var a=this,b=this.preview_value.match(/^data:([^;,]+)[;,]/);b&&(b=b[1]),b||(b="unknown");var c=this.uploader.files[0];if(this.preview.innerHTML="<strong>Type:</strong> "+b+", <strong>Size:</strong> "+c.size+" bytes","image"===b.substr(0,5)){this.preview.innerHTML+="<br>";var d=document.createElement("img");d.style.maxWidth="100%",d.style.maxHeight="100px",d.src=this.preview_value,this.preview.appendChild(d)}this.preview.innerHTML+="<br>";var e=this.getButton("Upload","upload","Upload");this.preview.appendChild(e),e.addEventListener("click",function(b){b.preventDefault(),e.setAttribute("disabled","disabled"),a.theme.removeInputError(a.uploader),a.theme.getProgressBar&&(a.progressBar=a.theme.getProgressBar(),a.preview.appendChild(a.progressBar)),a.jsoneditor.options.upload(a.path,c,{success:function(b){a.setValue(b),a.parent?a.parent.onChildEditorChange(a):a.jsoneditor.onChange(),a.progressBar&&a.preview.removeChild(a.progressBar),e.removeAttribute("disabled")},failure:function(b){a.theme.addInputError(a.uploader,b),a.progressBar&&a.preview.removeChild(a.progressBar),e.removeAttribute("disabled")},updateProgress:function(b){a.progressBar&&(b?a.theme.updateProgressBar(a.progressBar,b):a.theme.updateProgressBarUnknown(a.progressBar))}})})}},enable:function(){this.uploader&&(this.uploader.disabled=!1),this._super()},disable:function(){this.uploader&&(this.uploader.disabled=!0),this._super()},setValue:function(a){this.value!==a&&(this.value=a,this.input.value=this.value,this.onChange())},destroy:function(){this.preview&&this.preview.parentNode&&this.preview.parentNode.removeChild(this.preview),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this.uploader&&this.uploader.parentNode&&this.uploader.parentNode.removeChild(this.uploader),this._super()}}),f.defaults.editors.checkbox=f.AbstractEditor.extend({setValue:function(a,b){this.value=!!a,this.input.checked=this.value,this.onChange()},register:function(){this._super(),this.input&&this.input.setAttribute("name",this.formname)},unregister:function(){this._super(),this.input&&this.input.removeAttribute("name")},getNumColumns:function(){return Math.min(12,Math.max(this.getTitle().length/7,2))},build:function(){var a=this;this.options.compact||(this.label=this.header=this.theme.getCheckboxLabel(this.getTitle())),this.schema.description&&(this.description=this.theme.getFormInputDescription(this.schema.description)),this.options.compact&&(this.container.className+=" compact"),this.input=this.theme.getCheckbox(),this.control=this.theme.getFormControl(this.label,this.input,this.description),(this.schema.readOnly||this.schema.readonly)&&(this.always_disabled=!0,this.input.disabled=!0),this.input.addEventListener("change",function(b){b.preventDefault(),b.stopPropagation(),a.value=this.checked,a.onChange(!0)}),this.container.appendChild(this.control)},enable:function(){this.always_disabled||(this.input.disabled=!1),this._super()},disable:function(){this.input.disabled=!0,this._super()},destroy:function(){this.label&&this.label.parentNode&&this.label.parentNode.removeChild(this.label),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this._super()}}),f.defaults.editors.arraySelectize=f.AbstractEditor.extend({build:function(){this.title=this.theme.getFormInputLabel(this.getTitle()),this.title_controls=this.theme.getHeaderButtonHolder(),this.title.appendChild(this.title_controls),this.error_holder=document.createElement("div"),this.schema.description&&(this.description=this.theme.getDescription(this.schema.description)),this.input=document.createElement("select"),this.input.setAttribute("multiple","multiple");var a=this.theme.getFormControl(this.title,this.input,this.description);this.container.appendChild(a),this.container.appendChild(this.error_holder),window.jQuery(this.input).selectize({delimiter:!1,createOnBlur:!0,create:!0})},postBuild:function(){var a=this;this.input.selectize.on("change",function(b){a.refreshValue(),a.onChange(!0)})},destroy:function(){this.empty(!0),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this._super()},empty:function(a){},setValue:function(a,b){var c=this;a=a||[],Array.isArray(a)||(a=[a]),this.input.selectize.clearOptions(),this.input.selectize.clear(!0),a.forEach(function(a){c.input.selectize.addOption({text:a,value:a})}),this.input.selectize.setValue(a),this.refreshValue(b)},refreshValue:function(a){this.value=this.input.selectize.getValue()},showValidationErrors:function(a){var b=this,c=[],e=[];if(d(a,function(a,d){d.path===b.path?c.push(d):e.push(d)}),this.error_holder)if(c.length){this.error_holder.innerHTML="",this.error_holder.style.display="",d(c,function(a,c){b.error_holder.appendChild(b.theme.getErrorMessage(c.message))})}else this.error_holder.style.display="none"}});var g=function(){var a=document.documentElement;return a.matches?"matches":a.webkitMatchesSelector?"webkitMatchesSelector":a.mozMatchesSelector?"mozMatchesSelector":a.msMatchesSelector?"msMatchesSelector":a.oMatchesSelector?"oMatchesSelector":void 0}();f.AbstractTheme=a.extend({getContainer:function(){return document.createElement("div")},getFloatRightLinkHolder:function(){var a=document.createElement("div");return a.style=a.style||{},a.style.cssFloat="right",a.style.marginLeft="10px",a},getModal:function(){var a=document.createElement("div");return a.style.backgroundColor="white",a.style.border="1px solid black",a.style.boxShadow="3px 3px black",a.style.position="absolute",a.style.zIndex="10",a.style.display="none",a},getGridContainer:function(){var a=document.createElement("div");return a},getGridRow:function(){var a=document.createElement("div");return a.className="row",a},getGridColumn:function(){var a=document.createElement("div");return a},setGridColumnSize:function(a,b){},getLink:function(a){var b=document.createElement("a");return b.setAttribute("href","#"),b.appendChild(document.createTextNode(a)),b},disableHeader:function(a){a.style.color="#ccc"},disableLabel:function(a){a.style.color="#ccc"},enableHeader:function(a){a.style.color=""},enableLabel:function(a){a.style.color=""},getFormInputLabel:function(a){var b=document.createElement("label");return b.appendChild(document.createTextNode(a)),b},getCheckboxLabel:function(a){var b=this.getFormInputLabel(a);return b.style.fontWeight="normal",b},getHeader:function(a){var b=document.createElement("h3");return"string"==typeof a?b.textContent=a:b.appendChild(a),b},getCheckbox:function(){var a=this.getFormInputField("checkbox");return a.style.display="inline-block",a.style.width="auto",a},getMultiCheckboxHolder:function(a,b,c){var d=document.createElement("div");b&&(b.style.display="block",d.appendChild(b));for(var e in a)a.hasOwnProperty(e)&&(a[e].style.display="inline-block",a[e].style.marginRight="20px",d.appendChild(a[e]));return c&&d.appendChild(c),d},getSelectInput:function(a){var b=document.createElement("select");return a&&this.setSelectOptions(b,a),b},getSwitcher:function(a){var b=this.getSelectInput(a);return b.style.backgroundColor="transparent",b.style.display="inline-block",b.style.fontStyle="italic",b.style.fontWeight="normal",b.style.height="auto",b.style.marginBottom=0,b.style.marginLeft="5px",b.style.padding="0 0 0 3px",b.style.width="auto",b},getSwitcherOptions:function(a){return a.getElementsByTagName("option")},setSwitcherOptions:function(a,b,c){this.setSelectOptions(a,b,c)},setSelectOptions:function(a,b,c){c=c||[],a.innerHTML="";for(var d=0;d<b.length;d++){var e=document.createElement("option");e.setAttribute("value",b[d]),e.textContent=c[d]||b[d],a.appendChild(e)}},getTextareaInput:function(){var a=document.createElement("textarea");return a.style=a.style||{},a.style.width="100%",a.style.height="300px",a.style.boxSizing="border-box",a},getRangeInput:function(a,b,c){var d=this.getFormInputField("range");return d.setAttribute("min",a),d.setAttribute("max",b),d.setAttribute("step",c),d},getFormInputField:function(a){var b=document.createElement("input");return b.setAttribute("type",a),b},afterInputReady:function(a){},getFormControl:function(a,b,c){var d=document.createElement("div");return d.className="form-control",a&&d.appendChild(a),"checkbox"===b.type?a.insertBefore(b,a.firstChild):d.appendChild(b),c&&d.appendChild(c),d},getIndentedPanel:function(){var a=document.createElement("div");return a.style=a.style||{},a.style.paddingLeft="10px",a.style.marginLeft="10px",a.style.borderLeft="1px solid #ccc",a},getChildEditorHolder:function(){return document.createElement("div")},getDescription:function(a){var b=document.createElement("p");return b.innerHTML=a,b},getCheckboxDescription:function(a){return this.getDescription(a)},getFormInputDescription:function(a){return this.getDescription(a)},getHeaderButtonHolder:function(){return this.getButtonHolder()},getButtonHolder:function(){return document.createElement("div")},getButton:function(a,b,c){var d=document.createElement("button");return d.type="button",this.setButtonText(d,a,b,c),d},setButtonText:function(a,b,c,d){a.innerHTML="",c&&(a.appendChild(c),a.innerHTML+=" "),a.appendChild(document.createTextNode(b)),d&&a.setAttribute("title",d)},getTable:function(){return document.createElement("table")},getTableRow:function(){return document.createElement("tr")},getTableHead:function(){return document.createElement("thead")},getTableBody:function(){return document.createElement("tbody")},getTableHeaderCell:function(a){var b=document.createElement("th");return b.textContent=a,b},getTableCell:function(){var a=document.createElement("td");return a},getErrorMessage:function(a){var b=document.createElement("p");return b.style=b.style||{},b.style.color="red",b.appendChild(document.createTextNode(a)),b},addInputError:function(a,b){},removeInputError:function(a){},addTableRowError:function(a){},removeTableRowError:function(a){},getTabHolder:function(){var a=document.createElement("div");return a.innerHTML="<div style='float: left; width: 130px;' class='tabs'></div><div class='content' style='margin-left: 130px;'></div><div style='clear:both;'></div>",a},applyStyles:function(a,b){a.style=a.style||{};for(var c in b)b.hasOwnProperty(c)&&(a.style[c]=b[c])},closest:function(a,b){for(;a&&a!==document;){if(!g)return!1;if(a[g](b))return a;a=a.parentNode}return!1},getTab:function(a){var b=document.createElement("div");return b.appendChild(a),b.style=b.style||{},this.applyStyles(b,{border:"1px solid #ccc",borderWidth:"1px 0 1px 1px",textAlign:"center",lineHeight:"30px",borderRadius:"5px",borderBottomRightRadius:0,borderTopRightRadius:0,fontWeight:"bold",cursor:"pointer"}),b},getTabContentHolder:function(a){return a.children[1]},getTabContent:function(){return this.getIndentedPanel()},markTabActive:function(a){this.applyStyles(a,{opacity:1,background:"white"})},markTabInactive:function(a){this.applyStyles(a,{opacity:.5,background:""})},addTab:function(a,b){a.children[0].appendChild(b)},getBlockLink:function(){var a=document.createElement("a");return a.style.display="block",a},getBlockLinkHolder:function(){var a=document.createElement("div");return a},getLinksHolder:function(){var a=document.createElement("div");return a},createMediaLink:function(a,b,c){a.appendChild(b),c.style.width="100%",a.appendChild(c)},createImageLink:function(a,b,c){a.appendChild(b),b.appendChild(c)}}),f.defaults.themes.bootstrap2=f.AbstractTheme.extend({getRangeInput:function(a,b,c){return this._super(a,b,c)},getGridContainer:function(){var a=document.createElement("div");return a.className="container-fluid",a},getGridRow:function(){var a=document.createElement("div");return a.className="row-fluid",a},getFormInputLabel:function(a){var b=this._super(a);return b.style.display="inline-block",b.style.fontWeight="bold",b},setGridColumnSize:function(a,b){a.className="span"+b},getSelectInput:function(a){var b=this._super(a);return b.style.width="auto",b.style.maxWidth="98%",b},getFormInputField:function(a){var b=this._super(a);return b.style.width="98%",b},afterInputReady:function(a){a.controlgroup||(a.controlgroup=this.closest(a,".control-group"),a.controls=this.closest(a,".controls"),this.closest(a,".compact")&&(a.controlgroup.className=a.controlgroup.className.replace(/control-group/g,"").replace(/[ ]{2,}/g," "),a.controls.className=a.controlgroup.className.replace(/controls/g,"").replace(/[ ]{2,}/g," "),a.style.marginBottom=0))},getIndentedPanel:function(){var a=document.createElement("div");return a.className="well well-small",a.style.paddingBottom=0,a},getFormInputDescription:function(a){var b=document.createElement("p");return b.className="help-inline",b.textContent=a,b},getFormControl:function(a,b,c){var d=document.createElement("div");d.className="control-group";var e=document.createElement("div");return e.className="controls",a&&"checkbox"===b.getAttribute("type")?(d.appendChild(e),a.className+=" checkbox",a.appendChild(b),e.appendChild(a),e.style.height="30px"):(a&&(a.className+=" control-label",d.appendChild(a)),e.appendChild(b),d.appendChild(e)),c&&e.appendChild(c),d},getHeaderButtonHolder:function(){var a=this.getButtonHolder();return a.style.marginLeft="10px",a},getButtonHolder:function(){var a=document.createElement("div");return a.className="btn-group",a},getButton:function(a,b,c){var d=this._super(a,b,c);return d.className+=" btn btn-default",d},getTable:function(){var a=document.createElement("table");return a.className="table table-bordered",a.style.width="auto",a.style.maxWidth="none",a},addInputError:function(a,b){a.controlgroup&&a.controls&&(a.controlgroup.className+=" error",a.errmsg?a.errmsg.style.display="":(a.errmsg=document.createElement("p"),a.errmsg.className="help-block errormsg",a.controls.appendChild(a.errmsg)),a.errmsg.textContent=b)},removeInputError:function(a){a.errmsg&&(a.errmsg.style.display="none",a.controlgroup.className=a.controlgroup.className.replace(/\s?error/g,""))},getTabHolder:function(){var a=document.createElement("div");return a.className="tabbable tabs-left",a.innerHTML="<ul class='nav nav-tabs span2' style='margin-right: 0;'></ul><div class='tab-content span10' style='overflow:visible;'></div>",a},getTab:function(a){var b=document.createElement("li"),c=document.createElement("a");return c.setAttribute("href","#"),c.appendChild(a),b.appendChild(c),b},getTabContentHolder:function(a){return a.children[1]},getTabContent:function(){var a=document.createElement("div");return a.className="tab-pane active",a},markTabActive:function(a){a.className+=" active"},markTabInactive:function(a){a.className=a.className.replace(/\s?active/g,"")},addTab:function(a,b){a.children[0].appendChild(b)},getProgressBar:function(){var a=document.createElement("div");a.className="progress";var b=document.createElement("div");return b.className="bar",b.style.width="0%",a.appendChild(b),a},updateProgressBar:function(a,b){a&&(a.firstChild.style.width=b+"%")},updateProgressBarUnknown:function(a){a&&(a.className="progress progress-striped active",a.firstChild.style.width="100%")}}),f.defaults.themes.bootstrap3=f.AbstractTheme.extend({getSelectInput:function(a){var b=this._super(a);return b.className+="form-control",b},setGridColumnSize:function(a,b){a.className="col-md-"+b},afterInputReady:function(a){a.controlgroup||(a.controlgroup=this.closest(a,".form-group"),this.closest(a,".compact")&&(a.controlgroup.style.marginBottom=0))},getTextareaInput:function(){var a=document.createElement("textarea");return a.className="form-control",a},getRangeInput:function(a,b,c){return this._super(a,b,c)},getFormInputField:function(a){var b=this._super(a);return"checkbox"!==a&&(b.className+="form-control"),b},getFormControl:function(a,b,c){var d=document.createElement("div");return a&&"checkbox"===b.type?(d.className+=" checkbox",a.appendChild(b),a.style.fontSize="14px",d.style.marginTop="0",d.appendChild(a),b.style.position="relative",b.style.cssFloat="left"):(d.className+=" form-group",a&&(a.className+=" control-label",d.appendChild(a)),d.appendChild(b)),c&&d.appendChild(c),d},getIndentedPanel:function(){var a=document.createElement("div");return a.className="well well-sm",a.style.paddingBottom=0,a},getFormInputDescription:function(a){var b=document.createElement("p");return b.className="help-block",b.innerHTML=a,b},getHeaderButtonHolder:function(){var a=this.getButtonHolder();return a.style.marginLeft="10px",a},getButtonHolder:function(){var a=document.createElement("div");return a.className="btn-group",a},getButton:function(a,b,c){var d=this._super(a,b,c);return d.className+="btn btn-default",d},getTable:function(){var a=document.createElement("table");return a.className="table table-bordered",a.style.width="auto",a.style.maxWidth="none",a},addInputError:function(a,b){a.controlgroup&&(a.controlgroup.className+=" has-error",a.errmsg?a.errmsg.style.display="":(a.errmsg=document.createElement("p"),a.errmsg.className="help-block errormsg",a.controlgroup.appendChild(a.errmsg)),a.errmsg.textContent=b)},removeInputError:function(a){a.errmsg&&(a.errmsg.style.display="none",a.controlgroup.className=a.controlgroup.className.replace(/\s?has-error/g,""))},getTabHolder:function(){var a=document.createElement("div");return a.innerHTML="<div class='tabs list-group col-md-2'></div><div class='col-md-10'></div>",a.className="rows",a},getTab:function(a){var b=document.createElement("a");return b.className="list-group-item",b.setAttribute("href","#"),b.appendChild(a),b},markTabActive:function(a){a.className+=" active"},markTabInactive:function(a){a.className=a.className.replace(/\s?active/g,"")},getProgressBar:function(){var a=0,b=100,c=0,d=document.createElement("div");d.className="progress";var e=document.createElement("div");return e.className="progress-bar",e.setAttribute("role","progressbar"),e.setAttribute("aria-valuenow",c),e.setAttribute("aria-valuemin",a),e.setAttribute("aria-valuenax",b),e.innerHTML=c+"%",d.appendChild(e),d},updateProgressBar:function(a,b){if(a){var c=a.firstChild,d=b+"%";c.setAttribute("aria-valuenow",b),c.style.width=d,c.innerHTML=d}},updateProgressBarUnknown:function(a){if(a){var b=a.firstChild;a.className="progress progress-striped active",b.removeAttribute("aria-valuenow"),b.style.width="100%",b.innerHTML=""}}}),f.defaults.themes.foundation=f.AbstractTheme.extend({getChildEditorHolder:function(){var a=document.createElement("div");return a.style.marginBottom="15px",a},getSelectInput:function(a){var b=this._super(a);return b.style.minWidth="none",b.style.padding="5px",b.style.marginTop="3px",b},getSwitcher:function(a){var b=this._super(a);return b.style.paddingRight="8px",b},afterInputReady:function(a){this.closest(a,".compact")&&(a.style.marginBottom=0),a.group=this.closest(a,".form-control")},getFormInputLabel:function(a){var b=this._super(a);return b.style.display="inline-block",b},getFormInputField:function(a){var b=this._super(a);return b.style.width="100%",b.style.marginBottom="checkbox"===a?"0":"12px",b},getFormInputDescription:function(a){var b=document.createElement("p");return b.textContent=a,b.style.marginTop="-10px",b.style.fontStyle="italic",b},getIndentedPanel:function(){var a=document.createElement("div");return a.className="panel",a.style.paddingBottom=0,a},getHeaderButtonHolder:function(){var a=this.getButtonHolder();return a.style.display="inline-block",a.style.marginLeft="10px",a.style.verticalAlign="middle",a},getButtonHolder:function(){var a=document.createElement("div");return a.className="button-group",a},getButton:function(a,b,c){var d=this._super(a,b,c);return d.className+=" small button",d},addInputError:function(a,b){a.group&&(a.group.className+=" error",a.errmsg?a.errmsg.style.display="":(a.insertAdjacentHTML("afterend",'<small class="error"></small>'),a.errmsg=a.parentNode.getElementsByClassName("error")[0]),a.errmsg.textContent=b)},removeInputError:function(a){a.errmsg&&(a.group.className=a.group.className.replace(/ error/g,""),a.errmsg.style.display="none")},getProgressBar:function(){var a=document.createElement("div");a.className="progress";var b=document.createElement("span");return b.className="meter",b.style.width="0%",a.appendChild(b),a},updateProgressBar:function(a,b){a&&(a.firstChild.style.width=b+"%")},updateProgressBarUnknown:function(a){a&&(a.firstChild.style.width="100%")}}),f.defaults.themes.foundation3=f.defaults.themes.foundation.extend({getHeaderButtonHolder:function(){var a=this._super();return a.style.fontSize=".6em",a},getFormInputLabel:function(a){var b=this._super(a);return b.style.fontWeight="bold",b},getTabHolder:function(){var a=document.createElement("div");return a.className="row",a.innerHTML="<dl class='tabs vertical two columns'></dl><div class='tabs-content ten columns'></div>",a},setGridColumnSize:function(a,b){var c=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];a.className="columns "+c[b]},getTab:function(a){var b=document.createElement("dd"),c=document.createElement("a");return c.setAttribute("href","#"),c.appendChild(a),b.appendChild(c),b},getTabContentHolder:function(a){return a.children[1]},getTabContent:function(){var a=document.createElement("div");return a.className="content active",a.style.paddingLeft="5px",a},markTabActive:function(a){a.className+=" active"},markTabInactive:function(a){a.className=a.className.replace(/\s*active/g,"")},addTab:function(a,b){a.children[0].appendChild(b)}}),f.defaults.themes.foundation4=f.defaults.themes.foundation.extend({getHeaderButtonHolder:function(){var a=this._super();return a.style.fontSize=".6em",a},setGridColumnSize:function(a,b){a.className="columns large-"+b},getFormInputDescription:function(a){var b=this._super(a);return b.style.fontSize=".8rem",b},getFormInputLabel:function(a){var b=this._super(a);return b.style.fontWeight="bold",b}}),f.defaults.themes.foundation5=f.defaults.themes.foundation.extend({getFormInputDescription:function(a){var b=this._super(a);return b.style.fontSize=".8rem",b},setGridColumnSize:function(a,b){a.className="columns medium-"+b},getButton:function(a,b,c){var d=this._super(a,b,c);return d.className=d.className.replace(/\s*small/g,"")+" tiny",d},getTabHolder:function(){var a=document.createElement("div");return a.innerHTML="<dl class='tabs vertical'></dl><div class='tabs-content vertical'></div>",a},getTab:function(a){var b=document.createElement("dd"),c=document.createElement("a");return c.setAttribute("href","#"),c.appendChild(a),b.appendChild(c),b},getTabContentHolder:function(a){return a.children[1]},getTabContent:function(){var a=document.createElement("div");return a.className="content active",a.style.paddingLeft="5px",a},markTabActive:function(a){a.className+=" active"},markTabInactive:function(a){a.className=a.className.replace(/\s*active/g,"")},addTab:function(a,b){a.children[0].appendChild(b)}}),f.defaults.themes.html=f.AbstractTheme.extend({getFormInputLabel:function(a){var b=this._super(a);return b.style.display="block",b.style.marginBottom="3px",b.style.fontWeight="bold",b},getFormInputDescription:function(a){var b=this._super(a);return b.style.fontSize=".8em",b.style.margin=0,b.style.display="inline-block",b.style.fontStyle="italic",b},getIndentedPanel:function(){var a=this._super();return a.style.border="1px solid #ddd",a.style.padding="5px",a.style.margin="5px",a.style.borderRadius="3px",a},getChildEditorHolder:function(){var a=this._super();return a.style.marginBottom="8px",a},getHeaderButtonHolder:function(){var a=this.getButtonHolder();return a.style.display="inline-block",a.style.marginLeft="10px",a.style.fontSize=".8em",a.style.verticalAlign="middle",a},getTable:function(){var a=this._super();return a.style.borderBottom="1px solid #ccc",a.style.marginBottom="5px",a},addInputError:function(a,b){if(a.style.borderColor="red",a.errmsg)a.errmsg.style.display="block";else{var c=this.closest(a,".form-control");a.errmsg=document.createElement("div"),a.errmsg.setAttribute("class","errmsg"),a.errmsg.style=a.errmsg.style||{},a.errmsg.style.color="red",c.appendChild(a.errmsg)}a.errmsg.innerHTML="",a.errmsg.appendChild(document.createTextNode(b))},removeInputError:function(a){a.style.borderColor="",a.errmsg&&(a.errmsg.style.display="none")},getProgressBar:function(){var a=100,b=0,c=document.createElement("progress");return c.setAttribute("max",a),c.setAttribute("value",b),c},updateProgressBar:function(a,b){a&&a.setAttribute("value",b)},updateProgressBarUnknown:function(a){a&&a.removeAttribute("value")}}),f.defaults.themes.jqueryui=f.AbstractTheme.extend({getTable:function(){var a=this._super();return a.setAttribute("cellpadding",5),a.setAttribute("cellspacing",0),a},getTableHeaderCell:function(a){var b=this._super(a);return b.className="ui-state-active",b.style.fontWeight="bold",b},getTableCell:function(){var a=this._super();return a.className="ui-widget-content",a},getHeaderButtonHolder:function(){var a=this.getButtonHolder();return a.style.marginLeft="10px",a.style.fontSize=".6em",a.style.display="inline-block",a},getFormInputDescription:function(a){var b=this.getDescription(a);return b.style.marginLeft="10px",b.style.display="inline-block",b},getFormControl:function(a,b,c){var d=this._super(a,b,c);return"checkbox"===b.type?(d.style.lineHeight="25px",d.style.padding="3px 0"):d.style.padding="4px 0 8px 0",d},getDescription:function(a){var b=document.createElement("span");return b.style.fontSize=".8em",b.style.fontStyle="italic",b.textContent=a,b},getButtonHolder:function(){var a=document.createElement("div");return a.className="ui-buttonset",a.style.fontSize=".7em",a},getFormInputLabel:function(a){var b=document.createElement("label");return b.style.fontWeight="bold",b.style.display="block",b.textContent=a,b},getButton:function(a,b,c){var d=document.createElement("button");d.className="ui-button ui-widget ui-state-default ui-corner-all", b&&!a?(d.className+=" ui-button-icon-only",b.className+=" ui-button-icon-primary ui-icon-primary",d.appendChild(b)):b?(d.className+=" ui-button-text-icon-primary",b.className+=" ui-button-icon-primary ui-icon-primary",d.appendChild(b)):d.className+=" ui-button-text-only";var e=document.createElement("span");return e.className="ui-button-text",e.textContent=a||c||".",d.appendChild(e),d.setAttribute("title",c),d},setButtonText:function(a,b,c,d){a.innerHTML="",a.className="ui-button ui-widget ui-state-default ui-corner-all",c&&!b?(a.className+=" ui-button-icon-only",c.className+=" ui-button-icon-primary ui-icon-primary",a.appendChild(c)):c?(a.className+=" ui-button-text-icon-primary",c.className+=" ui-button-icon-primary ui-icon-primary",a.appendChild(c)):a.className+=" ui-button-text-only";var e=document.createElement("span");e.className="ui-button-text",e.textContent=b||d||".",a.appendChild(e),a.setAttribute("title",d)},getIndentedPanel:function(){var a=document.createElement("div");return a.className="ui-widget-content ui-corner-all",a.style.padding="1em 1.4em",a.style.marginBottom="20px",a},afterInputReady:function(a){a.controls||(a.controls=this.closest(a,".form-control"))},addInputError:function(a,b){a.controls&&(a.errmsg?a.errmsg.style.display="":(a.errmsg=document.createElement("div"),a.errmsg.className="ui-state-error",a.controls.appendChild(a.errmsg)),a.errmsg.textContent=b)},removeInputError:function(a){a.errmsg&&(a.errmsg.style.display="none")},markTabActive:function(a){a.className=a.className.replace(/\s*ui-widget-header/g,"")+" ui-state-active"},markTabInactive:function(a){a.className=a.className.replace(/\s*ui-state-active/g,"")+" ui-widget-header"}}),f.AbstractIconLib=a.extend({mapping:{collapse:"",expand:"","delete":"",edit:"",add:"",cancel:"",save:"",moveup:"",movedown:""},icon_prefix:"",getIconClass:function(a){return this.mapping[a]?this.icon_prefix+this.mapping[a]:null},getIcon:function(a){var b=this.getIconClass(a);if(!b)return null;var c=document.createElement("i");return c.className=b,c}}),f.defaults.iconlibs.bootstrap2=f.AbstractIconLib.extend({mapping:{collapse:"chevron-down",expand:"chevron-up","delete":"trash",edit:"pencil",add:"plus",cancel:"ban-circle",save:"ok",moveup:"arrow-up",movedown:"arrow-down"},icon_prefix:"icon-"}),f.defaults.iconlibs.bootstrap3=f.AbstractIconLib.extend({mapping:{collapse:"chevron-down",expand:"chevron-right","delete":"remove",edit:"pencil",add:"plus",cancel:"floppy-remove",save:"floppy-saved",moveup:"arrow-up",movedown:"arrow-down"},icon_prefix:"glyphicon glyphicon-"}),f.defaults.iconlibs.fontawesome3=f.AbstractIconLib.extend({mapping:{collapse:"chevron-down",expand:"chevron-right","delete":"remove",edit:"pencil",add:"plus",cancel:"ban-circle",save:"save",moveup:"arrow-up",movedown:"arrow-down"},icon_prefix:"icon-"}),f.defaults.iconlibs.fontawesome4=f.AbstractIconLib.extend({mapping:{collapse:"caret-square-o-down",expand:"caret-square-o-right","delete":"times",edit:"pencil",add:"plus",cancel:"ban",save:"save",moveup:"arrow-up",movedown:"arrow-down"},icon_prefix:"fa fa-"}),f.defaults.iconlibs.foundation2=f.AbstractIconLib.extend({mapping:{collapse:"minus",expand:"plus","delete":"remove",edit:"edit",add:"add-doc",cancel:"error",save:"checkmark",moveup:"up-arrow",movedown:"down-arrow"},icon_prefix:"foundicon-"}),f.defaults.iconlibs.foundation3=f.AbstractIconLib.extend({mapping:{collapse:"minus",expand:"plus","delete":"x",edit:"pencil",add:"page-add",cancel:"x-circle",save:"save",moveup:"arrow-up",movedown:"arrow-down"},icon_prefix:"fi-"}),f.defaults.iconlibs.jqueryui=f.AbstractIconLib.extend({mapping:{collapse:"triangle-1-s",expand:"triangle-1-e","delete":"trash",edit:"pencil",add:"plusthick",cancel:"closethick",save:"disk",moveup:"arrowthick-1-n",movedown:"arrowthick-1-s"},icon_prefix:"ui-icon ui-icon-"}),f.defaults.templates["default"]=function(){return{compile:function(a){var b=a.match(/{{\s*([a-zA-Z0-9\-_ \.]+)\s*}}/g),c=b&&b.length;if(!c)return function(){return a};for(var d=[],e=function(a){var c,e=b[a].replace(/[{}]+/g,"").trim().split("."),f=e.length;if(f>1){var g;c=function(b){for(g=b,a=0;f>a&&(g=g[e[a]],g);a++);return g}}else e=e[0],c=function(a){return a[e]};d.push({s:b[a],r:c})},f=0;c>f;f++)e(f);return function(b){var e,g=a+"";for(f=0;c>f;f++)e=d[f],g=g.replace(e.s,e.r(b));return g}}}},f.defaults.templates.ejs=function(){return window.EJS?{compile:function(a){var b=new window.EJS({text:a});return function(a){return b.render(a)}}}:!1},f.defaults.templates.handlebars=function(){return window.Handlebars},f.defaults.templates.hogan=function(){return window.Hogan?{compile:function(a){var b=window.Hogan.compile(a);return function(a){return b.render(a)}}}:!1},f.defaults.templates.markup=function(){return window.Mark&&window.Mark.up?{compile:function(a){return function(b){return window.Mark.up(a,b)}}}:!1},f.defaults.templates.mustache=function(){return window.Mustache?{compile:function(a){return function(b){return window.Mustache.render(a,b)}}}:!1},f.defaults.templates.swig=function(){return window.swig},f.defaults.templates.underscore=function(){return window._?{compile:function(a){return function(b){return window._.template(a,b)}}}:!1},f.defaults.theme="html",f.defaults.template="default",f.defaults.options={},f.defaults.translate=function(a,b){var c=f.defaults.languages[f.defaults.language];if(!c)throw"Unknown language "+f.defaults.language;var d=c[a]||f.defaults.languages[f.defaults.default_language][a];if("undefined"==typeof d)throw"Unknown translate string "+a;if(b)for(var e=0;e<b.length;e++)d=d.replace(new RegExp("\\{\\{"+e+"}}","g"),b[e]);return d},f.defaults.default_language="en",f.defaults.language=f.defaults.default_language,f.defaults.languages.en={error_notset:"Property must be set",error_notempty:"Value required",error_enum:"Value must be one of the enumerated values",error_anyOf:"Value must validate against at least one of the provided schemas",error_oneOf:"Value must validate against exactly one of the provided schemas. It currently validates against {{0}} of the schemas.",error_not:"Value must not validate against the provided schema",error_type_union:"Value must be one of the provided types",error_type:"Value must be of type {{0}}",error_disallow_union:"Value must not be one of the provided disallowed types",error_disallow:"Value must not be of type {{0}}",error_multipleOf:"Value must be a multiple of {{0}}",error_maximum_excl:"Value must be less than {{0}}",error_maximum_incl:"Value must be at most {{0}}",error_minimum_excl:"Value must be greater than {{0}}",error_minimum_incl:"Value must be at least {{0}}",error_maxLength:"Value must be at most {{0}} characters long",error_minLength:"Value must be at least {{0}} characters long",error_pattern:"Value must match the provided pattern",error_additionalItems:"No additional items allowed in this array",error_maxItems:"Value must have at most {{0}} items",error_minItems:"Value must have at least {{0}} items",error_uniqueItems:"Array must have unique items",error_maxProperties:"Object must have at most {{0}} properties",error_minProperties:"Object must have at least {{0}} properties",error_required:"Object is missing the required property '{{0}}'",error_additional_properties:"No additional properties allowed, but property {{0}} is set",error_dependency:"Must have property {{0}}"},f.plugins={ace:{theme:""},epiceditor:{},sceditor:{},select2:{},selectize:{}};for(var h in f.defaults.editors)f.defaults.editors.hasOwnProperty(h)&&(f.defaults.editors[h].options=f.defaults.editors.options||{});f.defaults.resolvers.unshift(function(a){return"string"!=typeof a.type?"multiple":void 0}),f.defaults.resolvers.unshift(function(a){return!a.type&&a.properties?"object":void 0}),f.defaults.resolvers.unshift(function(a){return"string"==typeof a.type?a.type:void 0}),f.defaults.resolvers.unshift(function(a){return"boolean"===a.type?"checkbox"===a.format||a.options&&a.options.checkbox?"checkbox":f.plugins.selectize.enable?"selectize":"select":void 0}),f.defaults.resolvers.unshift(function(a){return"any"===a.type?"multiple":void 0}),f.defaults.resolvers.unshift(function(a){return"string"===a.type&&a.media&&"base64"===a.media.binaryEncoding?"base64":void 0}),f.defaults.resolvers.unshift(function(a){return"string"===a.type&&"url"===a.format&&a.options&&a.options.upload===!0&&window.FileReader?"upload":void 0}),f.defaults.resolvers.unshift(function(a){return"array"==a.type&&"table"==a.format?"table":void 0}),f.defaults.resolvers.unshift(function(a){return a.enumSource?f.plugins.selectize.enable?"selectize":"select":void 0}),f.defaults.resolvers.unshift(function(a){if(a["enum"]){if("array"===a.type||"object"===a.type)return"enum";if("number"===a.type||"integer"===a.type||"string"===a.type)return f.plugins.selectize.enable?"selectize":"select"}}),f.defaults.resolvers.unshift(function(a){if("array"===a.type&&a.items&&!Array.isArray(a.items)&&a.uniqueItems&&["string","number","integer"].indexOf(a.items.type)>=0){if(a.items["enum"])return"multiselect";if(f.plugins.selectize.enable&&"string"===a.items.type)return"arraySelectize"}}),f.defaults.resolvers.unshift(function(a){return a.oneOf?"multiple":void 0}),function(){if(window.jQuery||window.Zepto){var a=window.jQuery||window.Zepto;a.jsoneditor=f.defaults,a.fn.jsoneditor=function(a){var b=this,c=this.data("jsoneditor");if("value"===a){if(!c)throw"Must initialize jsoneditor before getting/setting the value";if(!(arguments.length>1))return c.getValue();c.setValue(arguments[1])}else{if("validate"===a){if(!c)throw"Must initialize jsoneditor before validating";return arguments.length>1?c.validate(arguments[1]):c.validate()}"destroy"===a?c&&(c.destroy(),this.data("jsoneditor",null)):(c&&c.destroy(),c=new f(this.get(0),a),this.data("jsoneditor",c),c.on("change",function(){b.trigger("change")}),c.on("ready",function(){b.trigger("ready")}))}return this}}}(),window.JSONEditor=f}();
* Date: 2015-09-27 */ !function(){var a;!function(){var b=!1,c=/xyz/.test(function(){window.postMessage("xyz")})?/\b_super\b/:/.*/;return a=function(){},a.extend=function(a){function d(){!b&&this.init&&this.init.apply(this,arguments)}var e=this.prototype;b=!0;var f=new this;b=!1;for(var g in a)f[g]="function"==typeof a[g]&&"function"==typeof e[g]&&c.test(a[g])?function(a,b){return function(){var c=this._super;this._super=e[a];var d=b.apply(this,arguments);return this._super=c,d}}(g,a[g]):a[g];return d.prototype=f,d.prototype.constructor=d,d.extend=arguments.callee,d},a}(),function(){function a(a,b){b=b||{bubbles:!1,cancelable:!1,detail:void 0};var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,b.bubbles,b.cancelable,b.detail),c}a.prototype=window.Event.prototype,window.CustomEvent=a}(),function(){for(var a=0,b=["ms","moz","webkit","o"],c=0;c<b.length&&!window.requestAnimationFrame;++c)window.requestAnimationFrame=window[b[c]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[b[c]+"CancelAnimationFrame"]||window[b[c]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(b,c){var d=(new Date).getTime(),e=Math.max(0,16-(d-a)),f=window.setTimeout(function(){b(d+e)},e);return a=d+e,f}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})}(),function(){Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)})}();var b=function(a){return"object"!=typeof a||a.nodeType||null!==a&&a===a.window?!1:a.constructor&&!Object.prototype.hasOwnProperty.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},c=function(a){var d,e,f;for(e=1;e<arguments.length;e++){d=arguments[e];for(f in d)d.hasOwnProperty(f)&&(d[f]&&b(d[f])?(a.hasOwnProperty(f)||(a[f]={}),c(a[f],d[f])):a[f]=d[f])}return a},d=function(a,b){if(a&&"object"==typeof a){var c;if(Array.isArray(a)||"number"==typeof a.length&&a.length>0&&a.length-1 in a){for(c=0;c<a.length;c++)if(b(c,a[c])===!1)return}else if(Object.keys){var d=Object.keys(a);for(c=0;c<d.length;c++)if(b(d[c],a[d[c]])===!1)return}else for(c in a)if(a.hasOwnProperty(c)&&b(c,a[c])===!1)return}},e=function(a,b){var c=document.createEvent("HTMLEvents");c.initEvent(b,!0,!0),a.dispatchEvent(c)},f=function(a,b){if(!(a instanceof Element))throw new Error("element should be an instance of Element");b=c({},f.defaults.options,b||{}),this.element=a,this.options=b,this.init()};f.prototype={constructor:f,init:function(){var a=this;this.ready=!1;var b=f.defaults.themes[this.options.theme||f.defaults.theme];if(!b)throw"Unknown theme "+(this.options.theme||f.defaults.theme);this.schema=this.options.schema,this.theme=new b,this.template=this.options.template,this.refs=this.options.refs||{},this.uuid=0,this.__data={};var c=f.defaults.iconlibs[this.options.iconlib||f.defaults.iconlib];c&&(this.iconlib=new c),this.root_container=this.theme.getContainer(),this.element.appendChild(this.root_container),this.translate=this.options.translate||f.defaults.translate,this._loadExternalRefs(this.schema,function(){a._getDefinitions(a.schema);var b={};a.options.custom_validators&&(b.custom_validators=a.options.custom_validators),a.validator=new f.Validator(a,null,b);var c=a.getEditorClass(a.schema);a.root=a.createEditor(c,{jsoneditor:a,schema:a.schema,required:!0,container:a.root_container}),a.root.preBuild(),a.root.build(),a.root.postBuild(),a.options.startval&&a.root.setValue(a.options.startval),a.validation_results=a.validator.validate(a.root.getValue()),a.root.showValidationErrors(a.validation_results),a.ready=!0,window.requestAnimationFrame(function(){a.ready&&(a.validation_results=a.validator.validate(a.root.getValue()),a.root.showValidationErrors(a.validation_results),a.trigger("ready"),a.trigger("change"))})})},getValue:function(){if(!this.ready)throw"JSON Editor not ready yet. Listen for 'ready' event before getting the value";return this.root.getValue()},setValue:function(a){if(!this.ready)throw"JSON Editor not ready yet. Listen for 'ready' event before setting the value";return this.root.setValue(a),this},validate:function(a){if(!this.ready)throw"JSON Editor not ready yet. Listen for 'ready' event before validating";return 1===arguments.length?this.validator.validate(a):this.validation_results},destroy:function(){this.destroyed||this.ready&&(this.schema=null,this.options=null,this.root.destroy(),this.root=null,this.root_container=null,this.validator=null,this.validation_results=null,this.theme=null,this.iconlib=null,this.template=null,this.__data=null,this.ready=!1,this.element.innerHTML="",this.destroyed=!0)},on:function(a,b){return this.callbacks=this.callbacks||{},this.callbacks[a]=this.callbacks[a]||[],this.callbacks[a].push(b),this},off:function(a,b){if(a&&b){this.callbacks=this.callbacks||{},this.callbacks[a]=this.callbacks[a]||[];for(var c=[],d=0;d<this.callbacks[a].length;d++)this.callbacks[a][d]!==b&&c.push(this.callbacks[a][d]);this.callbacks[a]=c}else a?(this.callbacks=this.callbacks||{},this.callbacks[a]=[]):this.callbacks={};return this},trigger:function(a){if(this.callbacks&&this.callbacks[a]&&this.callbacks[a].length)for(var b=0;b<this.callbacks[a].length;b++)this.callbacks[a][b]();return this},setOption:function(a,b){if("show_errors"!==a)throw"Option "+a+" must be set during instantiation and cannot be changed later";return this.options.show_errors=b,this.onChange(),this},getEditorClass:function(a){var b;if(a=this.expandSchema(a),d(f.defaults.resolvers,function(c,d){var e=d(a);return e&&f.defaults.editors[e]?(b=e,!1):void 0}),!b)throw"Unknown editor for schema "+JSON.stringify(a);if(!f.defaults.editors[b])throw"Unknown editor "+b;return f.defaults.editors[b]},createEditor:function(a,b){return b=c({},a.options||{},b),new a(b)},onChange:function(){if(this.ready&&!this.firing_change){this.firing_change=!0;var a=this;return window.requestAnimationFrame(function(){a.firing_change=!1,a.ready&&(a.validation_results=a.validator.validate(a.root.getValue()),"never"!==a.options.show_errors?a.root.showValidationErrors(a.validation_results):a.root.showValidationErrors([]),a.trigger("change"))}),this}},compileTemplate:function(a,b){b=b||f.defaults.template;var c;if("string"==typeof b){if(!f.defaults.templates[b])throw"Unknown template engine "+b;if(c=f.defaults.templates[b](),!c)throw"Template engine "+b+" missing required library."}else c=b;if(!c)throw"No template engine set";if(!c.compile)throw"Invalid template engine set";return c.compile(a)},_data:function(a,b,c){if(3!==arguments.length)return a.hasAttribute("data-jsoneditor-"+b)?this.__data[a.getAttribute("data-jsoneditor-"+b)]:null;var d;a.hasAttribute("data-jsoneditor-"+b)?d=a.getAttribute("data-jsoneditor-"+b):(d=this.uuid++,a.setAttribute("data-jsoneditor-"+b,d)),this.__data[d]=c},registerEditor:function(a){return this.editors=this.editors||{},this.editors[a.path]=a,this},unregisterEditor:function(a){return this.editors=this.editors||{},this.editors[a.path]=null,this},getEditor:function(a){return this.editors?this.editors[a]:void 0},watch:function(a,b){return this.watchlist=this.watchlist||{},this.watchlist[a]=this.watchlist[a]||[],this.watchlist[a].push(b),this},unwatch:function(a,b){if(!this.watchlist||!this.watchlist[a])return this;if(!b)return this.watchlist[a]=null,this;for(var c=[],d=0;d<this.watchlist[a].length;d++)this.watchlist[a][d]!==b&&c.push(this.watchlist[a][d]);return this.watchlist[a]=c.length?c:null,this},notifyWatchers:function(a){if(!this.watchlist||!this.watchlist[a])return this;for(var b=0;b<this.watchlist[a].length;b++)this.watchlist[a][b]()},isEnabled:function(){return!this.root||this.root.isEnabled()},enable:function(){this.root.enable()},disable:function(){this.root.disable()},_getDefinitions:function(a,b){if(b=b||"#/definitions/",a.definitions)for(var c in a.definitions)a.definitions.hasOwnProperty(c)&&(this.refs[b+c]=a.definitions[c],a.definitions[c].definitions&&this._getDefinitions(a.definitions[c],b+c+"/definitions/"))},_getExternalRefs:function(a){var b={},c=function(a){for(var c in a)a.hasOwnProperty(c)&&(b[c]=!0)};a.$ref&&"object"!=typeof a.$ref&&"#"!==a.$ref.substr(0,1)&&!this.refs[a.$ref]&&(b[a.$ref]=!0);for(var d in a)if(a.hasOwnProperty(d))if(a[d]&&"object"==typeof a[d]&&Array.isArray(a[d]))for(var e=0;e<a[d].length;e++)"object"==typeof a[d][e]&&c(this._getExternalRefs(a[d][e]));else a[d]&&"object"==typeof a[d]&&c(this._getExternalRefs(a[d]));return b},_loadExternalRefs:function(a,b){var c=this,e=this._getExternalRefs(a),f=0,g=0,h=!1;d(e,function(a){if(!c.refs[a]){if(!c.options.ajax)throw"Must set ajax option to true to load external ref "+a;c.refs[a]="loading",g++;var d=new XMLHttpRequest;d.open("GET",a,!0),d.onreadystatechange=function(){if(4==d.readyState){if(200!==d.status)throw window.console.log(d),"Failed to fetch ref via ajax- "+a;var e;try{e=JSON.parse(d.responseText)}catch(i){throw window.console.log(i),"Failed to parse external ref "+a}if(!e||"object"!=typeof e)throw"External ref does not contain a valid schema - "+a;c.refs[a]=e,c._loadExternalRefs(e,function(){f++,f>=g&&!h&&(h=!0,b())})}},d.send()}}),g||b()},expandRefs:function(a){for(a=c({},a);a.$ref;){var b=a.$ref;delete a.$ref,this.refs[b]||(b=decodeURIComponent(b)),a=this.extendSchemas(a,this.refs[b])}return a},expandSchema:function(a){var b,e=this,f=c({},a);if("object"==typeof a.type&&(Array.isArray(a.type)?d(a.type,function(b,c){"object"==typeof c&&(a.type[b]=e.expandSchema(c))}):a.type=e.expandSchema(a.type)),"object"==typeof a.disallow&&(Array.isArray(a.disallow)?d(a.disallow,function(b,c){"object"==typeof c&&(a.disallow[b]=e.expandSchema(c))}):a.disallow=e.expandSchema(a.disallow)),a.anyOf&&d(a.anyOf,function(b,c){a.anyOf[b]=e.expandSchema(c)}),a.dependencies&&d(a.dependencies,function(b,c){"object"!=typeof c||Array.isArray(c)||(a.dependencies[b]=e.expandSchema(c))}),a.not&&(a.not=this.expandSchema(a.not)),a.allOf){for(b=0;b<a.allOf.length;b++)f=this.extendSchemas(f,this.expandSchema(a.allOf[b]));delete f.allOf}if(a["extends"]){if(Array.isArray(a["extends"]))for(b=0;b<a["extends"].length;b++)f=this.extendSchemas(f,this.expandSchema(a["extends"][b]));else f=this.extendSchemas(f,this.expandSchema(a["extends"]));delete f["extends"]}if(a.oneOf){var g=c({},f);for(delete g.oneOf,b=0;b<a.oneOf.length;b++)f.oneOf[b]=this.extendSchemas(this.expandSchema(a.oneOf[b]),g)}return this.expandRefs(f)},extendSchemas:function(a,b){a=c({},a),b=c({},b);var e=this,f={};return d(a,function(a,c){"undefined"!=typeof b[a]?"required"===a&&"object"==typeof c&&Array.isArray(c)?f.required=c.concat(b[a]).reduce(function(a,b){return a.indexOf(b)<0&&a.push(b),a},[]):"type"!==a||"string"!=typeof c&&!Array.isArray(c)?"object"==typeof c&&Array.isArray(c)?f[a]=c.filter(function(c){return-1!==b[a].indexOf(c)}):"object"==typeof c&&null!==c?f[a]=e.extendSchemas(c,b[a]):f[a]=c:("string"==typeof c&&(c=[c]),"string"==typeof b.type&&(b.type=[b.type]),f.type=c.filter(function(a){return-1!==b.type.indexOf(a)}),1===f.type.length&&"string"==typeof f.type[0]&&(f.type=f.type[0])):f[a]=c}),d(b,function(b,c){"undefined"==typeof a[b]&&(f[b]=c)}),f}},f.defaults={themes:{},templates:{},iconlibs:{},editors:{},languages:{},resolvers:[],custom_validators:[]},f.Validator=a.extend({init:function(a,b,c){this.jsoneditor=a,this.schema=b||this.jsoneditor.schema,this.options=c||{},this.translate=this.jsoneditor.translate||f.defaults.translate},validate:function(a){return this._validateSchema(this.schema,a)},_validateSchema:function(a,b,e){var g,h,i,j=this,k=[],l=JSON.stringify(b);if(e=e||"root",a=c({},this.jsoneditor.expandRefs(a)),a.required&&a.required===!0){if("undefined"==typeof b)return k.push({path:e,property:"required",message:this.translate("error_notset")}),k}else if("undefined"==typeof b){if(!this.jsoneditor.options.required_by_default)return k;k.push({path:e,property:"required",message:this.translate("error_notset")})}if(a["enum"]){for(g=!1,h=0;h<a["enum"].length;h++)l===JSON.stringify(a["enum"][h])&&(g=!0);g||k.push({path:e,property:"enum",message:this.translate("error_enum")})}if(a["extends"])for(h=0;h<a["extends"].length;h++)k=k.concat(this._validateSchema(a["extends"][h],b,e));if(a.allOf)for(h=0;h<a.allOf.length;h++)k=k.concat(this._validateSchema(a.allOf[h],b,e));if(a.anyOf){for(g=!1,h=0;h<a.anyOf.length;h++)if(!this._validateSchema(a.anyOf[h],b,e).length){g=!0;break}g||k.push({path:e,property:"anyOf",message:this.translate("error_anyOf")})}if(a.oneOf){g=0;var m=[];for(h=0;h<a.oneOf.length;h++){var n=this._validateSchema(a.oneOf[h],b,e);for(n.length||g++,i=0;i<n.length;i++)n[i].path=e+".oneOf["+h+"]"+n[i].path.substr(e.length);m=m.concat(n)}1!==g&&(k.push({path:e,property:"oneOf",message:this.translate("error_oneOf",[g])}),k=k.concat(m))}if(a.not&&(this._validateSchema(a.not,b,e).length||k.push({path:e,property:"not",message:this.translate("error_not")})),a.type)if(Array.isArray(a.type)){for(g=!1,h=0;h<a.type.length;h++)if(this._checkType(a.type[h],b)){g=!0;break}g||k.push({path:e,property:"type",message:this.translate("error_type_union")})}else this._checkType(a.type,b)||k.push({path:e,property:"type",message:this.translate("error_type",[a.type])});if(a.disallow)if(Array.isArray(a.disallow)){for(g=!0,h=0;h<a.disallow.length;h++)if(this._checkType(a.disallow[h],b)){g=!1;break}g||k.push({path:e,property:"disallow",message:this.translate("error_disallow_union")})}else this._checkType(a.disallow,b)&&k.push({path:e,property:"disallow",message:this.translate("error_disallow",[a.disallow])});if("number"==typeof b)(a.multipleOf||a.divisibleBy)&&(g=b/(a.multipleOf||a.divisibleBy),g!==Math.floor(g)&&k.push({path:e,property:a.multipleOf?"multipleOf":"divisibleBy",message:this.translate("error_multipleOf",[a.multipleOf||a.divisibleBy])})),a.hasOwnProperty("maximum")&&(a.exclusiveMaximum&&b>=a.maximum?k.push({path:e,property:"maximum",message:this.translate("error_maximum_excl",[a.maximum])}):!a.exclusiveMaximum&&b>a.maximum&&k.push({path:e,property:"maximum",message:this.translate("error_maximum_incl",[a.maximum])})),a.hasOwnProperty("minimum")&&(a.exclusiveMinimum&&b<=a.minimum?k.push({path:e,property:"minimum",message:this.translate("error_minimum_excl",[a.minimum])}):!a.exclusiveMinimum&&b<a.minimum&&k.push({path:e,property:"minimum",message:this.translate("error_minimum_incl",[a.minimum])}));else if("string"==typeof b)a.maxLength&&(b+"").length>a.maxLength&&k.push({path:e,property:"maxLength",message:this.translate("error_maxLength",[a.maxLength])}),a.minLength&&(b+"").length<a.minLength&&k.push({path:e,property:"minLength",message:this.translate(1===a.minLength?"error_notempty":"error_minLength",[a.minLength])}),a.pattern&&(new RegExp(a.pattern).test(b)||k.push({path:e,property:"pattern",message:this.translate("error_pattern")}));else if("object"==typeof b&&null!==b&&Array.isArray(b)){if(a.items)if(Array.isArray(a.items))for(h=0;h<b.length;h++)if(a.items[h])k=k.concat(this._validateSchema(a.items[h],b[h],e+"."+h));else{if(a.additionalItems===!0)break;if(!a.additionalItems){if(a.additionalItems===!1){k.push({path:e,property:"additionalItems",message:this.translate("error_additionalItems")});break}break}k=k.concat(this._validateSchema(a.additionalItems,b[h],e+"."+h))}else for(h=0;h<b.length;h++)k=k.concat(this._validateSchema(a.items,b[h],e+"."+h));if(a.maxItems&&b.length>a.maxItems&&k.push({path:e,property:"maxItems",message:this.translate("error_maxItems",[a.maxItems])}),a.minItems&&b.length<a.minItems&&k.push({path:e,property:"minItems",message:this.translate("error_minItems",[a.minItems])}),a.uniqueItems){var o={};for(h=0;h<b.length;h++){if(g=JSON.stringify(b[h]),o[g]){k.push({path:e,property:"uniqueItems",message:this.translate("error_uniqueItems")});break}o[g]=!0}}}else if("object"==typeof b&&null!==b){if(a.maxProperties){g=0;for(h in b)b.hasOwnProperty(h)&&g++;g>a.maxProperties&&k.push({path:e,property:"maxProperties",message:this.translate("error_maxProperties",[a.maxProperties])})}if(a.minProperties){g=0;for(h in b)b.hasOwnProperty(h)&&g++;g<a.minProperties&&k.push({path:e,property:"minProperties",message:this.translate("error_minProperties",[a.minProperties])})}if(a.required&&Array.isArray(a.required))for(h=0;h<a.required.length;h++)"undefined"==typeof b[a.required[h]]&&k.push({path:e,property:"required",message:this.translate("error_required",[a.required[h]])});var p={};if(a.properties)for(h in a.properties)a.properties.hasOwnProperty(h)&&(p[h]=!0,k=k.concat(this._validateSchema(a.properties[h],b[h],e+"."+h)));if(a.patternProperties)for(h in a.patternProperties)if(a.patternProperties.hasOwnProperty(h)){var q=new RegExp(h);for(i in b)b.hasOwnProperty(i)&&q.test(i)&&(p[i]=!0,k=k.concat(this._validateSchema(a.patternProperties[h],b[i],e+"."+i)))}if("undefined"!=typeof a.additionalProperties||!this.jsoneditor.options.no_additional_properties||a.oneOf||a.anyOf||(a.additionalProperties=!1),"undefined"!=typeof a.additionalProperties)for(h in b)if(b.hasOwnProperty(h)&&!p[h]){if(!a.additionalProperties){k.push({path:e,property:"additionalProperties",message:this.translate("error_additional_properties",[h])});break}if(a.additionalProperties===!0)break;k=k.concat(this._validateSchema(a.additionalProperties,b[h],e+"."+h))}if(a.dependencies)for(h in a.dependencies)if(a.dependencies.hasOwnProperty(h)&&"undefined"!=typeof b[h])if(Array.isArray(a.dependencies[h]))for(i=0;i<a.dependencies[h].length;i++)"undefined"==typeof b[a.dependencies[h][i]]&&k.push({path:e,property:"dependencies",message:this.translate("error_dependency",[a.dependencies[h][i]])});else k=k.concat(this._validateSchema(a.dependencies[h],b,e))}return d(f.defaults.custom_validators,function(c,d){k=k.concat(d.call(j,a,b,e))}),this.options.custom_validators&&d(this.options.custom_validators,function(c,d){k=k.concat(d.call(j,a,b,e))}),k},_checkType:function(a,b){return"string"==typeof a?"string"===a?"string"==typeof b:"number"===a?"number"==typeof b:"integer"===a?"number"==typeof b&&b===Math.floor(b):"boolean"===a?"boolean"==typeof b:"array"===a?Array.isArray(b):"object"===a?null!==b&&!Array.isArray(b)&&"object"==typeof b:"null"===a?null===b:!0:!this._validateSchema(a,b).length}}),f.AbstractEditor=a.extend({onChildEditorChange:function(a){this.onChange(!0)},notify:function(){this.jsoneditor.notifyWatchers(this.path)},change:function(){this.parent?this.parent.onChildEditorChange(this):this.jsoneditor.onChange()},onChange:function(a){this.notify(),this.watch_listener&&this.watch_listener(),a&&this.change()},register:function(){this.jsoneditor.registerEditor(this),this.onChange()},unregister:function(){this.jsoneditor&&this.jsoneditor.unregisterEditor(this)},getNumColumns:function(){return 12},init:function(a){this.jsoneditor=a.jsoneditor,this.theme=this.jsoneditor.theme,this.template_engine=this.jsoneditor.template,this.iconlib=this.jsoneditor.iconlib,this.original_schema=a.schema,this.schema=this.jsoneditor.expandSchema(this.original_schema),this.options=c({},this.options||{},a.schema.options||{},a),a.path||this.schema.id||(this.schema.id="root"),this.path=a.path||"root",this.formname=a.formname||this.path.replace(/\.([^.]+)/g,"[$1]"),this.jsoneditor.options.form_name_root&&(this.formname=this.formname.replace(/^root\[/,this.jsoneditor.options.form_name_root+"[")),this.key=this.path.split(".").pop(),this.parent=a.parent,this.link_watchers=[],a.container&&this.setContainer(a.container)},setContainer:function(a){this.container=a,this.schema.id&&this.container.setAttribute("data-schemaid",this.schema.id),this.schema.type&&"string"==typeof this.schema.type&&this.container.setAttribute("data-schematype",this.schema.type),this.container.setAttribute("data-schemapath",this.path)},preBuild:function(){},build:function(){},postBuild:function(){this.setupWatchListeners(),this.addLinks(),this.setValue(this.getDefault(),!0),this.updateHeaderText(),this.register(),this.onWatchedFieldChange()},setupWatchListeners:function(){var a=this;if(this.watched={},this.schema.vars&&(this.schema.watch=this.schema.vars),this.watched_values={},this.watch_listener=function(){a.refreshWatchedFieldValues()&&a.onWatchedFieldChange()},this.register(),this.schema.hasOwnProperty("watch")){var b,c,d,e,f;for(var g in this.schema.watch)if(this.schema.watch.hasOwnProperty(g)){if(b=this.schema.watch[g],Array.isArray(b)?c=[b[0]].concat(b[1].split(".")):(c=b.split("."),a.theme.closest(a.container,'[data-schemaid="'+c[0]+'"]')||c.unshift("#")),d=c.shift(),"#"===d&&(d=a.jsoneditor.schema.id||"root"),e=a.theme.closest(a.container,'[data-schemaid="'+d+'"]'),!e)throw"Could not find ancestor node with id "+d;f=e.getAttribute("data-schemapath")+"."+c.join("."),a.jsoneditor.watch(f,a.watch_listener),a.watched[g]=f}}this.schema.headerTemplate&&(this.header_template=this.jsoneditor.compileTemplate(this.schema.headerTemplate,this.template_engine))},addLinks:function(){if(!this.no_link_holder&&(this.link_holder=this.theme.getLinksHolder(),this.container.appendChild(this.link_holder),this.schema.links))for(var a=0;a<this.schema.links.length;a++)this.addLink(this.getLink(this.schema.links[a]))},getButton:function(a,b,c){var d="json-editor-btn-"+b;b=this.iconlib?this.iconlib.getIcon(b):null,!b&&c&&(a=c,c=null);var e=this.theme.getButton(a,b,c);return e.className+=" "+d+" ",e},setButtonText:function(a,b,c,d){return c=this.iconlib?this.iconlib.getIcon(c):null,!c&&d&&(b=d,d=null),this.theme.setButtonText(a,b,c,d)},addLink:function(a){this.link_holder&&this.link_holder.appendChild(a)},getLink:function(a){var b,c,d=a.mediaType||"application/javascript",e=d.split("/")[0],f=this.jsoneditor.compileTemplate(a.href,this.template_engine);if("image"===e){b=this.theme.getBlockLinkHolder(),c=document.createElement("a"),c.setAttribute("target","_blank");var g=document.createElement("img");this.theme.createImageLink(b,c,g),this.link_watchers.push(function(b){var d=f(b);c.setAttribute("href",d),c.setAttribute("title",a.rel||d),g.setAttribute("src",d)})}else if(["audio","video"].indexOf(e)>=0){b=this.theme.getBlockLinkHolder(),c=this.theme.getBlockLink(),c.setAttribute("target","_blank");var h=document.createElement(e);h.setAttribute("controls","controls"),this.theme.createMediaLink(b,c,h),this.link_watchers.push(function(b){var d=f(b);c.setAttribute("href",d),c.textContent=a.rel||d,h.setAttribute("src",d)})}else b=this.theme.getBlockLink(),b.setAttribute("target","_blank"),b.textContent=a.rel,this.link_watchers.push(function(c){var d=f(c);b.setAttribute("href",d),b.textContent=a.rel||d});return b},refreshWatchedFieldValues:function(){if(this.watched_values){var a={},b=!1,c=this;if(this.watched){var d,e;for(var f in this.watched)this.watched.hasOwnProperty(f)&&(e=c.jsoneditor.getEditor(this.watched[f]),d=e?e.getValue():null,c.watched_values[f]!==d&&(b=!0),a[f]=d)}return a.self=this.getValue(),this.watched_values.self!==a.self&&(b=!0),this.watched_values=a,b}},getWatchedFieldValues:function(){return this.watched_values},updateHeaderText:function(){if(this.header)if(this.header.children.length){for(var a=0;a<this.header.childNodes.length;a++)if(3===this.header.childNodes[a].nodeType){this.header.childNodes[a].nodeValue=this.getHeaderText();break}}else this.header.textContent=this.getHeaderText()},getHeaderText:function(a){return this.header_text?this.header_text:a?this.schema.title:this.getTitle()},onWatchedFieldChange:function(){var a;if(this.header_template){a=c(this.getWatchedFieldValues(),{key:this.key,i:this.key,i0:1*this.key,i1:1*this.key+1,title:this.getTitle()});var b=this.header_template(a);b!==this.header_text&&(this.header_text=b,this.updateHeaderText(),this.notify())}if(this.link_watchers.length){a=this.getWatchedFieldValues();for(var d=0;d<this.link_watchers.length;d++)this.link_watchers[d](a)}},setValue:function(a){this.value=a},getValue:function(){return this.value},refreshValue:function(){},getChildEditors:function(){return!1},destroy:function(){var a=this;this.unregister(this),d(this.watched,function(b,c){a.jsoneditor.unwatch(c,a.watch_listener)}),this.watched=null,this.watched_values=null,this.watch_listener=null,this.header_text=null,this.header_template=null,this.value=null,this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null,this.jsoneditor=null,this.schema=null,this.path=null,this.key=null,this.parent=null},getDefault:function(){if(this.schema["default"])return this.schema["default"];if(this.schema["enum"])return this.schema["enum"][0];var a=this.schema.type||this.schema.oneOf;if(a&&Array.isArray(a)&&(a=a[0]),a&&"object"==typeof a&&(a=a.type),a&&Array.isArray(a)&&(a=a[0]),"string"==typeof a){if("number"===a)return 0;if("boolean"===a)return!1;if("integer"===a)return 0;if("string"===a)return"";if("object"===a)return{};if("array"===a)return[]}return null},getTitle:function(){return this.schema.title||this.key},enable:function(){this.disabled=!1},disable:function(){this.disabled=!0},isEnabled:function(){return!this.disabled},isRequired:function(){return"boolean"==typeof this.schema.required?this.schema.required:this.parent&&this.parent.schema&&Array.isArray(this.parent.schema.required)?this.parent.schema.required.indexOf(this.key)>-1:this.jsoneditor.options.required_by_default?!0:!1},getDisplayText:function(a){var b=[],c={};d(a,function(a,b){b.title&&(c[b.title]=c[b.title]||0,c[b.title]++),b.description&&(c[b.description]=c[b.description]||0,c[b.description]++),b.format&&(c[b.format]=c[b.format]||0,c[b.format]++),b.type&&(c[b.type]=c[b.type]||0,c[b.type]++)}),d(a,function(a,d){var e;e="string"==typeof d?d:d.title&&c[d.title]<=1?d.title:d.format&&c[d.format]<=1?d.format:d.type&&c[d.type]<=1?d.type:d.description&&c[d.description]<=1?d.descripton:d.title?d.title:d.format?d.format:d.type?d.type:d.description?d.description:JSON.stringify(d).length<50?JSON.stringify(d):"type",b.push(e)});var e={};return d(b,function(a,d){e[d]=e[d]||0,e[d]++,c[d]>1&&(b[a]=d+" "+e[d])}),b},getOption:function(a){try{throw"getOption is deprecated"}catch(b){window.console.error(b)}return this.options[a]},showValidationErrors:function(a){}}),f.defaults.editors["null"]=f.AbstractEditor.extend({getValue:function(){return null},setValue:function(){this.onChange()},getNumColumns:function(){return 2}}),f.defaults.editors.string=f.AbstractEditor.extend({register:function(){this._super(),this.input&&this.input.setAttribute("name",this.formname)},unregister:function(){this._super(),this.input&&this.input.removeAttribute("name")},setValue:function(a,b,c){if((!this.template||c)&&(null===a||"undefined"==typeof a?a="":"object"==typeof a?a=JSON.stringify(a):"string"!=typeof a&&(a=""+a),a!==this.serialized)){var d=this.sanitize(a);if(this.input.value!==d){this.input.value=d,this.sceditor_instance?this.sceditor_instance.val(d):this.epiceditor?this.epiceditor.importFile(null,d):this.ace_editor&&this.ace_editor.setValue(d);var e=c||this.getValue()!==a;this.refreshValue(),b?this.is_dirty=!1:"change"===this.jsoneditor.options.show_errors&&(this.is_dirty=!0),this.adjust_height&&this.adjust_height(this.input),this.onChange(e)}}},getNumColumns:function(){var a,b=Math.ceil(Math.max(this.getTitle().length,this.schema.maxLength||0,this.schema.minLength||0)/5);return a="textarea"===this.input_type?6:["text","email"].indexOf(this.input_type)>=0?4:2,Math.min(12,Math.max(b,a))},build:function(){var a=this;if(this.options.compact||(this.header=this.label=this.theme.getFormInputLabel(this.getTitle())),this.schema.description&&(this.description=this.theme.getFormInputDescription(this.schema.description)),this.format=this.schema.format,!this.format&&this.schema.media&&this.schema.media.type&&(this.format=this.schema.media.type.replace(/(^(application|text)\/(x-)?(script\.)?)|(-source$)/g,"")),!this.format&&this.options.default_format&&(this.format=this.options.default_format),this.options.format&&(this.format=this.options.format),this.format)if("textarea"===this.format)this.input_type="textarea",this.input=this.theme.getTextareaInput();else if("range"===this.format){this.input_type="range";var b=this.schema.minimum||0,c=this.schema.maximum||Math.max(100,b+1),d=1;this.schema.multipleOf&&(b%this.schema.multipleOf&&(b=Math.ceil(b/this.schema.multipleOf)*this.schema.multipleOf),c%this.schema.multipleOf&&(c=Math.floor(c/this.schema.multipleOf)*this.schema.multipleOf),d=this.schema.multipleOf),this.input=this.theme.getRangeInput(b,c,d)}else["actionscript","batchfile","bbcode","c","c++","cpp","coffee","csharp","css","dart","django","ejs","erlang","golang","handlebars","haskell","haxe","html","ini","jade","java","javascript","json","less","lisp","lua","makefile","markdown","matlab","mysql","objectivec","pascal","perl","pgsql","php","python","r","ruby","sass","scala","scss","smarty","sql","stylus","svg","twig","vbscript","xml","yaml"].indexOf(this.format)>=0?(this.input_type=this.format,this.source_code=!0,this.input=this.theme.getTextareaInput()):(this.input_type=this.format,this.input=this.theme.getFormInputField(this.input_type));else this.input_type="text",this.input=this.theme.getFormInputField(this.input_type);"undefined"!=typeof this.schema.maxLength&&this.input.setAttribute("maxlength",this.schema.maxLength),"undefined"!=typeof this.schema.pattern?this.input.setAttribute("pattern",this.schema.pattern):"undefined"!=typeof this.schema.minLength&&this.input.setAttribute("pattern",".{"+this.schema.minLength+",}"),this.options.compact?this.container.className+=" compact":this.options.input_width&&(this.input.style.width=this.options.input_width),(this.schema.readOnly||this.schema.readonly||this.schema.template)&&(this.always_disabled=!0,this.input.disabled=!0),this.input.addEventListener("change",function(b){if(b.preventDefault(),b.stopPropagation(),a.schema.template)return void(this.value=a.value);var c=this.value,d=a.sanitize(c);c!==d&&(this.value=d),a.is_dirty=!0,a.refreshValue(),a.onChange(!0)}),this.options.input_height&&(this.input.style.height=this.options.input_height),this.options.expand_height&&(this.adjust_height=function(a){if(a){var b,c=a.offsetHeight;if(a.offsetHeight<a.scrollHeight)for(b=0;a.offsetHeight<a.scrollHeight+3&&!(b>100);)b++,c++,a.style.height=c+"px";else{for(b=0;a.offsetHeight>=a.scrollHeight+3&&!(b>100);)b++,c--,a.style.height=c+"px";a.style.height=c+1+"px"}}},this.input.addEventListener("keyup",function(b){a.adjust_height(this)}),this.input.addEventListener("change",function(b){a.adjust_height(this)}),this.adjust_height()),this.format&&this.input.setAttribute("data-schemaformat",this.format),this.control=this.theme.getFormControl(this.label,this.input,this.description),this.container.appendChild(this.control),window.requestAnimationFrame(function(){a.input.parentNode&&a.afterInputReady(),a.adjust_height&&a.adjust_height(a.input)}),this.schema.template?(this.template=this.jsoneditor.compileTemplate(this.schema.template,this.template_engine),this.refreshValue()):this.refreshValue()},enable:function(){this.always_disabled||(this.input.disabled=!1),this._super()},disable:function(){this.input.disabled=!0,this._super()},afterInputReady:function(){var a,b=this;if(this.source_code)if(this.options.wysiwyg&&["html","bbcode"].indexOf(this.input_type)>=0&&window.jQuery&&window.jQuery.fn&&window.jQuery.fn.sceditor)a=c({},{plugins:"html"===b.input_type?"xhtml":"bbcode",emoticonsEnabled:!1,width:"100%",height:300},f.plugins.sceditor,b.options.sceditor_options||{}),window.jQuery(b.input).sceditor(a),b.sceditor_instance=window.jQuery(b.input).sceditor("instance"),b.sceditor_instance.blur(function(){var a=window.jQuery("<div>"+b.sceditor_instance.val()+"</div>");window.jQuery("#sceditor-start-marker,#sceditor-end-marker,.sceditor-nlf",a).remove(),b.input.value=a.html(),b.value=b.input.value,b.is_dirty=!0,b.onChange(!0)});else if("markdown"===this.input_type&&window.EpicEditor)this.epiceditor_container=document.createElement("div"),this.input.parentNode.insertBefore(this.epiceditor_container,this.input),this.input.style.display="none",a=c({},f.plugins.epiceditor,{container:this.epiceditor_container,clientSideStorage:!1}),this.epiceditor=new window.EpicEditor(a).load(), this.epiceditor.importFile(null,this.getValue()),this.epiceditor.on("update",function(){var a=b.epiceditor.exportFile();b.input.value=a,b.value=a,b.is_dirty=!0,b.onChange(!0)});else if(window.ace){var d=this.input_type;("cpp"===d||"c++"===d||"c"===d)&&(d="c_cpp"),this.ace_container=document.createElement("div"),this.ace_container.style.width="100%",this.ace_container.style.position="relative",this.ace_container.style.height="400px",this.input.parentNode.insertBefore(this.ace_container,this.input),this.input.style.display="none",this.ace_editor=window.ace.edit(this.ace_container),this.ace_editor.setValue(this.getValue()),f.plugins.ace.theme&&this.ace_editor.setTheme("ace/theme/"+f.plugins.ace.theme),d=window.ace.require("ace/mode/"+d),d&&this.ace_editor.getSession().setMode(new d.Mode),this.ace_editor.on("change",function(){var a=b.ace_editor.getValue();b.input.value=a,b.refreshValue(),b.is_dirty=!0,b.onChange(!0)})}b.theme.afterInputReady(b.input)},refreshValue:function(){this.value=this.input.value,"string"!=typeof this.value&&(this.value=""),this.serialized=this.value},destroy:function(){this.sceditor_instance?this.sceditor_instance.destroy():this.epiceditor?this.epiceditor.unload():this.ace_editor&&this.ace_editor.destroy(),this.template=null,this.input&&this.input.parentNode&&this.input.parentNode.removeChild(this.input),this.label&&this.label.parentNode&&this.label.parentNode.removeChild(this.label),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this._super()},sanitize:function(a){return a},onWatchedFieldChange:function(){var a;this.template&&(a=this.getWatchedFieldValues(),this.setValue(this.template(a),!1,!0)),this._super()},showValidationErrors:function(a){var b=this;if("always"===this.jsoneditor.options.show_errors);else if(!this.is_dirty&&this.previous_error_setting===this.jsoneditor.options.show_errors)return;this.previous_error_setting=this.jsoneditor.options.show_errors;var c=[];d(a,function(a,d){d.path===b.path&&c.push(d.message)}),c.length?this.theme.addInputError(this.input,c.join(". ")+"."):this.theme.removeInputError(this.input)}}),f.defaults.editors.number=f.defaults.editors.string.extend({sanitize:function(a){return(a+"").replace(/[^0-9\.\-eE]/g,"")},getNumColumns:function(){return 2},getValue:function(){return 1*this.value}}),f.defaults.editors.integer=f.defaults.editors.number.extend({sanitize:function(a){return a+="",a.replace(/[^0-9\-]/g,"")},getNumColumns:function(){return 2}}),f.defaults.editors.object=f.AbstractEditor.extend({getDefault:function(){return c({},this.schema["default"]||{})},getChildEditors:function(){return this.editors},register:function(){if(this._super(),this.editors)for(var a in this.editors)this.editors.hasOwnProperty(a)&&this.editors[a].register()},unregister:function(){if(this._super(),this.editors)for(var a in this.editors)this.editors.hasOwnProperty(a)&&this.editors[a].unregister()},getNumColumns:function(){return Math.max(Math.min(12,this.maxwidth),3)},enable:function(){if(this.editjson_button&&(this.editjson_button.disabled=!1),this.addproperty_button&&(this.addproperty_button.disabled=!1),this._super(),this.editors)for(var a in this.editors)this.editors.hasOwnProperty(a)&&this.editors[a].enable()},disable:function(){if(this.editjson_button&&(this.editjson_button.disabled=!0),this.addproperty_button&&(this.addproperty_button.disabled=!0),this.hideEditJSON(),this._super(),this.editors)for(var a in this.editors)this.editors.hasOwnProperty(a)&&this.editors[a].disable()},layoutEditors:function(){var a,b,c=this;if(this.row_container){this.property_order=Object.keys(this.editors),this.property_order=this.property_order.sort(function(a,b){var d=c.editors[a].schema.propertyOrder,e=c.editors[b].schema.propertyOrder;return"number"!=typeof d&&(d=1e3),"number"!=typeof e&&(e=1e3),d-e});var e;if("grid"===this.format){var f=[];for(d(this.property_order,function(a,b){var d=c.editors[b];if(!d.property_removed){for(var e=!1,g=d.options.hidden?0:d.options.grid_columns||d.getNumColumns(),h=d.options.hidden?0:d.container.offsetHeight,i=0;i<f.length;i++)f[i].width+g<=12&&(!h||.5*f[i].minh<h&&2*f[i].maxh>h)&&(e=i);e===!1&&(f.push({width:0,minh:999999,maxh:0,editors:[]}),e=f.length-1),f[e].editors.push({key:b,width:g,height:h}),f[e].width+=g,f[e].minh=Math.min(f[e].minh,h),f[e].maxh=Math.max(f[e].maxh,h)}}),a=0;a<f.length;a++)if(f[a].width<12){var g=!1,h=0;for(b=0;b<f[a].editors.length;b++)g===!1?g=b:f[a].editors[b].width>f[a].editors[g].width&&(g=b),f[a].editors[b].width*=12/f[a].width,f[a].editors[b].width=Math.floor(f[a].editors[b].width),h+=f[a].editors[b].width;12>h&&(f[a].editors[g].width+=12-h),f[a].width=12}if(this.layout===JSON.stringify(f))return!1;for(this.layout=JSON.stringify(f),e=document.createElement("div"),a=0;a<f.length;a++){var i=this.theme.getGridRow();for(e.appendChild(i),b=0;b<f[a].editors.length;b++){var j=f[a].editors[b].key,k=this.editors[j];k.options.hidden?k.container.style.display="none":this.theme.setGridColumnSize(k.container,f[a].editors[b].width),i.appendChild(k.container)}}}else e=document.createElement("div"),d(this.property_order,function(a,b){var d=c.editors[b];if(!d.property_removed){var f=c.theme.getGridRow();e.appendChild(f),d.options.hidden?d.container.style.display="none":c.theme.setGridColumnSize(d.container,12),f.appendChild(d.container)}});this.row_container.innerHTML="",this.row_container.appendChild(e)}},getPropertySchema:function(a){var b=this.schema.properties[a]||{};b=c({},b);var d=this.schema.properties[a]?!0:!1;if(this.schema.patternProperties)for(var e in this.schema.patternProperties)if(this.schema.patternProperties.hasOwnProperty(e)){var f=new RegExp(e);f.test(a)&&(b.allOf=b.allOf||[],b.allOf.push(this.schema.patternProperties[e]),d=!0)}return!d&&this.schema.additionalProperties&&"object"==typeof this.schema.additionalProperties&&(b=c({},this.schema.additionalProperties)),b},preBuild:function(){this._super(),this.editors={},this.cached_editors={};var a=this;if(this.format=this.options.layout||this.options.object_layout||this.schema.format||this.jsoneditor.options.object_layout||"normal",this.schema.properties=this.schema.properties||{},this.minwidth=0,this.maxwidth=0,this.options.table_row)d(this.schema.properties,function(b,c){var d=a.jsoneditor.getEditorClass(c);a.editors[b]=a.jsoneditor.createEditor(d,{jsoneditor:a.jsoneditor,schema:c,path:a.path+"."+b,parent:a,compact:!0,required:!0}),a.editors[b].preBuild();var e=a.editors[b].options.hidden?0:a.editors[b].options.grid_columns||a.editors[b].getNumColumns();a.minwidth+=e,a.maxwidth+=e}),this.no_link_holder=!0;else{if(this.options.table)throw"Not supported yet";this.defaultProperties=this.schema.defaultProperties||Object.keys(this.schema.properties),a.maxwidth+=1,d(this.defaultProperties,function(b,c){a.addObjectProperty(c,!0),a.editors[c]&&(a.minwidth=Math.max(a.minwidth,a.editors[c].options.grid_columns||a.editors[c].getNumColumns()),a.maxwidth+=a.editors[c].options.grid_columns||a.editors[c].getNumColumns())})}this.property_order=Object.keys(this.editors),this.property_order=this.property_order.sort(function(b,c){var d=a.editors[b].schema.propertyOrder,e=a.editors[c].schema.propertyOrder;return"number"!=typeof d&&(d=1e3),"number"!=typeof e&&(e=1e3),d-e})},build:function(){var a=this;if(this.options.table_row)this.editor_holder=this.container,d(this.editors,function(b,c){var d=a.theme.getTableCell();a.editor_holder.appendChild(d),c.setContainer(d),c.build(),c.postBuild(),a.editors[b].options.hidden&&(d.style.display="none"),a.editors[b].options.input_width&&(d.style.width=a.editors[b].options.input_width)});else{if(this.options.table)throw"Not supported yet";this.header=document.createElement("span"),this.header.textContent=this.getTitle(),this.title=this.theme.getHeader(this.header),this.container.appendChild(this.title),this.container.style.position="relative",this.editjson_holder=this.theme.getModal(),this.editjson_textarea=this.theme.getTextareaInput(),this.editjson_textarea.style.height="170px",this.editjson_textarea.style.width="300px",this.editjson_textarea.style.display="block",this.editjson_save=this.getButton("Save","save","Save"),this.editjson_save.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.saveJSON()}),this.editjson_cancel=this.getButton("Cancel","cancel","Cancel"),this.editjson_cancel.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.hideEditJSON()}),this.editjson_holder.appendChild(this.editjson_textarea),this.editjson_holder.appendChild(this.editjson_save),this.editjson_holder.appendChild(this.editjson_cancel),this.addproperty_holder=this.theme.getModal(),this.addproperty_list=document.createElement("div"),this.addproperty_list.style.width="295px",this.addproperty_list.style.maxHeight="160px",this.addproperty_list.style.padding="5px 0",this.addproperty_list.style.overflowY="auto",this.addproperty_list.style.overflowX="hidden",this.addproperty_list.style.paddingLeft="5px",this.addproperty_list.setAttribute("class","property-selector"),this.addproperty_add=this.getButton("add","add","add"),this.addproperty_input=this.theme.getFormInputField("text"),this.addproperty_input.setAttribute("placeholder","Property name..."),this.addproperty_input.style.width="220px",this.addproperty_input.style.marginBottom="0",this.addproperty_input.style.display="inline-block",this.addproperty_add.addEventListener("click",function(b){if(b.preventDefault(),b.stopPropagation(),a.addproperty_input.value){if(a.editors[a.addproperty_input.value])return void window.alert("there is already a property with that name");a.addObjectProperty(a.addproperty_input.value),a.editors[a.addproperty_input.value]&&a.editors[a.addproperty_input.value].disable(),a.onChange(!0)}}),this.addproperty_holder.appendChild(this.addproperty_list),this.addproperty_holder.appendChild(this.addproperty_input),this.addproperty_holder.appendChild(this.addproperty_add);var b=document.createElement("div");b.style.clear="both",this.addproperty_holder.appendChild(b),this.schema.description&&(this.description=this.theme.getDescription(this.schema.description),this.container.appendChild(this.description)),this.error_holder=document.createElement("div"),this.container.appendChild(this.error_holder),this.editor_holder=this.theme.getIndentedPanel(),this.container.appendChild(this.editor_holder),this.row_container=this.theme.getGridContainer(),this.editor_holder.appendChild(this.row_container),d(this.editors,function(b,c){var d=a.theme.getGridColumn();a.row_container.appendChild(d),c.setContainer(d),c.build(),c.postBuild()}),this.title_controls=this.theme.getHeaderButtonHolder(),this.editjson_controls=this.theme.getHeaderButtonHolder(),this.addproperty_controls=this.theme.getHeaderButtonHolder(),this.title.appendChild(this.title_controls),this.title.appendChild(this.editjson_controls),this.title.appendChild(this.addproperty_controls),this.collapsed=!1,this.toggle_button=this.getButton("","collapse","Collapse"),this.title_controls.appendChild(this.toggle_button),this.toggle_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.collapsed?(a.editor_holder.style.display="",a.collapsed=!1,a.setButtonText(a.toggle_button,"","collapse","Collapse")):(a.editor_holder.style.display="none",a.collapsed=!0,a.setButtonText(a.toggle_button,"","expand","Expand"))}),this.options.collapsed&&e(this.toggle_button,"click"),this.schema.options&&"undefined"!=typeof this.schema.options.disable_collapse?this.schema.options.disable_collapse&&(this.toggle_button.style.display="none"):this.jsoneditor.options.disable_collapse&&(this.toggle_button.style.display="none"),this.editjson_button=this.getButton("JSON","edit","Edit JSON"),this.editjson_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.toggleEditJSON()}),this.editjson_controls.appendChild(this.editjson_button),this.editjson_controls.appendChild(this.editjson_holder),this.schema.options&&"undefined"!=typeof this.schema.options.disable_edit_json?this.schema.options.disable_edit_json&&(this.editjson_button.style.display="none"):this.jsoneditor.options.disable_edit_json&&(this.editjson_button.style.display="none"),this.addproperty_button=this.getButton("Properties","edit","Object Properties"),this.addproperty_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation(),a.toggleAddProperty()}),this.addproperty_controls.appendChild(this.addproperty_button),this.addproperty_controls.appendChild(this.addproperty_holder),this.refreshAddProperties()}this.options.table_row?(this.editor_holder=this.container,d(this.property_order,function(b,c){a.editor_holder.appendChild(a.editors[c].container)})):(this.layoutEditors(),this.layoutEditors())},showEditJSON:function(){this.editjson_holder&&(this.hideAddProperty(),this.editjson_holder.style.left=this.editjson_button.offsetLeft+"px",this.editjson_holder.style.top=this.editjson_button.offsetTop+this.editjson_button.offsetHeight+"px",this.editjson_textarea.value=JSON.stringify(this.getValue(),null,2),this.disable(),this.editjson_holder.style.display="",this.editjson_button.disabled=!1,this.editing_json=!0)},hideEditJSON:function(){this.editjson_holder&&this.editing_json&&(this.editjson_holder.style.display="none",this.enable(),this.editing_json=!1)},saveJSON:function(){if(this.editjson_holder)try{var a=JSON.parse(this.editjson_textarea.value);this.setValue(a),this.hideEditJSON()}catch(b){throw window.alert("invalid JSON"),b}},toggleEditJSON:function(){this.editing_json?this.hideEditJSON():this.showEditJSON()},insertPropertyControlUsingPropertyOrder:function(a,b,c){var d;this.schema.properties[a]&&(d=this.schema.properties[a].propertyOrder),"number"!=typeof d&&(d=1e3),b.propertyOrder=d;for(var e=0;e<c.childNodes.length;e++){var f=c.childNodes[e];if(b.propertyOrder<f.propertyOrder){this.addproperty_list.insertBefore(b,f),b=null;break}}b&&this.addproperty_list.appendChild(b)},addPropertyCheckbox:function(a){var b,c,d,e,f=this;return b=f.theme.getCheckbox(),b.style.width="auto",d=this.schema.properties[a]&&this.schema.properties[a].title?this.schema.properties[a].title:a,c=f.theme.getCheckboxLabel(d),e=f.theme.getFormControl(c,b),e.style.paddingBottom=e.style.marginBottom=e.style.paddingTop=e.style.marginTop=0,e.style.height="auto",this.insertPropertyControlUsingPropertyOrder(a,e,this.addproperty_list),b.checked=a in this.editors,b.addEventListener("change",function(){b.checked?f.addObjectProperty(a):f.removeObjectProperty(a),f.onChange(!0)}),f.addproperty_checkboxes[a]=b,b},showAddProperty:function(){this.addproperty_holder&&(this.hideEditJSON(),this.addproperty_holder.style.left=this.addproperty_button.offsetLeft+"px",this.addproperty_holder.style.top=this.addproperty_button.offsetTop+this.addproperty_button.offsetHeight+"px",this.disable(),this.adding_property=!0,this.addproperty_button.disabled=!1,this.addproperty_holder.style.display="",this.refreshAddProperties())},hideAddProperty:function(){this.addproperty_holder&&this.adding_property&&(this.addproperty_holder.style.display="none",this.enable(),this.adding_property=!1)},toggleAddProperty:function(){this.adding_property?this.hideAddProperty():this.showAddProperty()},removeObjectProperty:function(a){this.editors[a]&&(this.editors[a].unregister(),delete this.editors[a],this.refreshValue(),this.layoutEditors())},addObjectProperty:function(a,b){var c=this;if(!this.editors[a]){if(this.cached_editors[a]){if(this.editors[a]=this.cached_editors[a],b)return;this.editors[a].register()}else{if(!(this.canHaveAdditionalProperties()||this.schema.properties&&this.schema.properties[a]))return;var d=c.getPropertySchema(a),e=c.jsoneditor.getEditorClass(d);if(c.editors[a]=c.jsoneditor.createEditor(e,{jsoneditor:c.jsoneditor,schema:d,path:c.path+"."+a,parent:c}),c.editors[a].preBuild(),!b){var f=c.theme.getChildEditorHolder();c.editor_holder.appendChild(f),c.editors[a].setContainer(f),c.editors[a].build(),c.editors[a].postBuild()}c.cached_editors[a]=c.editors[a]}b||(c.refreshValue(),c.layoutEditors())}},onChildEditorChange:function(a){this.refreshValue(),this._super(a)},canHaveAdditionalProperties:function(){return"boolean"==typeof this.schema.additionalProperties?this.schema.additionalProperties:!this.jsoneditor.options.no_additional_properties},destroy:function(){d(this.cached_editors,function(a,b){b.destroy()}),this.editor_holder&&(this.editor_holder.innerHTML=""),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.error_holder&&this.error_holder.parentNode&&this.error_holder.parentNode.removeChild(this.error_holder),this.editors=null,this.cached_editors=null,this.editor_holder&&this.editor_holder.parentNode&&this.editor_holder.parentNode.removeChild(this.editor_holder),this.editor_holder=null,this._super()},getValue:function(){var a=this._super();if(this.jsoneditor.options.remove_empty_properties||this.options.remove_empty_properties)for(var b in a)a.hasOwnProperty(b)&&(a[b]||delete a[b]);return a},refreshValue:function(){this.value={};for(var a in this.editors)this.editors.hasOwnProperty(a)&&(this.value[a]=this.editors[a].getValue());this.adding_property&&this.refreshAddProperties()},refreshAddProperties:function(){if(this.options.disable_properties||this.options.disable_properties!==!1&&this.jsoneditor.options.disable_properties)return void(this.addproperty_controls.style.display="none");var a,b=!1,c=!1,d=0,e=!1;for(a in this.editors)this.editors.hasOwnProperty(a)&&d++;b=this.canHaveAdditionalProperties()&&!("undefined"!=typeof this.schema.maxProperties&&d>=this.schema.maxProperties),this.addproperty_checkboxes&&(this.addproperty_list.innerHTML=""),this.addproperty_checkboxes={};for(a in this.cached_editors)this.cached_editors.hasOwnProperty(a)&&(this.addPropertyCheckbox(a),this.isRequired(this.cached_editors[a])&&a in this.editors&&(this.addproperty_checkboxes[a].disabled=!0),"undefined"!=typeof this.schema.minProperties&&d<=this.schema.minProperties?(this.addproperty_checkboxes[a].disabled=this.addproperty_checkboxes[a].checked,this.addproperty_checkboxes[a].checked||(e=!0)):a in this.editors?(e=!0,c=!0):b||this.schema.properties.hasOwnProperty(a)?(this.addproperty_checkboxes[a].disabled=!1,e=!0):this.addproperty_checkboxes[a].disabled=!0);this.canHaveAdditionalProperties()&&(e=!0);for(a in this.schema.properties)this.schema.properties.hasOwnProperty(a)&&(this.cached_editors[a]||(e=!0,this.addPropertyCheckbox(a)));e?this.canHaveAdditionalProperties()?b?this.addproperty_add.disabled=!1:this.addproperty_add.disabled=!0:(this.addproperty_add.style.display="none",this.addproperty_input.style.display="none"):(this.hideAddProperty(),this.addproperty_controls.style.display="none")},isRequired:function(a){return"boolean"==typeof a.schema.required?a.schema.required:Array.isArray(this.schema.required)?this.schema.required.indexOf(a.key)>-1:this.jsoneditor.options.required_by_default?!0:!1},setValue:function(a,b){var c=this;a=a||{},("object"!=typeof a||Array.isArray(a))&&(a={}),d(this.cached_editors,function(d,e){"undefined"!=typeof a[d]?(c.addObjectProperty(d),e.setValue(a[d],b)):b||c.isRequired(e)?e.setValue(e.getDefault(),b):c.removeObjectProperty(d)}),d(a,function(a,d){c.cached_editors[a]||(c.addObjectProperty(a),c.editors[a]&&c.editors[a].setValue(d,b))}),this.refreshValue(),this.layoutEditors(),this.onChange()},showValidationErrors:function(a){var b=this,c=[],e=[];if(d(a,function(a,d){d.path===b.path?c.push(d):e.push(d)}),this.error_holder)if(c.length){this.error_holder.innerHTML="",this.error_holder.style.display="",d(c,function(a,c){b.error_holder.appendChild(b.theme.getErrorMessage(c.message))})}else this.error_holder.style.display="none";this.options.table_row&&(c.length?this.theme.addTableRowError(this.container):this.theme.removeTableRowError(this.container)),d(this.editors,function(a,b){b.showValidationErrors(e)})}}),f.defaults.editors.array=f.AbstractEditor.extend({getDefault:function(){return this.schema["default"]||[]},register:function(){if(this._super(),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].register()},unregister:function(){if(this._super(),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].unregister()},getNumColumns:function(){var a=this.getItemInfo(0);return this.tabs_holder?Math.max(Math.min(12,a.width+2),4):a.width},enable:function(){if(this.add_row_button&&(this.add_row_button.disabled=!1),this.remove_all_rows_button&&(this.remove_all_rows_button.disabled=!1),this.delete_last_row_button&&(this.delete_last_row_button.disabled=!1),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].enable(),this.rows[a].moveup_button&&(this.rows[a].moveup_button.disabled=!1),this.rows[a].movedown_button&&(this.rows[a].movedown_button.disabled=!1),this.rows[a].delete_button&&(this.rows[a].delete_button.disabled=!1);this._super()},disable:function(){if(this.add_row_button&&(this.add_row_button.disabled=!0),this.remove_all_rows_button&&(this.remove_all_rows_button.disabled=!0),this.delete_last_row_button&&(this.delete_last_row_button.disabled=!0),this.rows)for(var a=0;a<this.rows.length;a++)this.rows[a].disable(),this.rows[a].moveup_button&&(this.rows[a].moveup_button.disabled=!0),this.rows[a].movedown_button&&(this.rows[a].movedown_button.disabled=!0),this.rows[a].delete_button&&(this.rows[a].delete_button.disabled=!0);this._super()},preBuild:function(){this._super(),this.rows=[],this.row_cache=[],this.hide_delete_buttons=this.options.disable_array_delete||this.jsoneditor.options.disable_array_delete,this.hide_move_buttons=this.options.disable_array_reorder||this.jsoneditor.options.disable_array_reorder,this.hide_add_button=this.options.disable_array_add||this.jsoneditor.options.disable_array_add},build:function(){this.options.compact?(this.panel=this.theme.getIndentedPanel(),this.container.appendChild(this.panel),this.controls=this.theme.getButtonHolder(),this.panel.appendChild(this.controls),this.row_holder=document.createElement("div"),this.panel.appendChild(this.row_holder)):(this.header=document.createElement("span"),this.header.textContent=this.getTitle(),this.title=this.theme.getHeader(this.header),this.container.appendChild(this.title),this.title_controls=this.theme.getHeaderButtonHolder(),this.title.appendChild(this.title_controls),this.schema.description&&(this.description=this.theme.getDescription(this.schema.description),this.container.appendChild(this.description)),this.error_holder=document.createElement("div"),this.container.appendChild(this.error_holder),"tabs"===this.schema.format?(this.controls=this.theme.getHeaderButtonHolder(),this.title.appendChild(this.controls),this.tabs_holder=this.theme.getTabHolder(),this.container.appendChild(this.tabs_holder),this.row_holder=this.theme.getTabContentHolder(this.tabs_holder),this.active_tab=null):(this.panel=this.theme.getIndentedPanel(),this.container.appendChild(this.panel),this.row_holder=document.createElement("div"),this.panel.appendChild(this.row_holder),this.controls=this.theme.getButtonHolder(),this.panel.appendChild(this.controls))),this.addControls()},onChildEditorChange:function(a){this.refreshValue(),this.refreshTabs(!0),this._super(a)},getItemTitle:function(){if(!this.item_title)if(this.schema.items&&!Array.isArray(this.schema.items)){var a=this.jsoneditor.expandRefs(this.schema.items);this.item_title=a.title||"item"}else this.item_title="item";return this.item_title},getItemSchema:function(a){return Array.isArray(this.schema.items)?a>=this.schema.items.length?this.schema.additionalItems===!0?{}:this.schema.additionalItems?c({},this.schema.additionalItems):void 0:c({},this.schema.items[a]):this.schema.items?c({},this.schema.items):{}},getItemInfo:function(a){var b=this.getItemSchema(a);this.item_info=this.item_info||{};var c=JSON.stringify(b);return"undefined"!=typeof this.item_info[c]?this.item_info[c]:(b=this.jsoneditor.expandRefs(b),this.item_info[c]={title:b.title||"item","default":b["default"],width:12,child_editors:b.properties||b.items},this.item_info[c])},getElementEditor:function(a){var b=this.getItemInfo(a),c=this.getItemSchema(a);c=this.jsoneditor.expandRefs(c),c.title=b.title+" "+(a+1);var d,e=this.jsoneditor.getEditorClass(c);d=this.tabs_holder?this.theme.getTabContent():b.child_editors?this.theme.getChildEditorHolder():this.theme.getIndentedPanel(),this.row_holder.appendChild(d);var f=this.jsoneditor.createEditor(e,{jsoneditor:this.jsoneditor,schema:c,container:d,path:this.path+"."+a,parent:this,required:!0});return f.preBuild(),f.build(),f.postBuild(),f.title_controls||(f.array_controls=this.theme.getButtonHolder(),d.appendChild(f.array_controls)),f},destroy:function(){this.empty(!0),this.title&&this.title.parentNode&&this.title.parentNode.removeChild(this.title),this.description&&this.description.parentNode&&this.description.parentNode.removeChild(this.description),this.row_holder&&this.row_holder.parentNode&&this.row_holder.parentNode.removeChild(this.row_holder),this.controls&&this.controls.parentNode&&this.controls.parentNode.removeChild(this.controls),this.panel&&this.panel.parentNode&&this.panel.parentNode.removeChild(this.panel),this.rows=this.row_cache=this.title=this.description=this.row_holder=this.panel=this.controls=null,this._super()},empty:function(a){if(this.rows){var b=this;d(this.rows,function(c,d){a&&(d.tab&&d.tab.parentNode&&d.tab.parentNode.removeChild(d.tab),b.destroyRow(d,!0),b.row_cache[c]=null),b.rows[c]=null}),b.rows=[],a&&(b.row_cache=[])}},destroyRow:function(a,b){var c=a.container;b?(a.destroy(),c.parentNode&&c.parentNode.removeChild(c),a.tab&&a.tab.parentNode&&a.tab.parentNode.removeChild(a.tab)):(a.tab&&(a.tab.style.display="none"),c.style.display="none",a.unregister())},getMax:function(){return Array.isArray(this.schema.items)&&this.schema.additionalItems===!1?Math.min(this.schema.items.length,this.schema.maxItems||1/0):this.schema.maxItems||1/0},refreshTabs:function(a){var b=this;d(this.rows,function(c,d){d.tab&&(a?d.tab_text.textContent=d.getHeaderText():d.tab===b.active_tab?(b.theme.markTabActive(d.tab),d.container.style.display=""):(b.theme.markTabInactive(d.tab),d.container.style.display="none"))})},setValue:function(a,b){a=a||[],Array.isArray(a)||(a=[a]);var c=JSON.stringify(a);if(c!==this.serialized){if(this.schema.minItems)for(;a.length<this.schema.minItems;)a.push(this.getItemInfo(a.length)["default"]);this.getMax()&&a.length>this.getMax()&&(a=a.slice(0,this.getMax()));var e=this;d(a,function(a,c){e.rows[a]?e.rows[a].setValue(c,b):e.row_cache[a]?(e.rows[a]=e.row_cache[a],e.rows[a].setValue(c,b),e.rows[a].container.style.display="",e.rows[a].tab&&(e.rows[a].tab.style.display=""),e.rows[a].register()):e.addRow(c,b)});for(var f=a.length;f<e.rows.length;f++)e.destroyRow(e.rows[f]),e.rows[f]=null;e.rows=e.rows.slice(0,a.length);var g=null;d(e.rows,function(a,b){return b.tab===e.active_tab?(g=b.tab,!1):void 0}),!g&&e.rows.length&&(g=e.rows[0].tab),e.active_tab=g,e.refreshValue(b),e.refreshTabs(!0),e.refreshTabs(),e.onChange()}},refreshValue:function(a){var b=this,c=this.value?this.value.length:0;if(this.value=[],d(this.rows,function(a,c){b.value[a]=c.getValue()}),c!==this.value.length||a){var e=this.schema.minItems&&this.schema.minItems>=this.rows.length;d(this.rows,function(a,c){c.movedown_button&&(a===b.rows.length-1?c.movedown_button.style.display="none":c.movedown_button.style.display=""),c.delete_button&&(e?c.delete_button.style.display="none":c.delete_button.style.display=""),b.value[a]=c.getValue()});var f=!1;this.value.length?1===this.value.length?(this.remove_all_rows_button.style.display="none",e||this.hide_delete_buttons?this.delete_last_row_button.style.display="none":(this.delete_last_row_button.style.display="",f=!0)):e||this.hide_delete_buttons?(this.delete_last_row_button.style.display="none",this.remove_all_rows_button.style.display="none"):(this.delete_last_row_button.style.display="",this.remove_all_rows_button.style.display="",f=!0):(this.delete_last_row_button.style.display="none",this.remove_all_rows_button.style.display="none"),this.getMax()&&this.getMax()<=this.rows.length||this.hide_add_button?this.add_row_button.style.display="none":(this.add_row_button.style.display="",f=!0),!this.collapsed&&f?this.controls.style.display="inline-block":this.controls.style.display="none"}},addRow:function(a,b){var c=this,e=this.rows.length;c.rows[e]=this.getElementEditor(e),c.row_cache[e]=c.rows[e],c.tabs_holder&&(c.rows[e].tab_text=document.createElement("span"),c.rows[e].tab_text.textContent=c.rows[e].getHeaderText(),c.rows[e].tab=c.theme.getTab(c.rows[e].tab_text),c.rows[e].tab.addEventListener("click",function(a){c.active_tab=c.rows[e].tab,c.refreshTabs(),a.preventDefault(),a.stopPropagation()}),c.theme.addTab(c.tabs_holder,c.rows[e].tab));var f=c.rows[e].title_controls||c.rows[e].array_controls;c.hide_delete_buttons||(c.rows[e].delete_button=this.getButton(c.getItemTitle(),"delete","Excluir "+c.getItemTitle()),c.rows[e].delete_button.className+=" delete",c.rows[e].delete_button.setAttribute("data-i",e),c.rows[e].delete_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var b=1*this.getAttribute("data-i"),e=c.getValue(),f=[],g=null;d(e,function(a,d){return a===b?void(c.rows[a].tab===c.active_tab&&(c.rows[a+1]?g=c.rows[a].tab:a&&(g=c.rows[a-1].tab))):void f.push(d)}),c.setValue(f),g&&(c.active_tab=g,c.refreshTabs()),c.onChange(!0)}),f&&f.appendChild(c.rows[e].delete_button)),e&&!c.hide_move_buttons&&(c.rows[e].moveup_button=this.getButton("","moveup","Mover para cima"),c.rows[e].moveup_button.className+=" moveup",c.rows[e].moveup_button.setAttribute("data-i",e),c.rows[e].moveup_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var b=1*this.getAttribute("data-i");if(!(0>=b)){var d=c.getValue(),e=d[b-1];d[b-1]=d[b],d[b]=e,c.setValue(d),c.active_tab=c.rows[b-1].tab,c.refreshTabs(),c.onChange(!0)}}),f&&f.appendChild(c.rows[e].moveup_button)),c.hide_move_buttons||(c.rows[e].movedown_button=this.getButton("","movedown","Mover para baixo"),c.rows[e].movedown_button.className+=" movedown",c.rows[e].movedown_button.setAttribute("data-i",e),c.rows[e].movedown_button.addEventListener("click",function(a){a.preventDefault(),a.stopPropagation();var b=1*this.getAttribute("data-i"),d=c.getValue();if(!(b>=d.length-1)){var e=d[b+1];d[b+1]=d[b],d[b]=e,c.setValue(d),c.active_tab=c.rows[b+1].tab,c.refreshTabs(),c.onChange(!0)}}),f&&f.appendChild(c.rows[e].movedown_button)),a&&c.rows[e].setValue(a,b),c.refreshTabs()},addControls:function(){var a=this;this.collapsed=!1,this.toggle_button=this.getButton("","collapse","Collapse"),this.title_controls.appendChild(this.toggle_button);var b=a.row_holder.style.display,c=a.controls.style.display;this.toggle_button.addEventListener("click",function(d){d.preventDefault(),d.stopPropagation(),a.collapsed?(a.collapsed=!1,a.panel&&(a.panel.style.display=""),a.row_holder.style.display=b,a.tabs_holder&&(a.tabs_holder.style.display=""),a.controls.style.display=c,a.setButtonText(this,"","collapse","Collapse")):(a.collapsed=!0,a.row_holder.style.display="none",a.tabs_holder&&(a.tabs_holder.style.display="none"),a.controls.style.display="none",a.panel&&(a.panel.style.display="none"),a.setButtonText(this,"","expand","Expand"))}),this.options.collapsed&&e(this.toggle_button,"click"),this.schema.options&&"undefined"!=typeof this.schema.options.disable_collapse?this.schema.options.disable_collapse&&(this.toggle_button.style.display="none"):this.jsoneditor.options.disable_collapse&&(this.toggle_button.style.display="none"),this.add_row_button=this.getButton(this.getItemTitle(),"add","Add "+this.getItemTitle()),this.add_row_button.addEventListener("click",function(b){b.preventDefault(),b.stopPropagation();var c=a.rows.length;a.row_cache[c]?(a.rows[c]=a.row_cache[c],a.rows[c].setValue(a.rows[c].getDefault()),a.rows[c].container.style.display="",a.rows[c].tab&&(a.rows[c].tab.style.display=""),a.rows[c].register()):a.addRow(),a.active_tab=a.rows[c].tab,a.refreshTabs(),
peerconnection.go
// +build !js // Package webrtc implements the WebRTC 1.0 as defined in W3C WebRTC specification document. package webrtc import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" mathRand "math/rand" "regexp" "strconv" "strings" "sync" "time" "github.com/pion/logging" "github.com/pion/rtcp" "github.com/pion/sdp/v2" "github.com/pion/webrtc/v2/internal/util" "github.com/pion/webrtc/v2/pkg/rtcerr" ) // PeerConnection represents a WebRTC connection that establishes a // peer-to-peer communications with another PeerConnection instance in a // browser, or to another endpoint implementing the required protocols. type PeerConnection struct { statsID string mu sync.RWMutex configuration Configuration currentLocalDescription *SessionDescription pendingLocalDescription *SessionDescription currentRemoteDescription *SessionDescription pendingRemoteDescription *SessionDescription signalingState SignalingState iceConnectionState ICEConnectionState connectionState PeerConnectionState idpLoginURL *string isClosed bool negotiationNeeded bool lastOffer string lastAnswer string rtpTransceivers []*RTPTransceiver // DataChannels dataChannels map[uint16]*DataChannel dataChannelsOpened uint32 dataChannelsRequested uint32 dataChannelsAccepted uint32 onSignalingStateChangeHandler func(SignalingState) onICEConnectionStateChangeHandler func(ICEConnectionState) onTrackHandler func(*Track, *RTPReceiver) onDataChannelHandler func(*DataChannel) iceGatherer *ICEGatherer iceTransport *ICETransport dtlsTransport *DTLSTransport sctpTransport *SCTPTransport // A reference to the associated API state used by this connection api *API log logging.LeveledLogger } // NewPeerConnection creates a peerconnection with the default // codecs. See API.NewRTCPeerConnection for details. func NewPeerConnection(configuration Configuration) (*PeerConnection, error) { m := MediaEngine{} m.RegisterDefaultCodecs() api := NewAPI(WithMediaEngine(m)) return api.NewPeerConnection(configuration) } // NewPeerConnection creates a new PeerConnection with the provided configuration against the received API object func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection, error) { // https://w3c.github.io/webrtc-pc/#constructor (Step #2) // Some variables defined explicitly despite their implicit zero values to // allow better readability to understand what is happening. pc := &PeerConnection{ statsID: fmt.Sprintf("PeerConnection-%d", time.Now().UnixNano()), configuration: Configuration{ ICEServers: []ICEServer{}, ICETransportPolicy: ICETransportPolicyAll, BundlePolicy: BundlePolicyBalanced, RTCPMuxPolicy: RTCPMuxPolicyRequire, Certificates: []Certificate{}, ICECandidatePoolSize: 0, }, isClosed: false, negotiationNeeded: false, lastOffer: "", lastAnswer: "", signalingState: SignalingStateStable, iceConnectionState: ICEConnectionStateNew, connectionState: PeerConnectionStateNew, dataChannels: make(map[uint16]*DataChannel), api: api, log: api.settingEngine.LoggerFactory.NewLogger("pc"), } var err error if err = pc.initConfiguration(configuration); err != nil { return nil, err } pc.iceGatherer, err = pc.createICEGatherer() if err != nil { return nil, err } if !pc.iceGatherer.agentIsTrickle { if err = pc.iceGatherer.Gather(); err != nil { return nil, err } } // Create the ice transport iceTransport := pc.createICETransport() pc.iceTransport = iceTransport // Create the DTLS transport dtlsTransport, err := pc.api.NewDTLSTransport(pc.iceTransport, pc.configuration.Certificates) if err != nil { return nil, err } pc.dtlsTransport = dtlsTransport return pc, nil } // initConfiguration defines validation of the specified Configuration and // its assignment to the internal configuration variable. This function differs // from its SetConfiguration counterpart because most of the checks do not // include verification statements related to the existing state. Thus the // function describes only minor verification of some the struct variables. func (pc *PeerConnection) initConfiguration(configuration Configuration) error { if configuration.PeerIdentity != "" { pc.configuration.PeerIdentity = configuration.PeerIdentity } // https://www.w3.org/TR/webrtc/#constructor (step #3) if len(configuration.Certificates) > 0 { now := time.Now() for _, x509Cert := range configuration.Certificates { if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) { return &rtcerr.InvalidAccessError{Err: ErrCertificateExpired} } pc.configuration.Certificates = append(pc.configuration.Certificates, x509Cert) } } else { sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return &rtcerr.UnknownError{Err: err} } certificate, err := GenerateCertificate(sk) if err != nil { return err } pc.configuration.Certificates = []Certificate{*certificate} } if configuration.BundlePolicy != BundlePolicy(Unknown) { pc.configuration.BundlePolicy = configuration.BundlePolicy } if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) { pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy } if configuration.ICECandidatePoolSize != 0 { pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize } if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) { pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy } if configuration.SDPSemantics != SDPSemantics(Unknown) { pc.configuration.SDPSemantics = configuration.SDPSemantics } if len(configuration.ICEServers) > 0 { for _, server := range configuration.ICEServers { if err := server.validate(); err != nil { return err } } pc.configuration.ICEServers = configuration.ICEServers } return nil } // OnSignalingStateChange sets an event handler which is invoked when the // peer connection's signaling state changes func (pc *PeerConnection) OnSignalingStateChange(f func(SignalingState)) { pc.mu.Lock() defer pc.mu.Unlock() pc.onSignalingStateChangeHandler = f } func (pc *PeerConnection) onSignalingStateChange(newState SignalingState) (done chan struct{}) { pc.mu.RLock() hdlr := pc.onSignalingStateChangeHandler pc.mu.RUnlock() pc.log.Infof("signaling state changed to %s", newState) done = make(chan struct{}) if hdlr == nil { close(done) return } go func() { hdlr(newState) close(done) }() return } // OnDataChannel sets an event handler which is invoked when a data // channel message arrives from a remote peer. func (pc *PeerConnection) OnDataChannel(f func(*DataChannel)) { pc.mu.Lock() defer pc.mu.Unlock() pc.onDataChannelHandler = f } // OnICECandidate sets an event handler which is invoked when a new ICE // candidate is found. func (pc *PeerConnection) OnICECandidate(f func(*ICECandidate)) { pc.iceGatherer.OnLocalCandidate(f) } // OnICEGatheringStateChange sets an event handler which is invoked when the // ICE candidate gathering state has changed. func (pc *PeerConnection) OnICEGatheringStateChange(f func(ICEGathererState)) { pc.iceGatherer.OnStateChange(f) } // OnTrack sets an event handler which is called when remote track // arrives from a remote peer. func (pc *PeerConnection) OnTrack(f func(*Track, *RTPReceiver)) { pc.mu.Lock() defer pc.mu.Unlock() pc.onTrackHandler = f } func (pc *PeerConnection) onTrack(t *Track, r *RTPReceiver) (done chan struct{}) { pc.mu.RLock() hdlr := pc.onTrackHandler pc.mu.RUnlock() pc.log.Debugf("got new track: %+v", t) done = make(chan struct{}) if hdlr == nil || t == nil { close(done) return } go func() { hdlr(t, r) close(done) }() return } // OnICEConnectionStateChange sets an event handler which is called // when an ICE connection state is changed. func (pc *PeerConnection) OnICEConnectionStateChange(f func(ICEConnectionState)) { pc.mu.Lock() defer pc.mu.Unlock() pc.onICEConnectionStateChangeHandler = f } func (pc *PeerConnection) onICEConnectionStateChange(cs ICEConnectionState) (done chan struct{}) { pc.mu.RLock() hdlr := pc.onICEConnectionStateChangeHandler pc.mu.RUnlock() pc.log.Infof("ICE connection state changed: %s", cs) done = make(chan struct{}) if hdlr == nil { close(done) return } go func() { hdlr(cs) close(done) }() return } // SetConfiguration updates the configuration of this PeerConnection object. func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2) if pc.isClosed { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #3) if configuration.PeerIdentity != "" { if configuration.PeerIdentity != pc.configuration.PeerIdentity { return &rtcerr.InvalidModificationError{Err: ErrModifyingPeerIdentity} } pc.configuration.PeerIdentity = configuration.PeerIdentity } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #4) if len(configuration.Certificates) > 0 { if len(configuration.Certificates) != len(pc.configuration.Certificates) { return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates} } for i, certificate := range configuration.Certificates { if !pc.configuration.Certificates[i].Equals(certificate) { return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates} } } pc.configuration.Certificates = configuration.Certificates } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #5) if configuration.BundlePolicy != BundlePolicy(Unknown) { if configuration.BundlePolicy != pc.configuration.BundlePolicy { return &rtcerr.InvalidModificationError{Err: ErrModifyingBundlePolicy} } pc.configuration.BundlePolicy = configuration.BundlePolicy } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #6) if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) { if configuration.RTCPMuxPolicy != pc.configuration.RTCPMuxPolicy { return &rtcerr.InvalidModificationError{Err: ErrModifyingRTCPMuxPolicy} } pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #7) if configuration.ICECandidatePoolSize != 0 { if pc.configuration.ICECandidatePoolSize != configuration.ICECandidatePoolSize && pc.LocalDescription() != nil { return &rtcerr.InvalidModificationError{Err: ErrModifyingICECandidatePoolSize} } pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #8) if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) { pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy } // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11) if len(configuration.ICEServers) > 0 { // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3) for _, server := range configuration.ICEServers { if err := server.validate(); err != nil { return err } } pc.configuration.ICEServers = configuration.ICEServers } return nil } // GetConfiguration returns a Configuration object representing the current // configuration of this PeerConnection object. The returned object is a // copy and direct mutation on it will not take affect until SetConfiguration // has been called with Configuration passed as its only argument. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration func (pc *PeerConnection) GetConfiguration() Configuration { return pc.configuration } func (pc *PeerConnection) getStatsID() string { pc.mu.RLock() defer pc.mu.RUnlock() return pc.statsID } // CreateOffer starts the PeerConnection and generates the localDescription func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error) { useIdentity := pc.idpLoginURL != nil switch { case options != nil: return SessionDescription{}, fmt.Errorf("TODO handle options") case useIdentity: return SessionDescription{}, fmt.Errorf("TODO handle identity provider") case pc.isClosed: return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } d := sdp.NewJSEPSessionDescription(useIdentity) if err := pc.addFingerprint(d); err != nil { return SessionDescription{}, err } iceParams, err := pc.iceGatherer.GetLocalParameters() if err != nil
candidates, err := pc.iceGatherer.GetLocalCandidates() if err != nil { return SessionDescription{}, err } bundleValue := "BUNDLE" bundleCount := 0 appendBundle := func(midValue string) { bundleValue += " " + midValue bundleCount++ } if pc.configuration.SDPSemantics == SDPSemanticsPlanB { video := make([]*RTPTransceiver, 0) audio := make([]*RTPTransceiver, 0) for _, t := range pc.GetTransceivers() { switch t.kind { case RTPCodecTypeVideo: video = append(video, t) case RTPCodecTypeAudio: audio = append(audio, t) } } if len(video) > 0 { if err = pc.addTransceiverSDP(d, "video", iceParams, candidates, sdp.ConnectionRoleActpass, video...); err != nil { return SessionDescription{}, err } appendBundle("video") } if len(audio) > 0 { if err = pc.addTransceiverSDP(d, "audio", iceParams, candidates, sdp.ConnectionRoleActpass, audio...); err != nil { return SessionDescription{}, err } appendBundle("audio") } } else { for _, t := range pc.GetTransceivers() { midValue := strconv.Itoa(bundleCount) if err = pc.addTransceiverSDP(d, midValue, iceParams, candidates, sdp.ConnectionRoleActpass, t); err != nil { return SessionDescription{}, err } appendBundle(midValue) } } midValue := strconv.Itoa(bundleCount) if pc.configuration.SDPSemantics == SDPSemanticsPlanB { midValue = "data" } pc.addDataMediaSection(d, midValue, iceParams, candidates, sdp.ConnectionRoleActpass) appendBundle(midValue) d = d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue) for _, m := range d.MediaDescriptions { m.WithPropertyAttribute("setup:actpass") } sdpBytes, err := d.Marshal() if err != nil { return SessionDescription{}, err } desc := SessionDescription{ Type: SDPTypeOffer, SDP: string(sdpBytes), parsed: d, } pc.lastOffer = desc.SDP return desc, nil } func (pc *PeerConnection) createICEGatherer() (*ICEGatherer, error) { g, err := pc.api.NewICEGatherer(ICEGatherOptions{ ICEServers: pc.configuration.ICEServers, ICEGatherPolicy: pc.configuration.ICETransportPolicy, }) if err != nil { return nil, err } return g, nil } func (pc *PeerConnection) createICETransport() *ICETransport { t := pc.api.NewICETransport(pc.iceGatherer) t.OnConnectionStateChange(func(state ICETransportState) { var cs ICEConnectionState switch state { case ICETransportStateNew: cs = ICEConnectionStateNew case ICETransportStateChecking: cs = ICEConnectionStateChecking case ICETransportStateConnected: cs = ICEConnectionStateConnected case ICETransportStateCompleted: cs = ICEConnectionStateCompleted case ICETransportStateFailed: cs = ICEConnectionStateFailed case ICETransportStateDisconnected: cs = ICEConnectionStateDisconnected case ICETransportStateClosed: cs = ICEConnectionStateClosed default: pc.log.Warnf("OnConnectionStateChange: unhandled ICE state: %s", state) return } pc.iceStateChange(cs) }) return t } func (pc *PeerConnection) getPeerDirection(media *sdp.MediaDescription) RTPTransceiverDirection { for _, a := range media.Attributes { if direction := NewRTPTransceiverDirection(a.Key); direction != RTPTransceiverDirection(Unknown) { return direction } } return RTPTransceiverDirection(Unknown) } func (pc *PeerConnection) getMidValue(media *sdp.MediaDescription) string { for _, attr := range media.Attributes { if attr.Key == "mid" { return attr.Value } } return "" } // Given a direction+type pluck a transceiver from the passed list // if no entry satisfies the requested type+direction return a inactive Transceiver func satisfyTypeAndDirection(remoteKind RTPCodecType, remoteDirection RTPTransceiverDirection, localTransceivers []*RTPTransceiver) (*RTPTransceiver, []*RTPTransceiver) { // Get direction order from most preferred to least getPreferredDirections := func() []RTPTransceiverDirection { switch remoteDirection { case RTPTransceiverDirectionSendrecv: return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv} case RTPTransceiverDirectionSendonly: return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv} case RTPTransceiverDirectionRecvonly: return []RTPTransceiverDirection{RTPTransceiverDirectionSendonly, RTPTransceiverDirectionSendrecv} } return []RTPTransceiverDirection{} } for _, possibleDirection := range getPreferredDirections() { for i := range localTransceivers { t := localTransceivers[i] if t.kind != remoteKind || possibleDirection != t.Direction { continue } return t, append(localTransceivers[:i], localTransceivers[i+1:]...) } } return &RTPTransceiver{ kind: remoteKind, Direction: RTPTransceiverDirectionInactive, }, localTransceivers } func (pc *PeerConnection) addAnswerMediaTransceivers(d *sdp.SessionDescription) (*sdp.SessionDescription, error) { iceParams, err := pc.iceGatherer.GetLocalParameters() if err != nil { return nil, err } candidates, err := pc.iceGatherer.GetLocalCandidates() if err != nil { return nil, err } bundleValue := "BUNDLE" appendBundle := func(midValue string) { bundleValue += " " + midValue } var t *RTPTransceiver localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...) detectedPlanB := pc.descriptionIsPlanB(pc.RemoteDescription()) for _, media := range pc.RemoteDescription().parsed.MediaDescriptions { midValue := pc.getMidValue(media) if midValue == "" { return nil, fmt.Errorf("RemoteDescription contained media section without mid value") } if media.MediaName.Media == "application" { pc.addDataMediaSection(d, midValue, iceParams, candidates, sdp.ConnectionRoleActive) appendBundle(midValue) continue } kind := NewRTPCodecType(media.MediaName.Media) direction := pc.getPeerDirection(media) if kind == 0 || direction == RTPTransceiverDirection(Unknown) { continue } t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) mediaTransceivers := []*RTPTransceiver{t} switch pc.configuration.SDPSemantics { case SDPSemanticsUnifiedPlanWithFallback: // If no match, process as unified-plan if !detectedPlanB { break } // If there was a match, fall through to plan-b fallthrough case SDPSemanticsPlanB: if !detectedPlanB { return nil, &rtcerr.TypeError{Err: ErrIncorrectSDPSemantics} } // If we're responding to a plan-b offer, then we should try to fill up this // media entry with all matching local transceivers for { // keep going until we can't get any more t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers) if t.Direction == RTPTransceiverDirectionInactive { break } mediaTransceivers = append(mediaTransceivers, t) } case SDPSemanticsUnifiedPlan: if detectedPlanB { return nil, &rtcerr.TypeError{Err: ErrIncorrectSDPSemantics} } } if err := pc.addTransceiverSDP(d, midValue, iceParams, candidates, sdp.ConnectionRoleActive, mediaTransceivers...); err != nil { return nil, err } appendBundle(midValue) } if pc.configuration.SDPSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB { pc.log.Info("Plan-B Offer detected; responding with Plan-B Answer") } return d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue), nil } // CreateAnswer starts the PeerConnection and generates the localDescription func (pc *PeerConnection) CreateAnswer(options *AnswerOptions) (SessionDescription, error) { useIdentity := pc.idpLoginURL != nil switch { case options != nil: return SessionDescription{}, fmt.Errorf("TODO handle options") case pc.RemoteDescription() == nil: return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription} case useIdentity: return SessionDescription{}, fmt.Errorf("TODO handle identity provider") case pc.isClosed: return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } d := sdp.NewJSEPSessionDescription(useIdentity) if err := pc.addFingerprint(d); err != nil { return SessionDescription{}, err } d, err := pc.addAnswerMediaTransceivers(d) if err != nil { return SessionDescription{}, err } sdpBytes, err := d.Marshal() if err != nil { return SessionDescription{}, err } desc := SessionDescription{ Type: SDPTypeAnswer, SDP: string(sdpBytes), parsed: d, } pc.lastAnswer = desc.SDP return desc, nil } // 4.4.1.6 Set the SessionDescription func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeOp) error { if pc.isClosed { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } cur := pc.signalingState setLocal := stateChangeOpSetLocal setRemote := stateChangeOpSetRemote newSDPDoesNotMatchOffer := &rtcerr.InvalidModificationError{Err: fmt.Errorf("new sdp does not match previous offer")} newSDPDoesNotMatchAnswer := &rtcerr.InvalidModificationError{Err: fmt.Errorf("new sdp does not match previous answer")} var nextState SignalingState var err error switch op { case setLocal: switch sd.Type { // stable->SetLocal(offer)->have-local-offer case SDPTypeOffer: if sd.SDP != pc.lastOffer { return newSDPDoesNotMatchOffer } nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalOffer, setLocal, sd.Type) if err == nil { pc.pendingLocalDescription = sd } // have-remote-offer->SetLocal(answer)->stable // have-local-pranswer->SetLocal(answer)->stable case SDPTypeAnswer: if sd.SDP != pc.lastAnswer { return newSDPDoesNotMatchAnswer } nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type) if err == nil { pc.currentLocalDescription = sd pc.currentRemoteDescription = pc.pendingRemoteDescription pc.pendingRemoteDescription = nil pc.pendingLocalDescription = nil } case SDPTypeRollback: nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type) if err == nil { pc.pendingLocalDescription = nil } // have-remote-offer->SetLocal(pranswer)->have-local-pranswer case SDPTypePranswer: if sd.SDP != pc.lastAnswer { return newSDPDoesNotMatchAnswer } nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalPranswer, setLocal, sd.Type) if err == nil { pc.pendingLocalDescription = sd } default: return &rtcerr.OperationError{Err: fmt.Errorf("invalid state change op: %s(%s)", op, sd.Type)} } case setRemote: switch sd.Type { // stable->SetRemote(offer)->have-remote-offer case SDPTypeOffer: nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemoteOffer, setRemote, sd.Type) if err == nil { pc.pendingRemoteDescription = sd } // have-local-offer->SetRemote(answer)->stable // have-remote-pranswer->SetRemote(answer)->stable case SDPTypeAnswer: nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type) if err == nil { pc.currentRemoteDescription = sd pc.currentLocalDescription = pc.pendingLocalDescription pc.pendingRemoteDescription = nil pc.pendingLocalDescription = nil } case SDPTypeRollback: nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type) if err == nil { pc.pendingRemoteDescription = nil } // have-local-offer->SetRemote(pranswer)->have-remote-pranswer case SDPTypePranswer: nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemotePranswer, setRemote, sd.Type) if err == nil { pc.pendingRemoteDescription = sd } default: return &rtcerr.OperationError{Err: fmt.Errorf("invalid state change op: %s(%s)", op, sd.Type)} } default: return &rtcerr.OperationError{Err: fmt.Errorf("unhandled state change op: %q", op)} } if err == nil { pc.signalingState = nextState pc.onSignalingStateChange(nextState) } return err } // SetLocalDescription sets the SessionDescription of the local peer func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error { if pc.isClosed { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } // JSEP 5.4 if desc.SDP == "" { switch desc.Type { case SDPTypeAnswer, SDPTypePranswer: desc.SDP = pc.lastAnswer case SDPTypeOffer: desc.SDP = pc.lastOffer default: return &rtcerr.InvalidModificationError{ Err: fmt.Errorf("invalid SDP type supplied to SetLocalDescription(): %s", desc.Type), } } } desc.parsed = &sdp.SessionDescription{} if err := desc.parsed.Unmarshal([]byte(desc.SDP)); err != nil { return err } if err := pc.setDescription(&desc, stateChangeOpSetLocal); err != nil { return err } // To support all unittests which are following the future trickle=true // setup while also support the old trickle=false synchronous gathering // process this is necessary to avoid calling Garther() in multiple // pleces; which causes race conditions. (issue-707) if !pc.iceGatherer.agentIsTrickle { if err := pc.iceGatherer.SignalCandidates(); err != nil { return err } return nil } if desc.Type == SDPTypeAnswer { return pc.iceGatherer.Gather() } return nil } // LocalDescription returns pendingLocalDescription if it is not null and // otherwise it returns currentLocalDescription. This property is used to // determine if setLocalDescription has already been called. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription func (pc *PeerConnection) LocalDescription() *SessionDescription { if localDescription := pc.PendingLocalDescription(); localDescription != nil { return localDescription } return pc.currentLocalDescription } // SetRemoteDescription sets the SessionDescription of the remote peer func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint pion/webrtc#614 if pc.currentRemoteDescription != nil { // pion/webrtc#207 return fmt.Errorf("remoteDescription is already defined, SetRemoteDescription can only be called once") } if pc.isClosed { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } desc.parsed = &sdp.SessionDescription{} if err := desc.parsed.Unmarshal([]byte(desc.SDP)); err != nil { return err } if err := pc.setDescription(&desc, stateChangeOpSetRemote); err != nil { return err } weOffer := true remoteUfrag := "" remotePwd := "" if desc.Type == SDPTypeOffer { weOffer = false } fingerprint, haveFingerprint := desc.parsed.Attribute("fingerprint") for _, m := range pc.RemoteDescription().parsed.MediaDescriptions { if !haveFingerprint { fingerprint, haveFingerprint = m.Attribute("fingerprint") } for _, a := range m.Attributes { switch { case a.IsICECandidate(): sdpCandidate, err := a.ToICECandidate() if err != nil { return err } candidate, err := newICECandidateFromSDP(sdpCandidate) if err != nil { return err } if err = pc.iceTransport.AddRemoteCandidate(candidate); err != nil { return err } case strings.HasPrefix(*a.String(), "ice-ufrag"): remoteUfrag = (*a.String())[len("ice-ufrag:"):] case strings.HasPrefix(*a.String(), "ice-pwd"): remotePwd = (*a.String())[len("ice-pwd:"):] } } } if !haveFingerprint { return fmt.Errorf("could not find fingerprint") } parts := strings.Split(fingerprint, " ") if len(parts) != 2 { return fmt.Errorf("invalid fingerprint") } fingerprint = parts[1] fingerprintHash := parts[0] // Create the SCTP transport sctp := pc.api.NewSCTPTransport(pc.dtlsTransport) pc.sctpTransport = sctp // Wire up the on datachannel handler sctp.OnDataChannel(func(d *DataChannel) { pc.mu.RLock() hdlr := pc.onDataChannelHandler pc.dataChannels[*d.ID()] = d pc.dataChannelsAccepted++ pc.mu.RUnlock() if hdlr != nil { hdlr(d) } }) // Wire up the on datachannel opened handler sctp.OnDataChannelOpened(func(d *DataChannel) { pc.mu.RLock() pc.dataChannelsOpened++ pc.mu.RUnlock() }) go func() { // Star the networking in a new routine since it will block until // the connection is actually established. // Start the ice transport iceRole := ICERoleControlled if weOffer { iceRole = ICERoleControlling } err := pc.iceTransport.Start( pc.iceGatherer, ICEParameters{ UsernameFragment: remoteUfrag, Password: remotePwd, ICELite: false, }, &iceRole, ) if err != nil { // pion/webrtc#614 pc.log.Warnf("Failed to start manager: %s", err) return } // Start the dtls transport err = pc.dtlsTransport.Start(DTLSParameters{ Role: DTLSRoleAuto, Fingerprints: []DTLSFingerprint{{Algorithm: fingerprintHash, Value: fingerprint}}, }) if err != nil { // pion/webrtc#614 pc.log.Warnf("Failed to start manager: %s", err) return } pc.openSRTP() for _, tranceiver := range pc.GetTransceivers() { if tranceiver.Sender != nil { err = tranceiver.Sender.Send(RTPSendParameters{ Encodings: RTPEncodingParameters{ RTPCodingParameters{ SSRC: tranceiver.Sender.track.SSRC(), PayloadType: tranceiver.Sender.track.PayloadType(), }, }}) if err != nil { pc.log.Warnf("Failed to start Sender: %s", err) } } } go pc.drainSRTP() // Start sctp err = pc.sctpTransport.Start(SCTPCapabilities{ MaxMessageSize: 0, }) if err != nil { // pion/webrtc#614 pc.log.Warnf("Failed to start SCTP: %s", err) return } // Open data channels that where created before signaling pc.mu.Lock() // make a copy of dataChannels to avoid race condition accessing pc.dataChannels dataChannels := make(map[uint16]*DataChannel, len(pc.dataChannels)) for k, v := range pc.dataChannels { dataChannels[k] = v } pc.mu.Unlock() var openedDCCount uint32 for _, d := range dataChannels { err := d.open(pc.sctpTransport) if err != nil { pc.log.Warnf("failed to open data channel: %s", err) continue } openedDCCount++ } pc.mu.Lock() pc.dataChannelsOpened += openedDCCount pc.mu.Unlock() }() if (desc.Type == SDPTypeAnswer || desc.Type == SDPTypePranswer) && pc.iceGatherer.agentIsTrickle { return pc.iceGatherer.Gather() } return nil } func (pc *PeerConnection) descriptionIsPlanB(desc *SessionDescription) bool { if desc == nil || desc.parsed == nil { return false } detectionRegex := regexp.MustCompile(`(?i)^(audio|video|data)$`) for _, media := range desc.parsed.MediaDescriptions { if len(detectionRegex.FindStringSubmatch(pc.getMidValue(media))) == 2 { return true } } return false } // openSRTP opens knows inbound SRTP streams from the RemoteDescription func (pc *PeerConnection) openSRTP() { type incomingTrack struct { kind RTPCodecType label string id string ssrc uint32 } incomingTracks := map[uint32]incomingTrack{} remoteIsPlanB := false switch pc.configuration.SDPSemantics { case SDPSemanticsPlanB: remoteIsPlanB = true case SDPSemanticsUnifiedPlanWithFallback: remoteIsPlanB = pc.descriptionIsPlanB(pc.RemoteDescription()) } for _, media := range pc.RemoteDescription().parsed.MediaDescriptions { for _, attr := range media.Attributes { codecType := NewRTPCodecType(media.MediaName.Media) if codecType == 0 { continue } if attr.Key == sdp.AttrKeySSRC { split := strings.Split(attr.Value, " ") ssrc, err := strconv.ParseUint(split[0], 10, 32) if err != nil { pc.log.Warnf("Failed to parse SSRC: %v", err) continue } trackID := "" trackLabel := "" if len(split) == 3 && strings.HasPrefix(split[1], "msid:") { trackLabel = split[1][len("msid:"):] trackID = split[2] } incomingTracks[uint32(ssrc)] = incomingTrack{codecType, trackLabel, trackID, uint32(ssrc)} if trackID != "" && trackLabel != "" { break // Remote provided Label+ID, we have all the information we need } } } } startReceiver := func(incoming incomingTrack, receiver *RTPReceiver) { err := receiver.Receive(RTPReceiveParameters{ Encodings: RTPDecodingParameters{ RTPCodingParameters{SSRC: incoming.ssrc}, }}) if err != nil { pc.log.Warnf("RTPReceiver Receive failed %s", err) return } if err = receiver.Track().determinePayloadType(); err != nil { pc.log.Warnf("Could not determine PayloadType for SSRC %d", receiver.Track().SSRC()) return } pc.mu.RLock() defer pc.mu.RUnlock() if pc.currentLocalDescription == nil { pc.log.Warnf("SetLocalDescription not called, unable to handle incoming media streams") return } sdpCodec, err := pc.currentLocalDescription.parsed.GetCodecForPayloadType(receiver.Track().PayloadType()) if err != nil { pc.log.Warnf("no codec could be found in RemoteDescription for payloadType %d", receiver.Track().PayloadType()) return } codec, err := pc.api.mediaEngine.getCodecSDP(sdpCodec) if err != nil { pc.log.Warnf("codec %s in not registered", sdpCodec) return } receiver.Track().mu.Lock() receiver.Track().id = incoming.id receiver.Track().label = incoming.label receiver.Track().kind = codec.Type receiver.Track().codec = codec receiver.Track().mu.Unlock() if pc.onTrackHandler != nil { pc.onTrack(receiver.Track(), receiver) } else { pc.log.Warnf("OnTrack unset, unable to handle incoming media streams") } } localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...) for ssrc, incoming := range incomingTracks { for i := range localTransceivers { t := localTransceivers[i] switch { case incomingTracks[ssrc].kind != t.kind: continue case t.Direction != RTPTransceiverDirectionRecvonly && t.Direction != RTPTransceiverDirectionSendrecv: continue case t.Receiver == nil: continue } delete(incomingTracks, ssrc) localTransceivers = append(localTransceivers[:i], localTransceivers[i+1:]...) go startReceiver(incoming, t.Receiver) break } } if remoteIsPlanB { for ssrc, incoming := range incomingTracks { t, err := pc.AddTransceiver(incoming.kind, RtpTransceiverInit{ Direction: RTPTransceiverDirectionSendrecv, }) if err != nil { pc.log.Warnf("Could not add transceiver for remote SSRC %d: %s", ssrc, err) continue } go startReceiver(incoming, t.Receiver) } } } // drainSRTP pulls and discards RTP/RTCP packets that don't match any SRTP // These could be sent to the user, but right now we don't provide an API // to distribute orphaned RTCP messages. This is needed to make sure we don't block // and provides useful debugging messages func (pc *PeerConnection) drainSRTP() { go func() { for { srtpSession, err := pc.dtlsTransport.getSRTPSession() if err != nil { pc.log.Warnf("drainSRTP failed to open SrtpSession: %v", err) return } _, ssrc, err := srtpSession.AcceptStream() if err != nil { pc.log.Warnf("Failed to accept RTP %v \n", err) return } pc.log.Debugf("Incoming unhandled RTP ssrc(%d)", ssrc) } }() for { srtcpSession, err := pc.dtlsTransport.getSRTCPSession() if err != nil { pc.log.Warnf("drainSRTP failed to open SrtcpSession: %v", err) return } _, ssrc, err := srtcpSession.AcceptStream() if err != nil { pc.log.Warnf("Failed to accept RTCP %v \n", err) return } pc.log.Debugf("Incoming unhandled RTCP ssrc(%d)", ssrc) } } // RemoteDescription returns pendingRemoteDescription if it is not null and // otherwise it returns currentRemoteDescription. This property is used to // determine if setRemoteDescription has already been called. // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription func (pc *PeerConnection) RemoteDescription() *SessionDescription { if pc.pendingRemoteDescription != nil { return pc.pendingRemoteDescription } return pc.currentRemoteDescription } // AddICECandidate accepts an ICE candidate string and adds it // to the existing set of candidates func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error { if pc.RemoteDescription() == nil { return &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription} } candidateValue := strings.TrimPrefix(candidate.Candidate, "candidate:") attribute := sdp.NewAttribute("candidate", candidateValue) sdpCandidate, err := attribute.ToICECandidate() if err != nil { return err } iceCandidate, err := newICECandidateFromSDP(sdpCandidate) if err != nil { return err } return pc.iceTransport.AddRemoteCandidate(iceCandidate) } // ICEConnectionState returns the ICE connection state of the // PeerConnection instance. func (pc *PeerConnection) ICEConnectionState() ICEConnectionState { pc.mu.RLock() defer pc.mu.RUnlock() return pc.iceConnectionState } // GetSenders returns the RTPSender that are currently attached to this PeerConnection func (pc *PeerConnection) GetSenders() []*RTPSender { pc.mu.Lock() defer pc.mu.Unlock() result := []*RTPSender{} for _, tranceiver := range pc.rtpTransceivers { if tranceiver.Sender != nil { result = append(result, tranceiver.Sender) } } return result } // GetReceivers returns the RTPReceivers that are currently attached to this RTCPeerConnection func (pc *PeerConnection) GetReceivers() []*RTPReceiver { pc.mu.Lock() defer pc.mu.Unlock() result := []*RTPReceiver{} for _, tranceiver := range pc.rtpTransceivers { if tranceiver.Receiver != nil { result = append(result, tranceiver.Receiver) } } return result } // GetTransceivers returns the RTCRtpTransceiver that are currently attached to this RTCPeerConnection func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver { pc.mu.Lock() defer pc.mu.Unlock() return pc.rtpTransceivers } // AddTrack adds a Track to the PeerConnection func (pc *PeerConnection) AddTrack(track *Track) (*RTPSender, error) { if pc.isClosed { return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } var transceiver *RTPTransceiver for _, t := range pc.GetTransceivers() { if !t.stopped && t.Sender != nil && !t.Sender.hasSent() && t.Receiver != nil && t.Receiver.Track() != nil && t.Receiver.Track().Kind() == track.Kind() { transceiver = t break } } if transceiver != nil { if err := transceiver.setSendingTrack(track); err != nil { return nil, err } } else { receiver, err := pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport) if err != nil { return nil, err } sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err != nil { return nil, err } transceiver = pc.newRTPTransceiver( receiver, sender, RTPTransceiverDirectionSendrecv, track.Kind(), ) } return transceiver.Sender, nil } // AddTransceiver Create a new RTCRtpTransceiver and add it to the set of transceivers. // Deprecated: Use AddTrack, AddTransceiverFromKind or AddTransceiverFromTrack func (pc *PeerConnection) AddTransceiver(trackOrKind RTPCodecType, init ...RtpTransceiverInit) (*RTPTransceiver, error) { return pc.AddTransceiverFromKind(trackOrKind, init...) } // AddTransceiverFromKind Create a new RTCRtpTransceiver(SendRecv or RecvOnly) and add it to the set of transceivers. func (pc *PeerConnection) AddTransceiverFromKind(kind RTPCodecType, init ...RtpTransceiverInit) (*RTPTransceiver, error) { direction := RTPTransceiverDirectionSendrecv if len(init) > 1 { return nil, fmt.Errorf("AddTransceiverFromKind only accepts one RtpTransceiverInit") } else if len(init) == 1 { direction = init[0].Direction } switch direction { case RTPTransceiverDirectionSendrecv: receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport) if err != nil { return nil, err } codecs := pc.api.mediaEngine.GetCodecsByKind(kind) if len(codecs) == 0 { return nil, fmt.Errorf("no %s codecs found", kind.String()) } track, err := pc.NewTrack(codecs[0].PayloadType, mathRand.Uint32(), util.RandSeq(trackDefaultIDLength), util.RandSeq(trackDefaultLabelLength)) if err != nil { return nil, err } sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err != nil { return nil, err } return pc.newRTPTransceiver( receiver, sender, RTPTransceiverDirectionSendrecv, kind, ), nil case RTPTransceiverDirectionRecvonly: receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport) if err != nil { return nil, err } return pc.newRTPTransceiver( receiver, nil, RTPTransceiverDirectionRecvonly, kind, ), nil default: return nil, fmt.Errorf("AddTransceiverFromKind currently only supports recvonly and sendrecv") } } // AddTransceiverFromTrack Creates a new send only transceiver and add it to the set of func (pc *PeerConnection) AddTransceiverFromTrack(track *Track, init ...RtpTransceiverInit) (*RTPTransceiver, error) { direction := RTPTransceiverDirectionSendrecv if len(init) > 1 { return nil, fmt.Errorf("AddTransceiverFromTrack only accepts one RtpTransceiverInit") } else if len(init) == 1 { direction = init[0].Direction } switch direction { case RTPTransceiverDirectionSendrecv: receiver, err := pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport) if err != nil { return nil, err } sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err != nil { return nil, err } return pc.newRTPTransceiver( receiver, sender, RTPTransceiverDirectionSendrecv, track.Kind(), ), nil case RTPTransceiverDirectionSendonly: sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err != nil { return nil, err } return pc.newRTPTransceiver( nil, sender, RTPTransceiverDirectionSendonly, track.Kind(), ), nil default: return nil, fmt.Errorf("AddTransceiverFromTrack currently only supports sendonly and sendrecv") } } // CreateDataChannel creates a new DataChannel object with the given label // and optional DataChannelInit used to configure properties of the // underlying channel such as data reliability. func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelInit) (*DataChannel, error) { pc.mu.Lock() // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2) if pc.isClosed { pc.mu.Unlock() return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } // pion/webrtc#748 params := &DataChannelParameters{ Label: label, Ordered: true, } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #19) if options == nil || options.ID == nil { var err error if params.ID, err = pc.generateDataChannelID(true); err != nil { pc.mu.Unlock() return nil, err } } else { params.ID = *options.ID } if options != nil { // Ordered indicates if data is allowed to be delivered out of order. The // default value of true, guarantees that data will be delivered in order. if options.Ordered != nil { params.Ordered = *options.Ordered } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #7) if options.MaxPacketLifeTime != nil { params.MaxPacketLifeTime = options.MaxPacketLifeTime } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #8) if options.MaxRetransmits != nil { params.MaxRetransmits = options.MaxRetransmits } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9) if options.Ordered != nil { params.Ordered = *options.Ordered } } // pion/webrtc#748 d, err := pc.api.newDataChannel(params, pc.log) if err != nil { pc.mu.Unlock() return nil, err } // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16) if d.maxPacketLifeTime != nil && d.maxRetransmits != nil { pc.mu.Unlock() return nil, &rtcerr.TypeError{Err: ErrRetransmitsOrPacketLifeTime} } // Remember datachannel pc.dataChannels[params.ID] = d sctpReady := pc.sctpTransport != nil && pc.sctpTransport.association != nil pc.dataChannelsRequested++ pc.mu.Unlock() // Open if networking already started if sctpReady { err = d.open(pc.sctpTransport) if err != nil { return nil, err } } return d, nil } func (pc *PeerConnection) generateDataChannelID(client bool) (uint16, error) { var id uint16 if !client { id++ } max := sctpMaxChannels if pc.sctpTransport != nil { max = pc.sctpTransport.MaxChannels() } for ; id < max-1; id += 2 { _, ok := pc.dataChannels[id] if !ok { return id, nil } } return 0, &rtcerr.OperationError{Err: ErrMaxDataChannelID} } // SetIdentityProvider is used to configure an identity provider to generate identity assertions func (pc *PeerConnection) SetIdentityProvider(provider string) error { return fmt.Errorf("TODO SetIdentityProvider") } // WriteRTCP sends a user provided RTCP packet to the connected peer // If no peer is connected the packet is discarded func (pc *PeerConnection) WriteRTCP(pkts []rtcp.Packet) error { raw, err := rtcp.Marshal(pkts) if err != nil { return err } srtcpSession, err := pc.dtlsTransport.getSRTCPSession() if err != nil { return nil } writeStream, err := srtcpSession.OpenWriteStream() if err != nil { return fmt.Errorf("WriteRTCP failed to open WriteStream: %v", err) } if _, err := writeStream.Write(raw); err != nil { return err } return nil } // Close ends the PeerConnection func (pc *PeerConnection) Close() error { // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2) if pc.isClosed { return nil } // Try closing everything and collect the errors // Shutdown strategy: // 1. All Conn close by closing their underlying Conn. // 2. A Mux stops this chain. It won't close the underlying // Conn if one of the endpoints is closed down. To // continue the chain the Mux has to be closed. var closeErrs []error // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3) pc.isClosed = true // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4) pc.signalingState = SignalingStateClosed // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11) if pc.iceTransport != nil { if err := pc.iceTransport.Stop(); err != nil { closeErrs = append(closeErrs, err) } } // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #12) pc.connectionState = PeerConnectionStateClosed if err := pc.dtlsTransport.Stop(); err != nil { closeErrs = append(closeErrs, err) } if pc.sctpTransport != nil { if err := pc.sctpTransport.Stop(); err != nil { closeErrs = append(closeErrs, err) } } for _, t := range pc.rtpTransceivers { if err := t.Stop(); err != nil { closeErrs = append(closeErrs, err) } } return util.FlattenErrs(closeErrs) } func (pc *PeerConnection) iceStateChange(newState ICEConnectionState) { pc.mu.Lock() pc.iceConnectionState = newState pc.mu.Unlock() pc.onICEConnectionStateChange(newState) } func (pc *PeerConnection) addFingerprint(d *sdp.SessionDescription) error { // pion/webrtc#753 fingerprints, err := pc.configuration.Certificates[0].GetFingerprints() if err != nil { return err } for _, fingerprint := range fingerprints { d.WithFingerprint(fingerprint.Algorithm, strings.ToUpper(fingerprint.Value)) } return nil } func (pc *PeerConnection) addTransceiverSDP(d *sdp.SessionDescription, midValue string, iceParams ICEParameters, candidates []ICECandidate, dtlsRole sdp.ConnectionRole, transceivers ...*RTPTransceiver) error { if len(transceivers) < 1 { return fmt.Errorf("addTransceiverSDP() called with 0 transceivers") } // Use the first transceiver to generate the section attributes t := transceivers[0] media := sdp.NewJSEPMediaDescription(t.kind.String(), []string{}). WithValueAttribute(sdp.AttrKeyConnectionSetup, dtlsRole.String()). // pion/webrtc#494 WithValueAttribute(sdp.AttrKeyMID, midValue). WithICECredentials(iceParams.UsernameFragment, iceParams.Password). WithPropertyAttribute(sdp.AttrKeyRTCPMux). WithPropertyAttribute(sdp.AttrKeyRTCPRsize) codecs := pc.api.mediaEngine.GetCodecsByKind(t.kind) for _, codec := range codecs { media.WithCodec(codec.PayloadType, codec.Name, codec.ClockRate, codec.Channels, codec.SDPFmtpLine) for _, feedback := range codec.RTPCodecCapability.RTCPFeedback { media.WithValueAttribute("rtcp-fb", fmt.Sprintf("%d %s %s", codec.PayloadType, feedback.Type, feedback.Parameter)) } } if len(codecs) == 0 { // Explicitly reject track if we don't have the codec d.WithMedia(&sdp.MediaDescription{ MediaName: sdp.MediaName{ Media: t.kind.String(), Port: sdp.RangedPort{Value: 0}, Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, Formats: []string{"0"}, }, }) return nil } for _, mt := range transceivers { if mt.Sender != nil && mt.Sender.track != nil { track := mt.Sender.track media = media.WithMediaSource(track.SSRC(), track.Label() /* cname */, track.Label() /* streamLabel */, track.ID()) if pc.configuration.SDPSemantics == SDPSemanticsUnifiedPlan { media = media.WithPropertyAttribute("msid:" + track.Label() + " " + track.ID()) break } } } media = media.WithPropertyAttribute(t.Direction.String()) addCandidatesToMediaDescriptions(candidates, media) d.WithMedia(media) return nil } func (pc *PeerConnection) addDataMediaSection(d *sdp.SessionDescription, midValue string, iceParams ICEParameters, candidates []ICECandidate, dtlsRole sdp.ConnectionRole) { media := (&sdp.MediaDescription{ MediaName: sdp.MediaName{ Media: "application", Port: sdp.RangedPort{Value: 9}, Protos: []string{"DTLS", "SCTP"}, Formats: []string{"5000"}, }, ConnectionInformation: &sdp.ConnectionInformation{ NetworkType: "IN", AddressType: "IP4", Address: &sdp.Address{ Address: "0.0.0.0", }, }, }). WithValueAttribute(sdp.AttrKeyConnectionSetup, dtlsRole.String()). // pion/webrtc#494 WithValueAttribute(sdp.AttrKeyMID, midValue). WithPropertyAttribute(RTPTransceiverDirectionSendrecv.String()). WithPropertyAttribute("sctpmap:5000 webrtc-datachannel 1024"). WithICECredentials(iceParams.UsernameFragment, iceParams.Password) addCandidatesToMediaDescriptions(candidates, media) d.WithMedia(media) } // NewTrack Creates a new Track func (pc *PeerConnection) NewTrack(payloadType uint8, ssrc uint32, id, label string) (*Track, error) { codec, err := pc.api.mediaEngine.getCodec(payloadType) if err != nil { return nil, err } else if codec.Payloader == nil { return nil, fmt.Errorf("codec payloader not set") } return NewTrack(payloadType, ssrc, id, label, codec) } func (pc *PeerConnection) newRTPTransceiver( receiver *RTPReceiver, sender *RTPSender, direction RTPTransceiverDirection, kind RTPCodecType, ) *RTPTransceiver { t := &RTPTransceiver{ Receiver: receiver, Sender: sender, Direction: direction, kind: kind, } pc.mu.Lock() defer pc.mu.Unlock() pc.rtpTransceivers = append(pc.rtpTransceivers, t) return t } func (pc *PeerConnection) populateLocalCandidates(orig *SessionDescription) *SessionDescription { if orig == nil { return nil } else if pc.iceGatherer == nil { return orig } candidates, err := pc.iceGatherer.GetLocalCandidates() if err != nil { return orig } parsed := pc.pendingLocalDescription.parsed for _, m := range parsed.MediaDescriptions { addCandidatesToMediaDescriptions(candidates, m) } sdp, err := parsed.Marshal() if err != nil { return orig } return &SessionDescription{ SDP: string(sdp), Type: pc.pendingLocalDescription.Type, } } // CurrentLocalDescription represents the local description that was // successfully negotiated the last time the PeerConnection transitioned // into the stable state plus any local candidates that have been generated // by the ICEAgent since the offer or answer was created. func (pc *PeerConnection) CurrentLocalDescription() *SessionDescription { return pc.populateLocalCandidates(pc.currentLocalDescription) } // PendingLocalDescription represents a local description that is in the // process of being negotiated plus any local candidates that have been // generated by the ICEAgent since the offer or answer was created. If the // PeerConnection is in the stable state, the value is null. func (pc *PeerConnection) PendingLocalDescription() *SessionDescription { return pc.populateLocalCandidates(pc.pendingLocalDescription) } // CurrentRemoteDescription represents the last remote description that was // successfully negotiated the last time the PeerConnection transitioned // into the stable state plus any remote candidates that have been supplied // via AddICECandidate() since the offer or answer was created. func (pc *PeerConnection) CurrentRemoteDescription() *SessionDescription { return pc.currentRemoteDescription } // PendingRemoteDescription represents a remote description that is in the // process of being negotiated, complete with any remote candidates that // have been supplied via AddICECandidate() since the offer or answer was // created. If the PeerConnection is in the stable state, the value is // null. func (pc *PeerConnection) PendingRemoteDescription() *SessionDescription { return pc.pendingRemoteDescription } // SignalingState attribute returns the signaling state of the // PeerConnection instance. func (pc *PeerConnection) SignalingState() SignalingState { return pc.signalingState } // ICEGatheringState attribute returns the ICE gathering state of the // PeerConnection instance. func (pc *PeerConnection) ICEGatheringState() ICEGatheringState { switch pc.iceGatherer.State() { case ICEGathererStateNew: return ICEGatheringStateNew case ICEGathererStateGathering: return ICEGatheringStateGathering default: return ICEGatheringStateComplete } } // ConnectionState attribute returns the connection state of the // PeerConnection instance. func (pc *PeerConnection) ConnectionState() PeerConnectionState { return pc.connectionState } // GetStats return data providing statistics about the overall connection func (pc *PeerConnection) GetStats() StatsReport { statsCollector := newStatsReportCollector() statsCollector.Collecting() pc.mu.Lock() var dataChannelsClosed uint32 for _, d := range pc.dataChannels { state := d.ReadyState() if state != DataChannelStateConnecting && state != DataChannelStateOpen { dataChannelsClosed++ } d.collectStats(statsCollector) } pc.iceGatherer.collectStats(statsCollector) stats := PeerConnectionStats{ Timestamp: statsTimestampNow(), Type: StatsTypePeerConnection, ID: pc.statsID, DataChannelsOpened: pc.dataChannelsOpened, DataChannelsClosed: dataChannelsClosed, DataChannelsRequested: pc.dataChannelsRequested, DataChannelsAccepted: pc.dataChannelsAccepted, } pc.mu.Unlock() statsCollector.Collect(stats.ID, stats) return statsCollector.Ready() } func addCandidatesToMediaDescriptions(candidates []ICECandidate, m *sdp.MediaDescription) { for _, c := range candidates { sdpCandidate := iceCandidateToSDP(c) sdpCandidate.ExtensionAttributes = append(sdpCandidate.ExtensionAttributes, sdp.ICECandidateAttribute{Key: "generation", Value: "0"}) sdpCandidate.Component = 1 m.WithICECandidate(sdpCandidate) sdpCandidate.Component = 2 m.WithICECandidate(sdpCandidate) } if len(candidates) != 0 { m.WithPropertyAttribute("end-of-candidates") } }
{ return SessionDescription{}, err }
handler_0_1.py
#!/usr/bin/python # -*- coding: utf-8 -*- # __author__ : stray_camel # __description__ : trans_0_1 # __REFERENCES__ : https://blog.csdn.net/qq_42544196/article/details/106468658;https://docs.python.org/3/library/logging.html # __date__: 2020/12/11 15 import datetime import logging from pathlib import Path import random import re import sys import threading import time from functools import wraps from hashlib import md5 from typing import Any import requests def logger_set(): """ 自定义日志格式,保存至对应文件 官方文档:https://docs.python.org/3/library/logging.html """ # 日志文件存储格式 logger = logging.getLogger() logsf_loder = Path('./logs') # 如果目录不存在则创建 logsf_loder.mkdir(parents=True, exist_ok=True) # 储存的文件名,带时间戳后缀 logs_file = logsf_loder / \ "{}.log".format(datetime.datetime.now().strftime('%y-%m-%d')) # 转为绝对路径 fh = logging.FileHandler(logs_file.resolve(), encoding="utf-8", mode="a") logger.setLevel(logging.INFO) fh.setFormatter(logging.Formatter("%(message)s\n")) logger.addHandler(fh) # 打印格式 console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logger_set() class YouDaoFanYi(object): """ 引用于作者:https://blog.csdn.net/qq_42544196 """ def __init__(self): self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/81.0.4044.138 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Referer': 'http://fanyi.youdao.com/', 'Cookie': 'OUTFOX_SEARCH_USER_ID="[email protected]"' } @staticmethod def create_data(e): n = "5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" t = md5(n.encode()).hexdigest() r = int(time.time() * 1000) i = int(str(r) + str(random.randint(0, 10))) sign = md5(("fanyideskweb" + e + str(i) + "Nw(nmmbP%A-r6U3EUn]Aj").encode()).hexdigest() return {'ts': r, 'bv': t, 'salt': i, 'sign': sign} def fanyi_word(self, word): sys_data = self.create_data(word) data = { 'i': word, 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'doctype': 'json', 'version': 2.1, 'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTlME' } result = requests.post(url=self.url, headers=self.headers, data={ **data, **sys_data}).json() # print(result) return result def main(self, word): self.fanyi_word(word) def thread_handler(func): """ TODO:多线程运行 """ @wraps(func) def wrapper(self, *args, **kwargs): pass return wrapper class fanyi(YouDaoFanYi): """ 定制翻译对象 """ def _fanyi_word(self, word): res = self.fanyi_word(word=word) try: if res.get('translate
务 (transaction);及物的;(关系)可递的;过度的 (transitive);(尤指职业)翻译;翻译程序;电 >>> 视差频转播机 (translator) >>> adj. 反式的;跨性别的;(有机体)异型结合的 --------------------------------------------------------------------------- """ # fanyi = fanyi() # fanyi(*sys.argv[1:])
Result'): smartResults = res.get('smartResult', {}).get('entries', []) results = [ re.sub("[\!\%\\t\\r\\n]", "", res) for res in smartResults if res ] rest = '\n '.join([word]+results) if results else '' return rest except: pass def word_analysis_copy(self, *args: '翻译单个或多个单词', **kwds: Any): """ """ args = [' '.join(_.split('_')) if '_' in _ else _ for _ in set(args)] logging.info('\n'.join(map(self._fanyi_word, args))) def __call__(self, *args: Any, **kwds: Any) -> Any: self.word_analysis_copy(*args) """ --------------------------------------------------------------------------- 代码运行 >>> python .\main.py trans >>> trans >>> n. (Trans) (丹)唐(人名) >>> abbr. 交易;交易行为;交流;事
rippleapi_address_test.go
package xrp_test import ( "testing" "github.com/bookerzzz/grok" "github.com/hiromaily/go-crypto-wallet/pkg/testutil" ) // TestGenerateAddress is test for GenerateAddress func TestGenerateAddress(t *testing.T) { // t.SkipNow() xr := testutil.GetXRP() addressInfo, err := xr.GenerateAddress() if err != nil { t.Fatal(err) } grok.Value(addressInfo) } // TestGenerateXAddress is test for GenerateXAddress func TestGenerateXAddress(t *testing.T)
// TestIsValidAddress is test for IsValidAddress func TestIsValidAddress(t *testing.T) { // t.SkipNow() xr := testutil.GetXRP() type args struct { address string } type want struct { isErr bool } tests := []struct { name string args args want want }{ { name: "happy path 1", args: args{ address: "XV9StxHCQ5meDLmRkw2ifV97iy7KiSW22Aku1D4UKqRKXwR", }, want: want{false}, }, { name: "happy path 2", args: args{ address: "rss1EZUwTCPZSTyJiDKvhBfCXjTxffcArZ", }, want: want{false}, }, { name: "happy path 3", args: args{ address: "X7vq1EiQAv1K4miEEqJLWcwsbbTENyVZLc96rGUd8XJSX7C", }, want: want{false}, }, { name: "happy path 4", args: args{ address: "r94FEwKytUn6qf4hxTL1wTeMP3sQfLGac9", }, want: want{false}, }, { name: "wrong address", args: args{ address: "0xabc12345", }, want: want{true}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // PrepareTransaction accountInfo, err := xr.IsValidAddress(tt.args.address) if err != nil { t.Fatal(err) } grok.Value(accountInfo) }) } }
{ // t.SkipNow() xr := testutil.GetXRP() addressInfo, err := xr.GenerateXAddress() if err != nil { t.Fatal(err) } grok.Value(addressInfo) }
main.go
package main import ( "context" "database/sql" "fmt" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/sqlitedialect" "github.com/uptrace/bun/driver/sqliteshim" "github.com/uptrace/bun/extra/bundebug" ) type Order struct { ID int64 Items []Item `bun:"m2m:order_to_items"` } type Item struct { ID int64 } type OrderToItem struct { OrderID int64 `bun:",pk"` Order *Order `bun:"rel:belongs-to"` ItemID int64 `bun:",pk"` Item *Item `bun:"rel:belongs-to"` } func
() { ctx := context.Background() sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared") if err != nil { panic(err) } db := bun.NewDB(sqldb, sqlitedialect.New()) defer db.Close() db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true))) // Register many to many model so bun can better recognize m2m relation. // This should be done before you use the model for the first time. db.RegisterModel((*OrderToItem)(nil)) if err := createSchema(ctx, db); err != nil { panic(err) } order := new(Order) if err := db.NewSelect(). Model(order). Relation("Items"). Order("order.id ASC"). Limit(1). Scan(ctx); err != nil { panic(err) } fmt.Println("Order", order.ID, "Items", order.Items[0].ID, order.Items[1].ID) order = new(Order) if err := db.NewSelect(). Model(order). Relation("Items", func(q *bun.SelectQuery) *bun.SelectQuery { q = q.OrderExpr("item.id DESC") return q }). Limit(1). Scan(ctx); err != nil { panic(err) } fmt.Println("Order", order.ID, "Items", order.Items[0].ID, order.Items[1].ID) // Output: Order 1 Items 1 2 // Order 1 Items 2 1 } func createSchema(ctx context.Context, db *bun.DB) error { models := []interface{}{ (*Order)(nil), (*Item)(nil), (*OrderToItem)(nil), } for _, model := range models { if _, err := db.NewCreateTable().Model(model).Exec(ctx); err != nil { return err } } values := []interface{}{ &Item{ID: 1}, &Item{ID: 2}, &Order{ID: 1}, &OrderToItem{OrderID: 1, ItemID: 1}, &OrderToItem{OrderID: 1, ItemID: 2}, } for _, value := range values { if _, err := db.NewInsert().Model(value).Exec(ctx); err != nil { return err } } return nil }
main
foldersApi.ts
/** * SendinBlue API * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | * * The version of the OpenAPI document: 3.0.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import localVarRequest = require('request'); import http = require('http'); /* tslint:disable:no-unused-locals */ import { CreateModel } from '../model/createModel'; import { CreateUpdateFolder } from '../model/createUpdateFolder'; import { GetFolder } from '../model/getFolder'; import { GetFolderLists } from '../model/getFolderLists'; import { GetFolders } from '../model/getFolders'; import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; import { ApiKeyAuth } from '../model/models'; import { HttpError } from './apis'; const defaultBasePath = 'https://api.sendinblue.com/v3'; // =============================================== // This file is autogenerated - Please do not edit // =============================================== export enum FoldersApiApiKeys { apiKey, partnerKey, } export class
{ protected _basePath = defaultBasePath; protected _defaultHeaders : any = { 'user-agent': 'sendinblue_clientAPI/v2.2.0/ts-node' }; protected _useQuerystring = false; protected authentications = { 'default': <Authentication>new VoidAuth(), 'apiKey': new ApiKeyAuth('header', 'api-key'), 'partnerKey': new ApiKeyAuth('header', 'partner-key'), } protected interceptors: Interceptor[] = []; constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } set defaultHeaders(defaultHeaders: any) { if (defaultHeaders['user-agent'] && defaultHeaders['user-agent'].substr(0,11).toLowerCase() !== 'sendinblue_') { this._defaultHeaders = this._defaultHeaders; } else { this._defaultHeaders = defaultHeaders; } } get defaultHeaders() { return this._defaultHeaders; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: FoldersApiApiKeys, value: string) { (this.authentications as any)[FoldersApiApiKeys[key]].apiKey = value; } public addInterceptor(interceptor: Interceptor) { this.interceptors.push(interceptor); } /** * * @summary Create a folder * @param createFolder Name of the folder */ public async createFolder (createFolder: CreateUpdateFolder, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: CreateModel; }> { const localVarPath = this.basePath + '/contacts/folders'; const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'createFolder' is not null or undefined if (createFolder === null || createFolder === undefined) { throw new Error('Required parameter createFolder was null or undefined when calling createFolder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(createFolder, "CreateUpdateFolder") }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: CreateModel; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "CreateModel"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * * @summary Delete a folder (and all its lists) * @param folderId Id of the folder */ public async deleteFolder (folderId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/contacts/folders/{folderId}' .replace('{' + 'folderId' + '}', encodeURIComponent(String(folderId))); const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'folderId' is not null or undefined if (folderId === null || folderId === undefined) { throw new Error('Required parameter folderId was null or undefined when calling deleteFolder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * * @summary Returns a folder\'s details * @param folderId id of the folder */ public async getFolder (folderId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: GetFolder; }> { const localVarPath = this.basePath + '/contacts/folders/{folderId}' .replace('{' + 'folderId' + '}', encodeURIComponent(String(folderId))); const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'folderId' is not null or undefined if (folderId === null || folderId === undefined) { throw new Error('Required parameter folderId was null or undefined when calling getFolder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: GetFolder; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "GetFolder"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * * @summary Get lists in a folder * @param folderId Id of the folder * @param limit Number of documents per page * @param offset Index of the first document of the page * @param sort Sort the results in the ascending/descending order of record creation. Default order is **descending** if &#x60;sort&#x60; is not passed */ public async getFolderLists (folderId: number, limit?: number, offset?: number, sort?: 'asc' | 'desc', options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: GetFolderLists; }> { const localVarPath = this.basePath + '/contacts/folders/{folderId}/lists' .replace('{' + 'folderId' + '}', encodeURIComponent(String(folderId))); const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'folderId' is not null or undefined if (folderId === null || folderId === undefined) { throw new Error('Required parameter folderId was null or undefined when calling getFolderLists.'); } if (limit !== undefined) { localVarQueryParameters['limit'] = ObjectSerializer.serialize(limit, "number"); } if (offset !== undefined) { localVarQueryParameters['offset'] = ObjectSerializer.serialize(offset, "number"); } if (sort !== undefined) { localVarQueryParameters['sort'] = ObjectSerializer.serialize(sort, "'asc' | 'desc'"); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: GetFolderLists; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "GetFolderLists"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * * @summary Get all folders * @param limit Number of documents per page * @param offset Index of the first document of the page * @param sort Sort the results in the ascending/descending order of record creation. Default order is **descending** if &#x60;sort&#x60; is not passed */ public async getFolders (limit: number, offset: number, sort?: 'asc' | 'desc', options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: GetFolders; }> { const localVarPath = this.basePath + '/contacts/folders'; const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'limit' is not null or undefined if (limit === null || limit === undefined) { throw new Error('Required parameter limit was null or undefined when calling getFolders.'); } // verify required parameter 'offset' is not null or undefined if (offset === null || offset === undefined) { throw new Error('Required parameter offset was null or undefined when calling getFolders.'); } if (limit !== undefined) { localVarQueryParameters['limit'] = ObjectSerializer.serialize(limit, "number"); } if (offset !== undefined) { localVarQueryParameters['offset'] = ObjectSerializer.serialize(offset, "number"); } if (sort !== undefined) { localVarQueryParameters['sort'] = ObjectSerializer.serialize(sort, "'asc' | 'desc'"); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: GetFolders; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "GetFolders"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * * @summary Update a folder * @param folderId Id of the folder * @param updateFolder Name of the folder */ public async updateFolder (folderId: number, updateFolder: CreateUpdateFolder, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/contacts/folders/{folderId}' .replace('{' + 'folderId' + '}', encodeURIComponent(String(folderId))); const localVarQueryParameters: any = {}; const localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } const localVarFormParams: any = {}; // verify required parameter 'folderId' is not null or undefined if (folderId === null || folderId === undefined) { throw new Error('Required parameter folderId was null or undefined when calling updateFolder.'); } // verify required parameter 'updateFolder' is not null or undefined if (updateFolder === null || updateFolder === undefined) { throw new Error('Required parameter updateFolder was null or undefined when calling updateFolder.'); } (<any>Object).assign(localVarHeaderParams, options.headers); const localVarUseFormData = false; const localVarRequestOptions: localVarRequest.Options = { method: 'PUT', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(updateFolder, "CreateUpdateFolder") }; let authenticationPromise = Promise.resolve(); if (this.authentications.apiKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.apiKey.applyToRequest(localVarRequestOptions)); } if (this.authentications.partnerKey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.partnerKey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } }
FoldersApi
rush_test.go
// Copyright 2017 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "fmt" "regexp" "strings" "testing" "github.com/u-root/u-root/pkg/testutil" ) var tests = []struct { stdin string // input stdout string // output (regular expression) stderr string // output (regular expression) ret int // output }{ // TODO: Create a `-c` flag for rush so stdout does not contain // prompts, or have the prompt be derived from $PS1. {"exit\n", "% ", "", 0}, {"exit 77\n", "% ", "", 77}, {"exit 1 2 3\n", "% % ", "Too many arguments\n", 0}, {"exit abcd\n", "% % ", "Non numeric argument\n", 0}, {"time cd .\n", "% % ", `real 0.0\d\d\n`, 0}, {"time sleep 0.25\n", "% % ", `real \d+.\d{3}\nuser \d+.\d{3}\nsys \d+.\d{3}\n`, 0}, } func testRush(t *testing.T) { // Table-driven testing for i, tt := range tests { t.Run(fmt.Sprintf("test%d", i), func(t *testing.T) { // Run command cmd := testutil.Command(t) cmd.Stdin = strings.NewReader(tt.stdin) var stdout bytes.Buffer cmd.Stdout = &stdout var stderr bytes.Buffer cmd.Stderr = &stderr err := cmd.Run() // Check stdout strout := stdout.String() if !regexp.MustCompile("^" + tt.stdout + "$").MatchString(strout) { t.Errorf("Want: %#v; Got: %#v", tt.stdout, strout) } // Check stderr strerr := stderr.String() if !regexp.MustCompile("^" + tt.stderr + "$").MatchString(strerr) { t.Errorf("Want: %#v; Got: %#v", tt.stderr, strerr) } // Check return code if err := testutil.IsExitCode(err, tt.ret); err != nil { t.Error(err) } })
} func TestMain(m *testing.M) { testutil.Run(m, main) }
}
template.ts
/** * @file: template.ts * @description .对 san 的模板的 */ // 删除模板中的注释, 主要针对模板中的 js 和 css 部分 // 也适用于 ts // @note: 双斜杠注释的双斜杠后面必须有空格, 否则不会删除这个注释, 即 // 后面这个注释会删除: // x // 后面这个注释不会删除: //x export function removeComments(oriCode: string) { /* eslint-disable max-len */ const reg = /"(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|`(?:[^\\`]|
/\/\s+[^\r\n\f]+|\/\*[\s\S]+?(?:\*\/|$))/g; /* eslint-enable max-len */ const code = oriCode.replace(reg, (m, comment) => { return comment ? '' : m; }); return code; }
\\[\s\S])*`|(\
combo_box.rs
#![allow(non_snake_case,dead_code,unused_variables)] use atl::{CWindow,NULL_HWND}; use winapi::ctypes::*; use winapi::shared::basetsd::*; use winapi::shared::minwindef::*; use winapi::shared::windef::*; use winapi::shared::ntdef::*; use winapi::um::commctrl::*; use winapi::um::winuser::*; use std::ops::{Deref,DerefMut}; pub struct CComboBox { inner: CWindow, } impl Deref for CComboBox { type Target = CWindow; fn deref<'a>(&'a self)->&'a CWindow { &self.inner } } //impl this for Attach and Detach impl DerefMut for CComboBox { //type Target = CWindow; fn deref_mut<'a>(&'a mut self)->&'a mut CWindow{ &mut self.inner } } impl CComboBox { pub fn new()->CComboBox
pub fn cwin(&self)->&CWindow { &self.inner } // pub fn Attach(&mut self,h: HWND) { // self.inner.Attach(h) // } // pub fn Detach(&mut self)->HWND { // self.inner.Detach() // } // pub fn cwin_mut(&mut self)->&mut CWindow { // &mut self.inner // } } /* (1) delete const ) const => ) convert fn format ^\t(\w+)\s+(\w+)\((.*)\)\s+\{ => \tpub fn \2 \(\3\)->\1 { (2) delete ) const ->void (3) ATLASSERT(::IsWindow(m_hWnd)); => self.inner.assert_window(); (4) ::SendMessage(m_hWnd, => self.inner.SendMessage( (5) parameter define // no parameter pub fn (\w+)\s*\(\) => pub fn \1\(&self) //one parameter pub fn (\w+)\s*\((\w+) (\w+)\) => pub fn \1\(&self,\3: \2\) // two parameter pub fn (\w+)\s*\((\w+) (\w+), (\w+) (\w+)\) => pub fn \1\(&self,\3: \2\, \5: \4) (6) coercion \(LPARAM\)(\w+) => \1 as LPARAM \(WPARAM\)(\w+) => \1 as WPARAM (7) define #define (\w+)\s+(\w+) => \1: UINT = \2; (8) return convert return \((\w+)\)(.*); => \2 as \1 */ impl CComboBox{ // Constructors // CComboBoxT(HWND hWnd = NULL) : TBase(hWnd) // { } // CComboBoxT< TBase >& operator =(HWND hWnd) // { // m_hWnd = hWnd; // return *this; // } // HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL, // DWORD dwStyle = 0, DWORD dwExStyle = 0, // ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL) // { // return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam); // } // // Attributes // static LPCTSTR GetWndClassName() // { // return _T("COMBOBOX"); // } // for entire combo box pub fn GetCount(&self)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETCOUNT, 0, 0) as c_int } pub fn GetCurSel(&self)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETCURSEL, 0, 0) as c_int } pub fn SetCurSel(&self,nSelect: c_int)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETCURSEL, nSelect as WPARAM, 0) as c_int } pub fn GetLocale(&self)->LCID { self.inner.assert_window(); self.inner.SendMessage( CB_GETLOCALE, 0, 0) as LCID } pub fn SetLocale(&self,nNewLocale: LCID)->LCID { self.inner.assert_window(); self.inner.SendMessage( CB_SETLOCALE, nNewLocale as WPARAM, 0) as LCID } pub fn GetTopIndex(&self)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETTOPINDEX, 0, 0) as c_int } pub fn SetTopIndex(&self,nIndex: c_int)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETTOPINDEX, nIndex as WPARAM, 0) as c_int } pub fn GetHorizontalExtent(&self)->UINT { self.inner.assert_window(); self.inner.SendMessage( CB_GETHORIZONTALEXTENT, 0, 0) as UINT } pub fn SetHorizontalExtent(&self,nExtent: UINT) { self.inner.assert_window(); self.inner.SendMessage( CB_SETHORIZONTALEXTENT, nExtent as WPARAM, 0); } pub fn GetDroppedWidth(&self)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETDROPPEDWIDTH, 0, 0) as c_int } pub fn SetDroppedWidth(&self,nWidth: UINT)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETDROPPEDWIDTH, nWidth as WPARAM, 0) as c_int } //#if ((WINVER >= 0x0500) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420)) pub fn GetComboBoxInfo(&self,pComboBoxInfo: PCOMBOBOXINFO)->BOOL { self.inner.assert_window(); //#if ((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420)) self.inner.SendMessage( CB_GETCOMBOBOXINFO, 0, pComboBoxInfo as LPARAM) as BOOL //#else // !((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420)) // return ::GetComboBoxInfo(m_hWnd, pComboBoxInfo); //#endif // !((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420)) } //#endif // ((WINVER >= 0x0500) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420)) // for edit control pub fn GetEditSel(&self)->DWORD { self.inner.assert_window(); self.inner.SendMessage( CB_GETEDITSEL, 0, 0) as DWORD } pub fn SetEditSel(&self,nStartChar: c_int, nEndChar: c_int)->BOOL { self.inner.assert_window(); self.inner.SendMessage( CB_SETEDITSEL, 0, MAKELONG(nStartChar as WORD, nEndChar as WORD) as LPARAM) as BOOL } // for combobox item pub fn GetItemData(&self,nIndex: c_int)->DWORD_PTR { self.inner.assert_window(); self.inner.SendMessage( CB_GETITEMDATA, nIndex as WPARAM, 0) as DWORD_PTR } pub fn SetItemData(&self,nIndex: c_int, dwItemData: DWORD_PTR)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETITEMDATA, nIndex as WPARAM, dwItemData as LPARAM) as c_int } pub fn GetItemDataPtr(&self,nIndex: c_int)->*const c_void { self.inner.assert_window(); self.GetItemData(nIndex) as *const c_void } pub fn SetItemDataPtr (&self, nIndex: c_int, pData: *const c_void)->c_int { self.inner.assert_window(); self.SetItemData(nIndex, pData as DWORD_PTR) } // pub fn GetLBText(&self,nIndex: c_int, lpszText: LPTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_GETLBTEXT, nIndex, lpszText as LPARAM) as c_int // } // #ifndef _ATL_NO_COM // pub fn GetLBTextBSTR (c_int nIndex, BSTR& bstrText)->BOOL { // USES_CONVERSION; // self.inner.assert_window(); // ATLASSERT(bstrText == NULL); // c_int nLen = GetLBTextLen(nIndex); // if(nLen == CB_ERR) // return FALSE; // CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff; // LPTSTR lpstrText = buff.Allocate(nLen + 1); // if(lpstrText == NULL) // return FALSE; // if(GetLBText(nIndex, lpstrText) == CB_ERR) // return FALSE; // bstrText = ::SysAllocString(T2OLE(lpstrText)); // return (bstrText != NULL) ? TRUE : FALSE; // } // #endif // !_ATL_NO_COM // #if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) // pub fn GetLBText (c_int nIndex, _CSTRING_NS::CString& strText)->c_int { // self.inner.assert_window(); // c_int cchLen = GetLBTextLen(nIndex); // if(cchLen == CB_ERR) // return CB_ERR; // c_int nRet = CB_ERR; // LPTSTR lpstr = strText.GetBufferSetLength(cchLen); // if(lpstr != NULL) // { // nRet = GetLBText(nIndex, lpstr); // strText.ReleaseBuffer(); // } // return nRet; // } // #endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__) pub fn GetLBTextLen(&self,nIndex: c_int)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETLBTEXTLEN, nIndex as WPARAM, 0) as c_int } pub fn GetItemHeight(&self,nIndex: c_int)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETITEMHEIGHT, nIndex as WPARAM, 0) as c_int } pub fn SetItemHeight(&self,nIndex: c_int, cyItemHeight: UINT)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETITEMHEIGHT, nIndex as WPARAM, MAKELONG(cyItemHeight as WORD, 0) as LPARAM) as c_int } pub fn GetExtendedUI(&self)->BOOL { self.inner.assert_window(); self.inner.SendMessage( CB_GETEXTENDEDUI, 0, 0) as BOOL } pub fn SetExtendedUI (&self,bExtended: BOOL)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_SETEXTENDEDUI, bExtended as WPARAM, 0) as c_int } pub fn GetDroppedControlRect(&self,lprect: LPRECT) { self.inner.assert_window(); self.inner.SendMessage( CB_GETDROPPEDCONTROLRECT, 0, lprect as LPARAM); } pub fn GetDroppedState(&self)->BOOL { self.inner.assert_window(); self.inner.SendMessage( CB_GETDROPPEDSTATE, 0, 0) as BOOL } //#if (_WIN32_WINNT >= 0x0501) pub fn GetMinVisible(&self)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_GETMINVISIBLE, 0, 0) as c_int } pub fn SetMinVisible(&self,nMinVisible: c_int)->BOOL { self.inner.assert_window(); self.inner.SendMessage( CB_SETMINVISIBLE, nMinVisible as WPARAM, 0) as BOOL } // Vista only pub fn GetCueBannerText(&self,lpwText: LPWSTR, cchText: c_int)->BOOL { //#ifndef CB_GETCUEBANNER const CB_GETCUEBANNER:UINT = CBM_FIRST + 4; //#endif self.inner.assert_window(); self.inner.SendMessage( CB_GETCUEBANNER, lpwText as WPARAM, cchText as LPARAM) as BOOL } // Vista only pub fn SetCueBannerText(&self,lpcwText: LPCWSTR)->BOOL { //#ifndef CB_SETCUEBANNER const CB_SETCUEBANNER:UINT = CBM_FIRST + 3; //#endif self.inner.assert_window(); self.inner.SendMessage( CB_SETCUEBANNER, 0, lpcwText as LPARAM) as BOOL } //#endif // (_WIN32_WINNT >= 0x0501) // Operations pub fn InitStorage(&self,nItems: c_int, nBytes: UINT)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_INITSTORAGE, nItems as WPARAM, nBytes as LPARAM) as c_int } pub fn ResetContent(&self) { self.inner.assert_window(); self.inner.SendMessage( CB_RESETCONTENT, 0, 0); } // for edit control pub fn LimitText(&self,nMaxChars: c_int)->BOOL { self.inner.assert_window(); self.inner.SendMessage( CB_LIMITTEXT, nMaxChars as WPARAM, 0) as BOOL } // for drop-down combo boxes pub fn ShowDropDown (&self, bShowIt: BOOL) { self.inner.assert_window(); self.inner.SendMessage( CB_SHOWDROPDOWN, bShowIt as WPARAM, 0); } // manipulating listbox items // pub fn AddString(&self,lpszString: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_ADDSTRING, 0, lpszString as LPARAM) as c_int // } pub fn DeleteString(&self,nIndex: UINT)->c_int { self.inner.assert_window(); self.inner.SendMessage( CB_DELETESTRING, nIndex as WPARAM, 0) as c_int } // pub fn InsertString(&self,nIndex: c_int, lpszString: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_INSERTSTRING, nIndex, lpszString as LPARAM) as c_int // } //#ifndef _WIN32_WCE // pub fn Dir(&self,attr: UINT, lpszWildCard: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_DIR, attr, lpszWildCard as LPARAM) as c_int // } //#endif // !_WIN32_WCE // selection helpers // pub fn FindString(&self,nStartAfter: c_int, lpszString: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_FINDSTRING, nStartAfter, lpszString as LPARAM) as c_int // } // pub fn FindStringExact(&self,nIndexStart: c_int, lpszFind: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_FINDSTRINGEXACT, nIndexStart, lpszFind as LPARAM) as c_int // } // pub fn SelectString(&self,nStartAfter: c_int, lpszString: LPCTSTR)->c_int { // self.inner.assert_window(); // self.inner.SendMessage( CB_SELECTSTRING, nStartAfter, lpszString as LPARAM) as c_int // } // Clipboard operations pub fn Clear(&self) { self.inner.assert_window(); self.inner.SendMessage( WM_CLEAR, 0, 0); } pub fn Copy(&self) { self.inner.assert_window(); self.inner.SendMessage( WM_COPY, 0, 0); } pub fn Cut(&self) { self.inner.assert_window(); self.inner.SendMessage( WM_CUT, 0, 0); } pub fn Paste(&self) { self.inner.assert_window(); self.inner.SendMessage( WM_PASTE, 0, 0); } } //typedef CComboBoxT<ATL::CWindow> CComboBox; ///////////////////////////////////////////////////////// // expose all inner methods // impl CComboBox { // expose_cwindow!(); // }
{ CComboBox{ inner: CWindow::new(NULL_HWND), } }
test_junitxml.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id: $ import os import io import sys import unittest import tempfile import shutil junitxml = None ## Basic test of xmlresult functionality of reading gtest xml files and ## summarizing their results into a new file. class MockResult(): def __init__(self, directory, filename, suites = [], noSuitesRoot = False): self.filename = os.path.join(directory, filename) self.suites = suites # whether to suppress <testsuites> root node self.noSuitesRoot = noSuitesRoot class MockSuite(): def __init__(self, cases, name, tests = 0, errors = 0, fail = 0, time = 1): self.cases = cases self.tests = tests self.time = time self.fail = fail self.errors = errors self.name = name class MockCase(): def __init__(self, name, errorList = [], classname="", time = 1): self.classname = classname self.name = name self.time = time self.errorList = errorList class MockErrorType(Exception): def __init__(self, value, etype = ''): self.value = value self.__name__ = value self.type = etype def _writeMockResultFile(result): "writes a test result as a gtest compatible test runner would do" with open(result.filename, 'w') as f: f.write('<?xml version="1.0" encoding="UTF-8"?>\n') if len(result.suites) > 1 or result.noSuitesRoot == False: f.write('<testsuites>\n') for suite in result.suites: f.write('<testsuite tests="'+str(suite.tests)+'" failures="'+str(suite.fail)+'" time="'+str(suite.time)+'" errors="'+str(suite.errors)+'" name="'+suite.name+'">\n') for case in suite.cases: f.write('<testcase name="'+case.name+'" status="run" time="'+str(case.time)+'" classname="'+case.classname+'">\n') for error in case.errorList: f.write('<failure message="'+error.value+'" type="'+error.value+'"/>\n') f.write('</testcase>\n') f.write('</testsuite>\n') if len(result.suites) > 1 or result.noSuitesRoot == False: f.write('</testsuites>\n') class XmlResultTestGeneration(unittest.TestCase): def setUp(self): global junitxml if junitxml is None: import rosunit.junitxml junitxml = rosunit.junitxml def tearDown(self): pass def testGenerateError(self): error = junitxml.TestError('error_type', 'error_text') error_str = error.xml() self.assertEquals(b'''<error type="error_type">&lt;![CDATA[ error_text ]]&gt;</error>''', error_str) def testGenerateFailure(self): failure = junitxml.TestFailure('failure_type', 'failure_text') failure_str = failure.xml() self.assertEquals(b'''<failure type="failure_type">&lt;![CDATA[ failure_text ]]&gt;</failure>''', failure_str) def testGenerateTestCaseResult(self): testcase = junitxml.TestCaseResult('test_case') error = junitxml.TestError('error_type', 'error_text') error_str = error.xml() failure = junitxml.TestFailure('failure_type', 'failure_text') failure_str = failure.xml() testcase.add_error(error) testcase.add_failure(failure)
failure_text ]]&gt;</failure><error type="error_type">&lt;![CDATA[ error_text ]]&gt;</error></testcase>''', testcase_str) class XmlResultTestRead(unittest.TestCase): def setUp(self): # lazy-import to get coverage global junitxml if junitxml is None: import rosunit.junitxml junitxml = rosunit.junitxml self.directory = tempfile.mkdtemp() # setting up mock results as dict so results can be checked individually self.mockresults={ "empty": MockResult(self.directory, "empty.xml", []), "emptysuite": MockResult(self.directory, "emptysuite.xml", [MockSuite([], "emptySuite", 0, 0, 0, 0)]), "succ1": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)]), "err1": MockResult(self.directory, "err1.xml", [MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1)]), "fail1": MockResult(self.directory, "fail1.xml", [MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]), "noroot": MockResult(self.directory, "succ1.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1)], noSuitesRoot = True), "multicase": MockResult(self.directory, "multicase.xml", [MockSuite([MockCase("succCase"), MockCase("errCase"), MockCase("failCase")], "succ1suite", 3, 1, 1, time = 3)]), "multisuite": MockResult(self.directory, "multisuite.xml", [MockSuite([MockCase("succCase")],"succ1suite", 1, 0, 0, 1), MockSuite([MockCase("errCase")],"err1suite", 1, 1, 0, 1), MockSuite([MockCase("failCase")],"fail1suite", 1, 0, 1, 1)]) } for name, result in self.mockresults.items(): _writeMockResultFile(result) def tearDown(self): shutil.rmtree(self.directory) #pass def testReadNoSuites(self): result = junitxml.read(self.mockresults["empty"].filename, "fooname") self.assert_(result is not None) self.assertEquals(0.0, result.time) self.assertEquals(0, result.num_tests) self.assertEquals(0, result.num_errors) self.assertEquals(0, result.num_failures) def testReadEmptySuite(self): result = junitxml.read(self.mockresults["emptysuite"].filename, "fooname") self.assert_(result is not None) self.assertEquals(0.0, result.time) self.assertEquals(0, result.num_tests) self.assertEquals(0, result.num_errors) self.assertEquals(0, result.num_failures) def testReadSuccess(self): result = junitxml.read(self.mockresults["succ1"].filename, "fooname") self.assert_(result is not None) self.assertEquals(1.0, result.time) self.assertEquals(1, result.num_tests) self.assertEquals(0, result.num_errors) self.assertEquals(0, result.num_failures) def testReadError(self): result = junitxml.read(self.mockresults["err1"].filename, "fooname") self.assert_(result is not None) self.assertEquals(1.0, result.time) self.assertEquals(1, result.num_tests) self.assertEquals(1, result.num_errors) self.assertEquals(0, result.num_failures) def testReadFail(self): result = junitxml.read(self.mockresults["fail1"].filename, "fooname") self.assert_(result is not None) self.assertEquals(1.0, result.time) self.assertEquals(1, result.num_tests) self.assertEquals(0, result.num_errors) self.assertEquals(1, result.num_failures) def testReadMulticase(self): result = junitxml.read(self.mockresults["multicase"].filename, "fooname") self.assert_(result is not None) self.assertEquals(3.0, result.time) self.assertEquals(3, result.num_tests) self.assertEquals(1, result.num_errors) self.assertEquals(1, result.num_failures) def testReadMultisuite(self): result = junitxml.read(self.mockresults["multisuite"].filename, "fooname") self.assert_(result is not None) self.assertEquals(3.0, result.time) self.assertEquals(3, result.num_tests) self.assertEquals(1, result.num_errors) self.assertEquals(1, result.num_failures)
testcase_str = testcase.xml() self.assertEquals(b'''<testcase classname="" name="test_case" time="0.0"><failure type="failure_type">&lt;![CDATA[
SUN_def.py
from sympy import sqrt, Symbol,symbols,conjugate,I,flatten,simplify,expand from numpy import array,arange,triu,tril,nonzero,append,unique, vectorize,sum,prod from ..util import MatrixProd,Deriv,Tuples def GetAssumptions(Sym,assL): tmpA=[] for i in assL: try: tmpA.append(Sym.assumptions0[i] ) except: tmpA.append(None ) return tmpA def Definitions(DimN, Gauge,Diag=False): global gauge, dimN dimN,gauge=DimN,Gauge global sqrt2,dimRange, mPhi2, mPhip2, v, vPhi, muH, lamH, lamHPhi, lamPhi mPhi2=array( symbols('mPhi2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) mPhi2[dimN-1][dimN-1]=Symbol('mPhi2{}{}'.format(dimN,dimN),real=True )#this is real, due to the minimization conditions mPhip2=array( symbols('mPhip2(1:{})(1:{})'.format(str(dimN+1),str(dimN+1)),complex=True,real=False ) ).reshape(dimN,dimN) #make mPhi symmetric (faster than numpy.triu(mPhi,+1).T+numpy.triu(mPhi)) for i in range(dimN): for j in range(i+1,dimN): mPhi2[j][i]=mPhi2[i][j] #make mPhip hermitian (faster than numpyconjugate(numpy.triu(mPhi,+1).T)+numpy.triu(mPhi)) for i in range(dimN): for j in range(i+1,dimN): mPhip2[j][i]=conjugate(mPhip2[i][j]) #make the diagonal real. keep in mind that the squared elements of the diagonal are real. #So the elements can be either real or imaginary for i in range(dimN): exec( 'mPhip2[{}][{}]=Symbol( \'mPhip2{}{}\' ,real=True)'.format(str(i),str(i),str(i+1),str(i+1)) ) tmpMPHI=(triu(mPhi2)).reshape(dimN**2) ParameterSymbols= array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] ) tmpMPHI=(triu(mPhip2)).reshape(dimN**2) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) )\ for i in nonzero(tmpMPHI)[0]] ) ) del tmpMPHI sqrt2=sqrt(2); if Diag: global Oh11,Oh12, MH,MS0,MG if gauge!='un': Fields=array( symbols('H S0 G1:{} G0 Gp Gm'.format(2*dimN) ) ) else: Fields=array( symbols('H S0 G1:{}'.format(2*dimN) ) ) MH,MS0 = symbols('MH MS0 ',real=True,positive=True) MG = symbols('MG1:{}'.format(2*dimN),real=True,positive=True) tmpMPHI=[MH,MS0]+list(MG) ParameterSymbols=append(ParameterSymbols, array( [ (tmpMPHI[i], GetAssumptions(tmpMPHI[i],['complex','real','positive'] ) ) \ for i in nonzero(tmpMPHI)[0]] )) del tmpMPHI Oh11,Oh12=symbols('Oh11 Oh12',real=True) v=Symbol('v',positive=True); vPhi=Symbol('vPhi',positive=True); muH=Symbol('muH'); lamH=Symbol('lamH',real=True,positive=True); lamHPhi=Symbol('lamHPhi',real=True,positive=None); lamPhi=Symbol('lamPhi',real=True,positive=True); ParameterSymbols=append(ParameterSymbols, array( [\ (Oh11,GetAssumptions(Oh11,['complex','real','positive'] )),\ (Oh12,GetAssumptions(Oh12,['complex','real','positive'] )),\ (v,GetAssumptions(v,['complex','real','positive'] )),\ (vPhi,GetAssumptions(vPhi,['complex','real','positive'] )),\ (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) return Fields,ParameterSymbols else: global Gp, H0, Gm, H0t, h, G0, H, Ht, Phi, Phit, chi, rho, phi, s global subsvev, subsexpand dimRange=arange(1,dimN+1); dimRangeM=range(dimN-1) Phi = symbols('Phi1:{}'.format(str(dimN+1))) Phit = symbols('Phi1:{}t'.format(str(dimN+1))) if gauge=='un': H0, H0t=symbols('H0, H0t') H = [0,H0]; Ht = [0, H0t]; else: H0,H0t,Gp,Gm,G0=symbols('H0,H0t,Gp,Gm,G0') H = [Gp,H0]; Ht = [Gm, H0t]; ##################--Declare symbols for expaned scalars phi = list(symbols('phi1:{}'.format(str(dimN)))) s = list(symbols('s1:{}'.format(str(dimN)))) h , chi, rho=symbols('h chi rho')
v=Symbol('v',positive=True); vPhi=Symbol('vPhi',positive=True); muH=Symbol('muH'); lamH=Symbol('lamH',real=True,positive=True); lamHPhi=Symbol('lamHPhi',real=True,positive=None); lamPhi=Symbol('lamPhi',real=True,positive=True); ParameterSymbols=append(ParameterSymbols, array( [\ (v,GetAssumptions(v,['complex','real','positive'] )),\ (vPhi,GetAssumptions(vPhi,['complex','real','positive'] )),\ (lamH,GetAssumptions(lamH,['complex','real','positive'] )),\ (lamHPhi,GetAssumptions(lamHPhi,['complex','real','positive'] )),\ (lamPhi,GetAssumptions(lamPhi,['complex','real','positive'] ))])) #Expand the fields at their vevs if gauge=='un': subsexpand =array(\ [(H0,(h+v)/sqrt2 ),(H0t,(h+v)/sqrt2 ),\ (Phi[dimN-1],(rho+ I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2 ) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) else: subsexpand = array(\ [(H0,(h+I*G0+v)/sqrt2 ),(H0t,(h-I*G0+v)/sqrt2 ),\ (Phi[dimN-1], (rho+I*chi+vPhi)/sqrt2 ),\ (Phit[dimN-1],(rho-I*chi+vPhi)/sqrt2 )]+ \ [(Phi[i], (phi[i]+I*s[i])/sqrt2) for i in dimRangeM]+\ [(Phit[i],(phi[i]-I*s[i])/sqrt2) for i in dimRangeM]) Fields=array(flatten([h,rho,s,chi,phi,G0,Gp,Gm])) subsvev = array(\ [(H0,v/sqrt2 ),(H0t,v/sqrt2 ),\ (G0,0),(Gm,0),(Gp,0),\ (Phi[dimN-1], vPhi/sqrt2 ),\ (Phit[dimN-1],vPhi/sqrt2 )]+ \ [(Phi[i], 0) for i in dimRangeM]+\ [(Phit[i],0) for i in dimRangeM]) return list(Fields),ParameterSymbols def GetLagrangian(AllFields=False,Diag=False): if Diag==False: mPhi2C=[[conjugate(i) for i in x] for x in mPhi2] V0=-muH**2/2*MatrixProd([H,Ht])+lamH/2*MatrixProd([H,Ht])**2+lamPhi/2*MatrixProd([Phi,Phit])**2\ +lamHPhi*MatrixProd([H,Ht])*MatrixProd([Phi,Phit] ); Vsoft=MatrixProd([Phi,mPhi2,Phi])+MatrixProd([Phit,mPhi2C,Phit])+MatrixProd([Phit,mPhip2,Phi]) V=(V0+Vsoft)#.subs(subsexpand) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] constV=simplify((V.subs(subsmin).subs(subsvev)) ) if AllFields!=False: try: CheckMinimizations(AllFields,V, constV, subsmin) except: print 'Something went wrong while checking the minimization. \nHave you passed the fields correctly? ' LMassInt = -( (V.subs(subsmin)).subs(subsexpand) -constV ); return LMassInt else: FHS=array(AllFields[:2]) FG=array(AllFields[2:2*dimN+1]) #h=H*Oh11 - Oh12*S0 hH=Oh11*FHS[0]-Oh12*FHS[1] #------------------------- #rho=H*Oh12 + Oh11*S0 RHO=Oh12*FHS[0]+Oh11*FHS[1] #-------------------------- Phit_times_Phi= (MatrixProd([FG,FG]) + (vPhi+RHO)**2)/2 if gauge=='un': HD=1/sqrt2*array([0,hH+v]) HDt=HD Gsm=array([0,0,0]) else: Gsm=array(AllFields[2*dimN+1:]) HD=array([Gsm[1],1/sqrt2*(hH+v+I*Gsm[0])]) HDt=array([Gsm[2],1/sqrt2*(hH+v-I*Gsm[0])]) subsmin= [ (mPhi2[i][dimN-1], -mPhip2[dimN-1][i]/2 ) for i in range(0,dimN-1)]+ \ [(muH, sqrt(v**2*lamH + vPhi**2*lamHPhi)),\ (lamPhi,-(lamHPhi*v**2 + 2*mPhi2[dimN-1][dimN-1] + 2*mPhip2[dimN-1][dimN-1] + 2*conjugate(mPhi2[dimN-1][dimN-1]))/vPhi**2),\ (conjugate(mPhi2[dimN-1][dimN-1]),mPhi2[dimN-1][dimN-1] )] L_int=-(lamH/2*(MatrixProd([HD,HDt])**2 )+lamPhi/2*(Phit_times_Phi**2 )\ +lamHPhi*MatrixProd([HD,HDt])*Phit_times_Phi) #Remove linear interactions (it is minimized!) Subs0=[(i,0) for i in AllFields] L_const=-lamH*v**4/8 - lamHPhi*v**2*vPhi**2/4 - lamPhi*vPhi**4/8 Linear_terms=( -Oh11*lamH*v**3/2 - Oh11*lamHPhi*v*vPhi**2/2 - Oh12*lamHPhi*v**2*vPhi/2 - Oh12*lamPhi*vPhi**3/2 )*FHS[0]\ +(-Oh11*lamHPhi*v**2*vPhi/2 - Oh11*lamPhi*vPhi**3/2 + Oh12*lamH*v**3/2 + Oh12*lamHPhi*v*vPhi**2/2)*FHS[1] #Remove 2-point interactions (the mass) P2_terms=(\ (- Oh11**2*lamHPhi*v**2/2 - 3*Oh11**2*lamPhi*vPhi**2/2 + 2*Oh11*Oh12*lamHPhi*v*vPhi - 3*Oh12**2*lamH*v**2/2 - Oh12**2*lamHPhi*vPhi**2/2 )/2*FHS[1]**2\ +( -Oh11**2*lamHPhi*v*vPhi + 3*Oh11*Oh12*lamH*v**2/2 - Oh11*Oh12*lamHPhi*v**2/2 + Oh11*Oh12*lamHPhi*vPhi**2/2 - 3*Oh11*Oh12*lamPhi*vPhi**2/2 + Oh12**2*lamHPhi*v*vPhi)*FHS[0]*FHS[1]\ +(- 3*Oh11**2*lamH*v**2/2 - Oh11**2*lamHPhi*vPhi**2/2 - 2*Oh11*Oh12*lamHPhi*v*vPhi - Oh12**2*lamHPhi*v**2/2 - 3*Oh12**2*lamPhi*vPhi**2/2)/2*FHS[0]**2 -(lamH*v**2 +lamHPhi*vPhi**2)/4*Gsm[0]**2\ -( lamH*v**2 + lamHPhi*vPhi**2)/2*Gsm[2]*Gsm[1]\ )+\ ( MatrixProd([FG,FG]))*( - lamHPhi*v**2/2 - lamPhi*vPhi**2/2 )/2 #Include the mases (it is the diagonalized Lagrangian) L_mass=-(FHS[0]**2*MH**2 + FHS[1]**2*MS0**2)/2 -sum([FG[i-1]**2*MG[i-1]**2 for i in range(1,2*dimN) ])/2 return expand(L_int-Linear_terms-P2_terms- L_const).subs(subsmin)+L_mass global tmp2 def tmp2(i): if i[0]==i[1]: f=1/2. else: f=1 return f*prod(i)*Deriv(L,i).subs(Subs0) def CheckMinimizations(AllFields,V, constV, subsmin):#uses only global subs0=[ (i,0) for i in AllFields] print 'Checking vanishing of the first derivatives of the potential...' minV=unique(map(lambda i: \ simplify(Deriv(V.subs(subsexpand),i ).subs(subs0).subs(subsmin) ),AllFields)) if (minV==0).all(): print 'The conditions are correct!' else: print 'The potential is not minimized correctlly...'
get.go
package commands import ( "compress/gzip" "errors" "fmt" "io" "os" "path/filepath" "strings" core "github.com/ipfs/go-ipfs/core" cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv" e "github.com/ipfs/go-ipfs/core/commands/e" "gx/ipfs/QmPTfgFTo9PFr1PvPKyKoeMgBvYPh6cX3aDP7DHKVbnCbi/go-ipfs-cmds" "gx/ipfs/QmPtj12fdwuAqj9sBSTNUxBNu8kCGNp8b3o8yUzMm5GHpq/pb" tar "gx/ipfs/QmQine7gvHncNevKtG9QXxf3nXcwSj6aDDmMm52mHofEEp/tar-utils" dag "gx/ipfs/QmRDaC5z6yXkXTTSWzaxs2sSVBon5RRCN6eNtMmpuHtKCr/go-merkledag" "gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit" path "gx/ipfs/QmTKaiDxQqVxmA1bRipSuP7hnTSgnMSmEa98NYeS6fcoiv/go-path" uarchive "gx/ipfs/QmVNEJ5Vk1e2G5kHMiuVbpD6VQZiK1oS6aWZKjcUQW7hEy/go-unixfs/archive" ) var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9") var GetCmd = &cmds.Command{ Helptext: cmdkit.HelpText{ Tagline: "Download IPFS objects.", ShortDescription: ` Stores to disk the data contained an IPFS or IPNS object(s) at the given path. By default, the output will be stored at './<ipfs-path>', but an alternate path can be specified with '--output=<path>' or '-o=<path>'. To output a TAR archive instead of unpacked files, use '--archive' or '-a'. To compress the output with GZIP compression, use '--compress' or '-C'. You may also specify the level of compression by specifying '-l=<1-9>'. `, }, Arguments: []cmdkit.Argument{ cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(), }, Options: []cmdkit.Option{ cmdkit.StringOption("output", "o", "The path where the output should be stored."), cmdkit.BoolOption("archive", "a", "Output a TAR archive."), cmdkit.BoolOption("compress", "C", "Compress the output with GZIP compression."), cmdkit.IntOption("compression-level", "l", "The level of compression (1-9)."), }, PreRun: func(req *cmds.Request, env cmds.Environment) error { _, err := getCompressOptions(req) return err }, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) { cmplvl, err := getCompressOptions(req) if err != nil { res.SetError(err, cmdkit.ErrNormal) return } node, err := cmdenv.GetNode(env) if err != nil { res.SetError(err, cmdkit.ErrNormal) return } p := path.Path(req.Arguments[0]) ctx := req.Context dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p) if err != nil { res.SetError(err, cmdkit.ErrNormal) return } switch dn := dn.(type) { case *dag.ProtoNode: size, err := dn.Size() if err != nil { res.SetError(err, cmdkit.ErrNormal) return } res.SetLength(size) case *dag.RawNode: res.SetLength(uint64(len(dn.RawData()))) default: res.SetError(err, cmdkit.ErrNormal) return } archive, _ := req.Options["archive"].(bool) reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl) if err != nil { res.SetError(err, cmdkit.ErrNormal) return } res.Emit(reader) }, PostRun: cmds.PostRunMap{ cmds.CLI: func(req *cmds.Request, re cmds.ResponseEmitter) cmds.ResponseEmitter { reNext, res := cmds.NewChanResponsePair(req) go func() { defer re.Close() v, err := res.Next() if !cmds.HandleError(err, res, re) { return } outReader, ok := v.(io.Reader) if !ok { log.Error(e.New(e.TypeErr(outReader, v))) return } outPath := getOutPath(req) cmplvl, err := getCompressOptions(req) if err != nil { re.SetError(err, cmdkit.ErrNormal) return } archive, _ := req.Options["archive"].(bool) gw := getWriter{ Out: os.Stdout, Err: os.Stderr, Archive: archive, Compression: cmplvl, Size: int64(res.Length()), } if err := gw.Write(outReader, outPath); err != nil { re.SetError(err, cmdkit.ErrNormal) } }() return reNext }, }, } type clearlineReader struct { io.Reader out io.Writer } func (r *clearlineReader) Read(p []byte) (n int, err error) { n, err = r.Reader.Read(p) if err == io.EOF { // callback fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF } return } func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader)
func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar { // setup bar reader // TODO: get total length of files bar := pb.New64(l).SetUnits(pb.U_BYTES) bar.Output = out // the progress bar lib doesn't give us a way to get the width of the output, // so as a hack we just use a callback to measure the output, then git rid of it bar.Callback = func(line string) { terminalWidth := len(line) bar.Callback = nil log.Infof("terminal width: %v\n", terminalWidth) } return bar } func getOutPath(req *cmds.Request) string { outPath, _ := req.Options["output"].(string) if outPath == "" { trimmed := strings.TrimRight(req.Arguments[0], "/") _, outPath = filepath.Split(trimmed) outPath = filepath.Clean(outPath) } return outPath } type getWriter struct { Out io.Writer // for output to user Err io.Writer // for progress bar output Archive bool Compression int Size int64 } func (gw *getWriter) Write(r io.Reader, fpath string) error { if gw.Archive || gw.Compression != gzip.NoCompression { return gw.writeArchive(r, fpath) } return gw.writeExtracted(r, fpath) } func (gw *getWriter) writeArchive(r io.Reader, fpath string) error { // adjust file name if tar if gw.Archive { if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") { fpath += ".tar" } } // adjust file name if gz if gw.Compression != gzip.NoCompression { if !strings.HasSuffix(fpath, ".gz") { fpath += ".gz" } } // create file file, err := os.Create(fpath) if err != nil { return err } defer file.Close() fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath) bar, barR := progressBarForReader(gw.Err, r, gw.Size) bar.Start() defer bar.Finish() _, err = io.Copy(file, barR) return err } func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error { fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath) bar := makeProgressBar(gw.Err, gw.Size) bar.Start() defer bar.Finish() defer bar.Set64(gw.Size) extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64} return extractor.Extract(r) } func getCompressOptions(req *cmds.Request) (int, error) { cmprs, _ := req.Options["compress"].(bool) cmplvl, cmplvlFound := req.Options["compression-level"].(int) switch { case !cmprs: return gzip.NoCompression, nil case cmprs && !cmplvlFound: return gzip.DefaultCompression, nil case cmprs && (cmplvl < 1 || cmplvl > 9): return gzip.NoCompression, ErrInvalidCompressionLevel } return cmplvl, nil }
{ bar := makeProgressBar(out, l) barR := bar.NewProxyReader(r) return bar, &clearlineReader{barR, out} }
options.go
package models import ( "net" "strings" "text/template" ) type modelOptions struct { nameTemplate string nameFunc NameFunc } // ModelOption defines function type which sets model options. type ModelOption func(*modelOptions) // NameFunc represents function which can name model instance. type NameFunc func(obj interface{}) (string, error) // WithNameTemplate returns option for models which sets function // for generating name of instances using custom template. func WithNameTemplate(t string) ModelOption { return func(opts *modelOptions) { opts.nameFunc = NameTemplate(t) opts.nameTemplate = t } } const namedTemplate = `{{.Name}}` type named interface { GetName() string } func
(t string) NameFunc { tmpl := template.Must( template.New("name").Funcs(funcMap).Option("missingkey=error").Parse(t), ) return func(obj interface{}) (string, error) { var s strings.Builder if err := tmpl.Execute(&s, obj); err != nil { return "", err } return s.String(), nil } } var funcMap = template.FuncMap{ "ip": func(s string) string { ip := net.ParseIP(s) if ip == nil { return "<invalid>" } return ip.String() }, "protoip": func(s string) string { ip := net.ParseIP(s) if ip == nil { return "<invalid>" } if ip.To4() == nil { return "IPv6" } return "IPv4" }, "ipnet": func(s string) map[string]interface{} { if strings.HasPrefix(s, "alloc:") { // reference to IP address allocated via netalloc return nil } _, ipNet, err := net.ParseCIDR(s) if err != nil { return map[string]interface{}{ "IP": "<invalid>", "MaskSize": 0, "AllocRef": "", } } maskSize, _ := ipNet.Mask.Size() return map[string]interface{}{ "IP": ipNet.IP.String(), "MaskSize": maskSize, "AllocRef": "", } }, }
NameTemplate
main.rs
use std::env; use std::process::Command; use std::thread; use std::thread::JoinHandle; use std::collections::HashMap; use std::io::{self, Write}; #[derive(Debug)] struct
{ act: Action, sp: BoolOrThread } impl SousProcessus { fn creer( sp: BoolOrThread, act: Action ) -> Self { SousProcessus { act: act, sp: sp } } } #[derive(Debug)] enum BoolOrThread { Bool(bool), Thread(JoinHandle<bool>) } #[derive(Debug)] struct Action { contexte: String, arguments: Vec<String>, environnement: HashMap<String, String> } impl Action { fn creer( contexte: String ) -> Self { Action { contexte: contexte, arguments: Vec::new(), environnement: HashMap::new() } } fn tester( &self ) -> bool { self.arguments.len() > 0 && self.contexte != "".to_string() } fn superviser( &mut self, env_global: &Vec<(String, String)> ) -> BoolOrThread { for (cle, valeur) in env_global.iter() { self.environnement.insert( cle.clone(), valeur.clone(), ); } let env_local = self.environnement.iter().fold( Vec::<(String, String)>::new(), | mut vec, (cle, valeur) | { vec.push( ( cle.clone(), valeur.clone() ) ); vec } ); return match self.contexte.as_str() { ":print" => { println!( ">>> {:}", self.reduction() ); BoolOrThread::Bool( true ) }, ":log" => BoolOrThread::Thread( executer_log( env_local, self.arguments.to_vec().into_iter().map( | c | { c.to_string() } ).collect() ) ), ":bash" => BoolOrThread::Thread( executer_bash( env_local, self.reduction() ) ), ":cmd" => BoolOrThread::Thread( executer_commande( env_local, self.arguments.to_vec().into_iter().map( | c | { c.to_string() } ).collect() ) ), _ => panic!( "contexte '{:?}' non implémenté", self.contexte ), } } fn reduction( &self ) -> String { return self.arguments.iter().fold( String::new(), | a, b | return a+b+" " ); } } fn executer_log_env( env: &Vec<(String, String)> ) { env.iter().map( | (cle, valeur) | { println!("{:}={:}", cle, valeur); } ).for_each(drop); } fn executer_log( environnement: Vec<(String, String)>, parties: Vec<String> ) -> JoinHandle<bool> { return thread::spawn( move || { for partie in parties { match partie.as_str() { "env" => executer_log_env( &environnement ), _ => panic!("action de log invalide : {:?}", partie) } } return true } ) } fn executer_bash( environnement: Vec<(String, String)>, commande: String ) -> JoinHandle<bool> { executer_commande( environnement, vec!( match env::var( "SHELL" ) { Ok( shell ) => shell, Err( _ ) => "bash".to_string(), }, "-c".to_string(), commande ) ) } fn executer_commande( environnement: Vec<(String, String)>, args: Vec<String> ) -> JoinHandle<bool> { return thread::spawn( move || { let mut a = args.iter(); let mut sp = Command::new( a.next().unwrap() ); sp.env_clear(); sp.envs( env::vars().filter( |&(ref k, _) | k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH" ).collect::<HashMap<String, String>>() ); for (cle, valeur) in environnement { sp.env( cle, valeur ); } for arg in a { sp.arg( arg ); } match sp.output() { Ok( output ) => { io::stdout().write_all(&output.stdout).unwrap(); io::stderr().write_all(&output.stderr).unwrap(); output.status.success() } Err( _ ) => false, } } ); } fn var_env_traduire( chaine: &String ) -> (String, String) { let paire = chaine.splitn( 2, '=' ).collect::<Vec<&str>>(); if paire.len() == 1 { return ( chaine.to_string(), "".to_string() ); } else { return ( paire[0].to_string(), paire[1].to_string() ); } } fn main() { let mut environnement_global: Vec<(String, String)> = env::vars().fold( Vec::<(String, String)>::new(), | mut vec, (cle, valeur) | { vec.push( ( cle.clone(), valeur.clone() ) ); vec } ); let mut sous_processus = Vec::<SousProcessus>::new(); let args: Vec<String> = env::args().collect(); let mut action = Action::creer( "".to_string() ); let mut args_iter = args.iter().enumerate(); loop { match args_iter.next() { Some( (i, arg) ) => { if i == 0 { continue; } match arg.chars().next() { Some( ':' ) => match arg.as_str() { ":env" => { if action.tester() { sous_processus.push( SousProcessus::creer( action.superviser( &environnement_global ), action ) ); } action = Action::creer( "".to_string() ); match args_iter.next() { Some( (_, e) ) => environnement_global.push( var_env_traduire( e ) ), None => panic!("demande de déf d'env sans valeur") } } _ => { if action.tester() { sous_processus.push( SousProcessus::creer( action.superviser( &environnement_global ), action ) ); } action = Action::creer( arg.to_string() ); } }, _ => action.arguments.push( arg.to_string() ) } } None => break } } if action.tester() { sous_processus.push( SousProcessus::creer( action.superviser( &environnement_global ), action ) ); } std::process::exit( match sous_processus.into_iter().fold( true, | etat, sous_processus | { match sous_processus.sp { BoolOrThread::Thread( t ) => { match t.join() { Ok( r ) => etat && r, Err( _ ) => false } }, BoolOrThread::Bool( r ) => etat && r } } ) { true => 0, false => 1 } ); }
SousProcessus
models.go
// +build go1.9 // Copyright 2020 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This code was auto-generated by: // github.com/test-repo-arcturus/azure-sdk-for-go/tools/profileBuilder package labservices import ( "context" original "github.com/test-repo-arcturus/azure-sdk-for-go/services/labservices/mgmt/2018-10-15/labservices" ) const ( DefaultBaseURI = original.DefaultBaseURI ) type AddRemove = original.AddRemove const ( Add AddRemove = original.Add Remove AddRemove = original.Remove ) type ConfigurationState = original.ConfigurationState const ( Completed ConfigurationState = original.Completed NotApplicable ConfigurationState = original.NotApplicable ) type LabUserAccessMode = original.LabUserAccessMode const ( Open LabUserAccessMode = original.Open Restricted LabUserAccessMode = original.Restricted ) type ManagedLabVMSize = original.ManagedLabVMSize const ( Basic ManagedLabVMSize = original.Basic Performance ManagedLabVMSize = original.Performance Standard ManagedLabVMSize = original.Standard ) type PublishingState = original.PublishingState const ( Draft PublishingState = original.Draft Published PublishingState = original.Published PublishFailed PublishingState = original.PublishFailed Publishing PublishingState = original.Publishing Scaling PublishingState = original.Scaling ) type AddUsersPayload = original.AddUsersPayload type BaseClient = original.BaseClient type CloudError = original.CloudError type CloudErrorBody = original.CloudErrorBody type CreateLabProperties = original.CreateLabProperties type Environment = original.Environment type EnvironmentDetails = original.EnvironmentDetails type EnvironmentFragment = original.EnvironmentFragment type EnvironmentOperationsPayload = original.EnvironmentOperationsPayload type EnvironmentProperties = original.EnvironmentProperties type EnvironmentPropertiesFragment = original.EnvironmentPropertiesFragment type EnvironmentSetting = original.EnvironmentSetting type EnvironmentSettingCreationParameters = original.EnvironmentSettingCreationParameters type EnvironmentSettingFragment = original.EnvironmentSettingFragment type EnvironmentSettingProperties = original.EnvironmentSettingProperties type EnvironmentSettingPropertiesFragment = original.EnvironmentSettingPropertiesFragment type EnvironmentSettingsClient = original.EnvironmentSettingsClient type EnvironmentSettingsCreateOrUpdateFuture = original.EnvironmentSettingsCreateOrUpdateFuture type EnvironmentSettingsDeleteFuture = original.EnvironmentSettingsDeleteFuture type EnvironmentSettingsStartFuture = original.EnvironmentSettingsStartFuture type EnvironmentSettingsStopFuture = original.EnvironmentSettingsStopFuture type EnvironmentSize = original.EnvironmentSize type EnvironmentSizeFragment = original.EnvironmentSizeFragment type EnvironmentsClient = original.EnvironmentsClient type EnvironmentsDeleteFuture = original.EnvironmentsDeleteFuture type EnvironmentsResetPasswordFuture = original.EnvironmentsResetPasswordFuture type EnvironmentsStartFuture = original.EnvironmentsStartFuture type EnvironmentsStopFuture = original.EnvironmentsStopFuture type GalleryImage = original.GalleryImage type GalleryImageFragment = original.GalleryImageFragment type GalleryImageProperties = original.GalleryImageProperties type GalleryImagePropertiesFragment = original.GalleryImagePropertiesFragment type GalleryImageReference = original.GalleryImageReference type GalleryImageReferenceFragment = original.GalleryImageReferenceFragment type GalleryImagesClient = original.GalleryImagesClient type GetEnvironmentResponse = original.GetEnvironmentResponse type GetPersonalPreferencesResponse = original.GetPersonalPreferencesResponse type GetRegionalAvailabilityResponse = original.GetRegionalAvailabilityResponse type GlobalUsersClient = original.GlobalUsersClient type GlobalUsersResetPasswordFuture = original.GlobalUsersResetPasswordFuture type GlobalUsersStartEnvironmentFuture = original.GlobalUsersStartEnvironmentFuture type GlobalUsersStopEnvironmentFuture = original.GlobalUsersStopEnvironmentFuture type Lab = original.Lab type LabAccount = original.LabAccount type LabAccountFragment = original.LabAccountFragment type LabAccountProperties = original.LabAccountProperties type LabAccountPropertiesFragment = original.LabAccountPropertiesFragment type LabAccountsClient = original.LabAccountsClient type LabAccountsDeleteFuture = original.LabAccountsDeleteFuture type LabCreationParameters = original.LabCreationParameters type LabDetails = original.LabDetails type LabFragment = original.LabFragment type LabProperties = original.LabProperties type LabPropertiesFragment = original.LabPropertiesFragment type LabsClient = original.LabsClient type LabsDeleteFuture = original.LabsDeleteFuture type LatestOperationResult = original.LatestOperationResult type ListEnvironmentsPayload = original.ListEnvironmentsPayload type ListEnvironmentsResponse = original.ListEnvironmentsResponse type ListLabsResponse = original.ListLabsResponse type NetworkInterface = original.NetworkInterface type OperationBatchStatusPayload = original.OperationBatchStatusPayload type OperationBatchStatusResponse = original.OperationBatchStatusResponse type OperationBatchStatusResponseItem = original.OperationBatchStatusResponseItem type OperationError = original.OperationError type OperationMetadata = original.OperationMetadata type OperationMetadataDisplay = original.OperationMetadataDisplay type OperationResult = original.OperationResult type OperationStatusPayload = original.OperationStatusPayload type OperationStatusResponse = original.OperationStatusResponse type OperationsClient = original.OperationsClient type PersonalPreferencesOperationsPayload = original.PersonalPreferencesOperationsPayload type ProviderOperationResult = original.ProviderOperationResult type ProviderOperationResultIterator = original.ProviderOperationResultIterator type ProviderOperationResultPage = original.ProviderOperationResultPage type ProviderOperationsClient = original.ProviderOperationsClient type PublishPayload = original.PublishPayload type ReferenceVM = original.ReferenceVM type ReferenceVMCreationParameters = original.ReferenceVMCreationParameters type ReferenceVMFragment = original.ReferenceVMFragment type RegionalAvailability = original.RegionalAvailability type RegisterPayload = original.RegisterPayload type ResetPasswordPayload = original.ResetPasswordPayload type Resource = original.Resource type ResourceSet = original.ResourceSet type ResourceSetFragment = original.ResourceSetFragment type ResourceSettingCreationParameters = original.ResourceSettingCreationParameters type ResourceSettings = original.ResourceSettings type ResourceSettingsFragment = original.ResourceSettingsFragment type ResponseWithContinuationEnvironment = original.ResponseWithContinuationEnvironment type ResponseWithContinuationEnvironmentIterator = original.ResponseWithContinuationEnvironmentIterator type ResponseWithContinuationEnvironmentPage = original.ResponseWithContinuationEnvironmentPage type ResponseWithContinuationEnvironmentSetting = original.ResponseWithContinuationEnvironmentSetting type ResponseWithContinuationEnvironmentSettingIterator = original.ResponseWithContinuationEnvironmentSettingIterator type ResponseWithContinuationEnvironmentSettingPage = original.ResponseWithContinuationEnvironmentSettingPage type ResponseWithContinuationGalleryImage = original.ResponseWithContinuationGalleryImage type ResponseWithContinuationGalleryImageIterator = original.ResponseWithContinuationGalleryImageIterator type ResponseWithContinuationGalleryImagePage = original.ResponseWithContinuationGalleryImagePage type ResponseWithContinuationLab = original.ResponseWithContinuationLab type ResponseWithContinuationLabAccount = original.ResponseWithContinuationLabAccount type ResponseWithContinuationLabAccountIterator = original.ResponseWithContinuationLabAccountIterator type ResponseWithContinuationLabAccountPage = original.ResponseWithContinuationLabAccountPage type ResponseWithContinuationLabIterator = original.ResponseWithContinuationLabIterator type ResponseWithContinuationLabPage = original.ResponseWithContinuationLabPage type ResponseWithContinuationUser = original.ResponseWithContinuationUser type ResponseWithContinuationUserIterator = original.ResponseWithContinuationUserIterator type ResponseWithContinuationUserPage = original.ResponseWithContinuationUserPage type SizeAvailability = original.SizeAvailability type SizeConfigurationProperties = original.SizeConfigurationProperties type SizeConfigurationPropertiesFragment = original.SizeConfigurationPropertiesFragment type SizeInfo = original.SizeInfo type SizeInfoFragment = original.SizeInfoFragment type User = original.User type UserFragment = original.UserFragment type UserProperties = original.UserProperties type UserPropertiesFragment = original.UserPropertiesFragment type UsersClient = original.UsersClient type UsersDeleteFuture = original.UsersDeleteFuture type VMStateDetails = original.VMStateDetails type VirtualMachineDetails = original.VirtualMachineDetails func New(subscriptionID string) BaseClient { return original.New(subscriptionID) } func NewEnvironmentSettingsClient(subscriptionID string) EnvironmentSettingsClient { return original.NewEnvironmentSettingsClient(subscriptionID) } func NewEnvironmentSettingsClientWithBaseURI(baseURI string, subscriptionID string) EnvironmentSettingsClient { return original.NewEnvironmentSettingsClientWithBaseURI(baseURI, subscriptionID) } func NewEnvironmentsClient(subscriptionID string) EnvironmentsClient { return original.NewEnvironmentsClient(subscriptionID) } func NewEnvironmentsClientWithBaseURI(baseURI string, subscriptionID string) EnvironmentsClient { return original.NewEnvironmentsClientWithBaseURI(baseURI, subscriptionID) } func NewGalleryImagesClient(subscriptionID string) GalleryImagesClient { return original.NewGalleryImagesClient(subscriptionID) } func NewGalleryImagesClientWithBaseURI(baseURI string, subscriptionID string) GalleryImagesClient { return original.NewGalleryImagesClientWithBaseURI(baseURI, subscriptionID) } func NewGlobalUsersClient(subscriptionID string) GlobalUsersClient { return original.NewGlobalUsersClient(subscriptionID) } func NewGlobalUsersClientWithBaseURI(baseURI string, subscriptionID string) GlobalUsersClient { return original.NewGlobalUsersClientWithBaseURI(baseURI, subscriptionID) } func NewLabAccountsClient(subscriptionID string) LabAccountsClient { return original.NewLabAccountsClient(subscriptionID) } func NewLabAccountsClientWithBaseURI(baseURI string, subscriptionID string) LabAccountsClient { return original.NewLabAccountsClientWithBaseURI(baseURI, subscriptionID) } func NewLabsClient(subscriptionID string) LabsClient { return original.NewLabsClient(subscriptionID) } func NewLabsClientWithBaseURI(baseURI string, subscriptionID string) LabsClient { return original.NewLabsClientWithBaseURI(baseURI, subscriptionID) } func NewOperationsClient(subscriptionID string) OperationsClient { return original.NewOperationsClient(subscriptionID) } func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID) } func NewProviderOperationResultIterator(page ProviderOperationResultPage) ProviderOperationResultIterator { return original.NewProviderOperationResultIterator(page) } func NewProviderOperationResultPage(getNextPage func(context.Context, ProviderOperationResult) (ProviderOperationResult, error)) ProviderOperationResultPage { return original.NewProviderOperationResultPage(getNextPage) } func NewProviderOperationsClient(subscriptionID string) ProviderOperationsClient { return original.NewProviderOperationsClient(subscriptionID) } func
(baseURI string, subscriptionID string) ProviderOperationsClient { return original.NewProviderOperationsClientWithBaseURI(baseURI, subscriptionID) } func NewResponseWithContinuationEnvironmentIterator(page ResponseWithContinuationEnvironmentPage) ResponseWithContinuationEnvironmentIterator { return original.NewResponseWithContinuationEnvironmentIterator(page) } func NewResponseWithContinuationEnvironmentPage(getNextPage func(context.Context, ResponseWithContinuationEnvironment) (ResponseWithContinuationEnvironment, error)) ResponseWithContinuationEnvironmentPage { return original.NewResponseWithContinuationEnvironmentPage(getNextPage) } func NewResponseWithContinuationEnvironmentSettingIterator(page ResponseWithContinuationEnvironmentSettingPage) ResponseWithContinuationEnvironmentSettingIterator { return original.NewResponseWithContinuationEnvironmentSettingIterator(page) } func NewResponseWithContinuationEnvironmentSettingPage(getNextPage func(context.Context, ResponseWithContinuationEnvironmentSetting) (ResponseWithContinuationEnvironmentSetting, error)) ResponseWithContinuationEnvironmentSettingPage { return original.NewResponseWithContinuationEnvironmentSettingPage(getNextPage) } func NewResponseWithContinuationGalleryImageIterator(page ResponseWithContinuationGalleryImagePage) ResponseWithContinuationGalleryImageIterator { return original.NewResponseWithContinuationGalleryImageIterator(page) } func NewResponseWithContinuationGalleryImagePage(getNextPage func(context.Context, ResponseWithContinuationGalleryImage) (ResponseWithContinuationGalleryImage, error)) ResponseWithContinuationGalleryImagePage { return original.NewResponseWithContinuationGalleryImagePage(getNextPage) } func NewResponseWithContinuationLabAccountIterator(page ResponseWithContinuationLabAccountPage) ResponseWithContinuationLabAccountIterator { return original.NewResponseWithContinuationLabAccountIterator(page) } func NewResponseWithContinuationLabAccountPage(getNextPage func(context.Context, ResponseWithContinuationLabAccount) (ResponseWithContinuationLabAccount, error)) ResponseWithContinuationLabAccountPage { return original.NewResponseWithContinuationLabAccountPage(getNextPage) } func NewResponseWithContinuationLabIterator(page ResponseWithContinuationLabPage) ResponseWithContinuationLabIterator { return original.NewResponseWithContinuationLabIterator(page) } func NewResponseWithContinuationLabPage(getNextPage func(context.Context, ResponseWithContinuationLab) (ResponseWithContinuationLab, error)) ResponseWithContinuationLabPage { return original.NewResponseWithContinuationLabPage(getNextPage) } func NewResponseWithContinuationUserIterator(page ResponseWithContinuationUserPage) ResponseWithContinuationUserIterator { return original.NewResponseWithContinuationUserIterator(page) } func NewResponseWithContinuationUserPage(getNextPage func(context.Context, ResponseWithContinuationUser) (ResponseWithContinuationUser, error)) ResponseWithContinuationUserPage { return original.NewResponseWithContinuationUserPage(getNextPage) } func NewUsersClient(subscriptionID string) UsersClient { return original.NewUsersClient(subscriptionID) } func NewUsersClientWithBaseURI(baseURI string, subscriptionID string) UsersClient { return original.NewUsersClientWithBaseURI(baseURI, subscriptionID) } func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { return original.NewWithBaseURI(baseURI, subscriptionID) } func PossibleAddRemoveValues() []AddRemove { return original.PossibleAddRemoveValues() } func PossibleConfigurationStateValues() []ConfigurationState { return original.PossibleConfigurationStateValues() } func PossibleLabUserAccessModeValues() []LabUserAccessMode { return original.PossibleLabUserAccessModeValues() } func PossibleManagedLabVMSizeValues() []ManagedLabVMSize { return original.PossibleManagedLabVMSizeValues() } func PossiblePublishingStateValues() []PublishingState { return original.PossiblePublishingStateValues() } func UserAgent() string { return original.UserAgent() + " profiles/preview" } func Version() string { return original.Version() }
NewProviderOperationsClientWithBaseURI
version.rs
use crate::prelude::*; use indexmap::IndexMap; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{value::StrExt, value::StringExt, Dictionary, Signature, UntaggedValue}; pub mod shadow { include!(concat!(env!("OUT_DIR"), "/shadow.rs")); } pub struct Version; impl WholeStreamCommand for Version { fn name(&self) -> &str { "version" } fn signature(&self) -> Signature { Signature::build("version") } fn
(&self) -> &str { "Display Nu version." } fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { version(args) } fn examples(&self) -> Vec<Example> { vec![Example { description: "Display Nu version", example: "version", result: None, }] } } pub fn version(args: CommandArgs) -> Result<ActionStream, ShellError> { let tag = args.call_info.args.span; let mut indexmap = IndexMap::with_capacity(4); indexmap.insert( "version".to_string(), UntaggedValue::string(clap::crate_version!()).into_value(&tag), ); let branch: Option<&str> = Some(shadow::BRANCH).filter(|x| !x.is_empty()); if let Some(branch) = branch { indexmap.insert( "branch".to_string(), branch.to_pattern_untagged_value().into_value(&tag), ); } let short_commit: Option<&str> = Some(shadow::SHORT_COMMIT).filter(|x| !x.is_empty()); if let Some(short_commit) = short_commit { indexmap.insert( "short_commit".to_string(), short_commit.to_pattern_untagged_value().into_value(&tag), ); } let commit_hash: Option<&str> = Some(shadow::COMMIT_HASH).filter(|x| !x.is_empty()); if let Some(commit_hash) = commit_hash { indexmap.insert( "commit_hash".to_string(), commit_hash.to_pattern_untagged_value().into_value(&tag), ); } let commit_date: Option<&str> = Some(shadow::COMMIT_DATE).filter(|x| !x.is_empty()); if let Some(commit_date) = commit_date { indexmap.insert( "commit_date".to_string(), commit_date.to_pattern_untagged_value().into_value(&tag), ); } let build_os: Option<&str> = Some(shadow::BUILD_OS).filter(|x| !x.is_empty()); if let Some(build_os) = build_os { indexmap.insert( "build_os".to_string(), build_os.to_pattern_untagged_value().into_value(&tag), ); } let rust_version: Option<&str> = Some(shadow::RUST_VERSION).filter(|x| !x.is_empty()); if let Some(rust_version) = rust_version { indexmap.insert( "rust_version".to_string(), rust_version.to_pattern_untagged_value().into_value(&tag), ); } let rust_channel: Option<&str> = Some(shadow::RUST_CHANNEL).filter(|x| !x.is_empty()); if let Some(rust_channel) = rust_channel { indexmap.insert( "rust_channel".to_string(), rust_channel.to_pattern_untagged_value().into_value(&tag), ); } let cargo_version: Option<&str> = Some(shadow::CARGO_VERSION).filter(|x| !x.is_empty()); if let Some(cargo_version) = cargo_version { indexmap.insert( "cargo_version".to_string(), cargo_version.to_pattern_untagged_value().into_value(&tag), ); } let pkg_version: Option<&str> = Some(shadow::PKG_VERSION).filter(|x| !x.is_empty()); if let Some(pkg_version) = pkg_version { indexmap.insert( "pkg_version".to_string(), pkg_version.to_pattern_untagged_value().into_value(&tag), ); } let build_time: Option<&str> = Some(shadow::BUILD_TIME).filter(|x| !x.is_empty()); if let Some(build_time) = build_time { indexmap.insert( "build_time".to_string(), build_time.to_pattern_untagged_value().into_value(&tag), ); } let build_rust_channel: Option<&str> = Some(shadow::BUILD_RUST_CHANNEL).filter(|x| !x.is_empty()); if let Some(build_rust_channel) = build_rust_channel { indexmap.insert( "build_rust_channel".to_string(), build_rust_channel .to_pattern_untagged_value() .into_value(&tag), ); } indexmap.insert( "features".to_string(), features_enabled().join(", ").to_string_value_create_tag(), ); let value = UntaggedValue::Row(Dictionary::from(indexmap)).into_value(&tag); Ok(ActionStream::one(value)) } fn features_enabled() -> Vec<String> { let mut names = vec!["default".to_string()]; #[cfg(feature = "ctrlc")] { names.push("ctrlc".to_string()); } #[cfg(feature = "dirs")] { names.push("dirs".to_string()); } #[cfg(feature = "directories")] { names.push("directories".to_string()); } #[cfg(feature = "ptree")] { names.push("ptree".to_string()); } // #[cfg(feature = "rich-benchmark")] // { // names.push("rich-benchmark".to_string()); // } #[cfg(feature = "rustyline-support")] { names.push("rustyline".to_string()); } #[cfg(feature = "term")] { names.push("term".to_string()); } #[cfg(feature = "uuid_crate")] { names.push("uuid".to_string()); } #[cfg(feature = "which")] { names.push("which".to_string()); } #[cfg(feature = "zip")] { names.push("zip".to_string()); } #[cfg(feature = "clipboard-cli")] { names.push("clipboard-cli".to_string()); } #[cfg(feature = "trash-support")] { names.push("trash".to_string()); } // #[cfg(feature = "binaryview")] // { // names.push("binaryview".to_string()); // } // #[cfg(feature = "start")] // { // names.push("start".to_string()); // } // #[cfg(feature = "bson")] // { // names.push("bson".to_string()); // } // #[cfg(feature = "sqlite")] // { // names.push("sqlite".to_string()); // } // #[cfg(feature = "s3")] // { // names.push("s3".to_string()); // } // #[cfg(feature = "chart")] // { // names.push("chart".to_string()); // } // #[cfg(feature = "xpath")] // { // names.push("xpath".to_string()); // } // #[cfg(feature = "selector")] // { // names.push("selector".to_string()); // } // #[cfg(feature = "extra")] // { // names.push("extra".to_string()); // } // #[cfg(feature = "preserve_order")] // { // names.push("preserve_order".to_string()); // } // #[cfg(feature = "wee_alloc")] // { // names.push("wee_alloc".to_string()); // } // #[cfg(feature = "console_error_panic_hook")] // { // names.push("console_error_panic_hook".to_string()); // } names.sort(); names } #[cfg(test)] mod tests { use super::ShellError; use super::Version; #[test] fn examples_work_as_expected() -> Result<(), ShellError> { use crate::examples::test as test_examples; test_examples(Version {}) } }
usage
getter.go
package getter import ( "context" apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" ) // Unlike reconciler, webhook or CSI gRPC are one shot API, so they needs read-after-create consistency. // This provides us such semantics by reading api-server directly if the object is missing on the cache reader. type RetryMissingGetter struct { cacheReader client.Reader apiReader client.Reader } // NewRetryMissingGetter creates a RetryMissingGetter instance. func NewRetryMissingGetter(cacheReader client.Reader, apiReader client.Reader) *RetryMissingGetter { return &RetryMissingGetter{ cacheReader: cacheReader, apiReader: apiReader, } } // Get tries cache reader, then if it returns NotFound error, retry direct reader. func (r *RetryMissingGetter) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error { err := r.cacheReader.Get(ctx, key, obj) if err == nil { return nil } if !apierrors.IsNotFound(err)
return r.apiReader.Get(ctx, key, obj) }
{ return err }
asyncio4.py
import asyncio async def sleep_task(num):
loop = asyncio.get_event_loop() task_list = [loop.create_task(sleep_task(i)) for i in range(2)] loop.run_until_complete(asyncio.wait(task_list)) loop.run_until_complete(loop.create_task(sleep_task(3))) loop.run_until_complete(asyncio.gather(sleep_task(10), sleep_task(20)))
for i in range(5): print(f'process task: {num} iter: {i}') await asyncio.sleep(1) return num
index.js
import Ruler from "./ruler.js"; import { onReady } from "./dom.js"; /** Class for FontFaceObserver. */ class FontFaceObserver { static Ruler = Ruler; /** * @type {null|boolean} */ static HAS_WEBKIT_FALLBACK_BUG = null; /** * @type {null|boolean} */ static HAS_SAFARI_10_BUG = null; /** * @type {null|boolean} */ static SUPPORTS_STRETCH = null; /** * @type {null|boolean} */ static SUPPORTS_NATIVE_FONT_LOADING = null; /** * @type {number} */ static DEFAULT_TIMEOUT = 3000; /** * @return {string} */ static getUserAgent() { return window.navigator.userAgent; }
/** * @return {string} */ static getNavigatorVendor() { return window.navigator.vendor; } /** * Returns true if this browser is WebKit and it has the fallback bug which is * present in WebKit 536.11 and earlier. * * @return {boolean} */ static hasWebKitFallbackBug() { if (FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG === null) { const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec( FontFaceObserver.getUserAgent() ); FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG = !!match && (parseInt(match[1], 10) < 536 || (parseInt(match[1], 10) === 536 && parseInt(match[2], 10) <= 11)); } return FontFaceObserver.HAS_WEBKIT_FALLBACK_BUG; } /** * Returns true if the browser has the Safari 10 bugs. The native font load * API in Safari 10 has two bugs that cause the document.fonts.load and * FontFace.prototype.load methods to return promises that don't reliably get * settled. * * The bugs are described in more detail here: * - https://bugs.webkit.org/show_bug.cgi?id=165037 * - https://bugs.webkit.org/show_bug.cgi?id=164902 * * If the browser is made by Apple, and has native font loading support, it is * potentially affected. But the API was fixed around AppleWebKit version 603, * so any newer versions that that does not contain the bug. * * @return {boolean} */ static hasSafari10Bug() { if (FontFaceObserver.HAS_SAFARI_10_BUG === null) { if ( FontFaceObserver.supportsNativeFontLoading() && /Apple/.test(FontFaceObserver.getNavigatorVendor()) ) { const match = /AppleWebKit\/([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/.exec( FontFaceObserver.getUserAgent() ); FontFaceObserver.HAS_SAFARI_10_BUG = !!match && parseInt(match[1], 10) < 603; } else { FontFaceObserver.HAS_SAFARI_10_BUG = false; } } return FontFaceObserver.HAS_SAFARI_10_BUG; } /** * Returns true if the browser supports the native font loading API. * * @return {boolean} */ static supportsNativeFontLoading() { if (FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING === null) { FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING = !!document["fonts"]; } return FontFaceObserver.SUPPORTS_NATIVE_FONT_LOADING; } /** * Returns true if the browser supports font-style in the font short-hand * syntax. * * @return {boolean} */ static supportStretch() { if (FontFaceObserver.SUPPORTS_STRETCH === null) { const div = document.createElement("div"); try { div.style.font = "condensed 100px sans-serif"; } catch (e) {} FontFaceObserver.SUPPORTS_STRETCH = div.style.font !== ""; } return FontFaceObserver.SUPPORTS_STRETCH; } /** * @typedef {Object} Descriptors * @property {string|undefined} style * @property {string|undefined} weight * @property {string|undefined} stretch */ /** * * @param {string} family font-family name (required) * @param {Descriptors} descriptors an object describing the variation * (optional). The object can contain `weight`, `style`, and `stretch` * properties. If a property is not present it will default to `normal`. */ constructor(family, descriptors = {}) { this.family = family; this.style = descriptors.style || "normal"; this.weight = descriptors.weight || "normal"; this.stretch = descriptors.stretch || "normal"; return this; } /** * @param {string=} text Optional test string to use for detecting if a font * is available. * @param {number=} timeout Optional timeout for giving up on font load * detection and rejecting the promise (defaults to 3 seconds). * @return {Promise.<FontFaceObserver>} */ load(text, timeout) { const that = this; const testString = text || "BESbswy"; let timeoutId = 0; const timeoutValue = timeout || FontFaceObserver.DEFAULT_TIMEOUT; const start = that.getTime(); return new Promise(function(resolve, reject) { if ( FontFaceObserver.supportsNativeFontLoading() && !FontFaceObserver.hasSafari10Bug() ) { const loader = new Promise(function(resolve, reject) { const check = function() { const now = that.getTime(); if (now - start >= timeoutValue) { reject(new Error("" + timeoutValue + "ms timeout exceeded")); } else { document.fonts .load(that.getStyle('"' + that["family"] + '"'), testString) .then(function(fonts) { if (fonts.length >= 1) { resolve(); } else { setTimeout(check, 25); } }, reject); } }; check(); }); const timer = new Promise(function(resolve, reject) { timeoutId = setTimeout(function() { reject(new Error("" + timeoutValue + "ms timeout exceeded")); }, timeoutValue); }); Promise.race([timer, loader]).then(function() { clearTimeout(timeoutId); resolve(that); }, reject); } else { onReady(function() { const rulerA = new Ruler(testString); const rulerB = new Ruler(testString); const rulerC = new Ruler(testString); let widthA = -1; let widthB = -1; let widthC = -1; let fallbackWidthA = -1; let fallbackWidthB = -1; let fallbackWidthC = -1; const container = document.createElement("div"); /** * @private */ function removeContainer() { if (container.parentNode !== null) { container.parentNode.removeChild(container); } } /** * @private * * If metric compatible fonts are detected, one of the widths will be * -1. This is because a metric compatible font won't trigger a scroll * event. We work around this by considering a font loaded if at least * two of the widths are the same. Because we have three widths, this * still prevents false positives. * * Cases: * 1) Font loads: both a, b and c are called and have the same value. * 2) Font fails to load: resize callback is never called and timeout * happens. * 3) WebKit bug: both a, b and c are called and have the same value, * but the values are equal to one of the last resort fonts, we * ignore this and continue waiting until we get new values (or a * timeout). */ function check() { if ( (widthA != -1 && widthB != -1) || (widthA != -1 && widthC != -1) || (widthB != -1 && widthC != -1) ) { if (widthA == widthB || widthA == widthC || widthB == widthC) { // All values are the same, so the browser has most likely // loaded the web font if (FontFaceObserver.hasWebKitFallbackBug()) { // Except if the browser has the WebKit fallback bug, in which // case we check to see if all values are set to one of the // last resort fonts. if ( (widthA == fallbackWidthA && widthB == fallbackWidthA && widthC == fallbackWidthA) || (widthA == fallbackWidthB && widthB == fallbackWidthB && widthC == fallbackWidthB) || (widthA == fallbackWidthC && widthB == fallbackWidthC && widthC == fallbackWidthC) ) { // The width we got matches some of the known last resort // fonts, so let's assume we're dealing with the last resort // font. return; } } removeContainer(); clearTimeout(timeoutId); resolve(that); } } } // This ensures the scroll direction is correct. container.dir = "ltr"; rulerA.setFont(that.getStyle("sans-serif")); rulerB.setFont(that.getStyle("serif")); rulerC.setFont(that.getStyle("monospace")); container.appendChild(rulerA.getElement()); container.appendChild(rulerB.getElement()); container.appendChild(rulerC.getElement()); document.body.appendChild(container); fallbackWidthA = rulerA.getWidth(); fallbackWidthB = rulerB.getWidth(); fallbackWidthC = rulerC.getWidth(); function checkForTimeout() { const now = that.getTime(); if (now - start >= timeoutValue) { removeContainer(); reject(new Error("" + timeoutValue + "ms timeout exceeded")); } else { const hidden = document["hidden"]; if (hidden === true || hidden === undefined) { widthA = rulerA.getWidth(); widthB = rulerB.getWidth(); widthC = rulerC.getWidth(); check(); } timeoutId = setTimeout(checkForTimeout, 50); } } checkForTimeout(); rulerA.onResize(function(width) { widthA = width; check(); }); rulerA.setFont(that.getStyle('"' + that["family"] + '",sans-serif')); rulerB.onResize(function(width) { widthB = width; check(); }); rulerB.setFont(that.getStyle('"' + that["family"] + '",serif')); rulerC.onResize(function(width) { widthC = width; check(); }); rulerC.setFont(that.getStyle('"' + that["family"] + '",monospace')); }); } }); } /** * @private * * @param {string} family * @return {string} */ getStyle(family) { return [ this.style, this.weight, FontFaceObserver.supportStretch() ? this.stretch : "", "100px", family ].join(" "); } /** * @private * * @return {number} */ getTime() { return new Date().getTime(); } } export default FontFaceObserver;
channel.rs
#![allow(bare_trait_objects, unknown_lints)] extern crate futures; use std::sync::atomic::*; use futures::prelude::*; use futures::future::result; use futures::sync::mpsc; mod support; use support::*; #[test] fn sequence() { let (tx, mut rx) = mpsc::channel(1); sassert_empty(&mut rx); sassert_empty(&mut rx); let amt = 20; send(amt, tx).forget(); let mut rx = rx.wait(); for i in (1..amt + 1).rev() { assert_eq!(rx.next(), Some(Ok(i))); } assert_eq!(rx.next(), None); fn send(n: u32, sender: mpsc::Sender<u32>) -> Box<Future<Item=(), Error=()> + Send> { if n == 0 { return Box::new(result(Ok(()))) } Box::new(sender.send(n).map_err(|_| ()).and_then(move |sender| { send(n - 1, sender) })) } } #[test] fn drop_sender() { let (tx, mut rx) = mpsc::channel::<u32>(1); drop(tx); sassert_done(&mut rx); } #[test] fn drop_rx() { let (tx, rx) = mpsc::channel::<u32>(1); let tx = tx.send(1).wait().ok().unwrap(); drop(rx); assert!(tx.send(1).wait().is_err()); } #[test] fn drop_order() { #[allow(deprecated)] static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; let (tx, rx) = mpsc::channel(1); struct A; impl Drop for A { fn drop(&mut self) {
} let tx = tx.send(A).wait().unwrap(); assert_eq!(DROPS.load(Ordering::SeqCst), 0); drop(rx); assert_eq!(DROPS.load(Ordering::SeqCst), 1); assert!(tx.send(A).wait().is_err()); assert_eq!(DROPS.load(Ordering::SeqCst), 2); }
DROPS.fetch_add(1, Ordering::SeqCst); }
redis.js
"use strict"; var registry = require("./registry.js"); /** * * @param name * @param url */ module.exports = function (client, name) { name = "REDIS-" + name; registry.add(name, function () { return new Promise((resolve, reject) => {
}); } else { return resolve({ connected: false, error: "Redis not connected" }); } }); }); }
if(client.connected) { return resolve({ connected: true
manager.py
import os from collections import defaultdict import numpy as np import torch from termcolor import colored from torch.utils.tensorboard import SummaryWriter from common import utils class Manager(): def __init__(self, model, optimizer, scheduler, params, dataloaders, logger): # params status self.params = params self.model = model self.optimizer = optimizer self.scheduler = scheduler self.dataloaders = dataloaders self.logger = logger self.epoch = 0 self.step = 0 self.best_val_score = np.inf self.cur_val_score = np.inf self.best_test_score = np.inf self.cur_test_score = np.inf # train status self.train_status = defaultdict(utils.AverageMeter) # val status self.val_status = defaultdict(utils.AverageMeter) # test status self.test_status = defaultdict(utils.AverageMeter) # model status self.loss_status = defaultdict(utils.AverageMeter) # init local tensorboard and html self.init_tb_and_html() def init_tb_and_html(self): # tensorboard loss local_tb_dir = os.path.join(self.params.model_dir, "summary/loss") os.makedirs(local_tb_dir, exist_ok=True) self.local_loss_writter = SummaryWriter(log_dir=local_tb_dir) # tensorboard metric local_tb_dir = os.path.join(self.params.model_dir, "summary/metric") os.makedirs(local_tb_dir, exist_ok=True) self.local_metric_writter = SummaryWriter(log_dir=local_tb_dir) # html local_html_dir = os.path.join(self.params.model_dir, "summary/html") os.makedirs(local_html_dir, exist_ok=True) self.local_html_dir = local_html_dir def update_step(self): self.step += 1 def update_epoch(self): self.epoch += 1 def update_loss_status(self, loss, batch_size): for k, v in loss.items(): self.loss_status[k].update(val=v.item(), num=batch_size) def update_metric_status(self, metrics, split, batch_size): if split == "val": for k, v in metrics.items(): self.val_status[k].update(val=v.item(), num=batch_size) self.cur_val_score = self.val_status[self.params.major_metric].avg elif split == "test": for k, v in metrics.items(): self.test_status[k].update(val=v.item(), num=batch_size) self.cur_test_score = self.test_status[self.params.major_metric].avg else: raise ValueError("Wrong eval type: {}".format(split)) def summarize_metric_status(self, metrics, split): if split == "val": for k in metrics: if k.endswith('MSE'): self.val_status[k[:-3] + 'RMSE'].set(val=np.sqrt(self.val_status[k].avg)) else: continue elif split == "test": for k in metrics: if k.endswith('MSE'): self.test_status[k[:-3] + 'RMSE'].set(val=np.sqrt(self.test_status[k].avg)) else: continue else: raise ValueError("Wrong eval type: {}".format(split)) def reset_loss_status(self): for k, v in self.loss_status.items(): self.loss_status[k].reset() def reset_metric_status(self, split): if split == "val": for k, v in self.val_status.items(): self.val_status[k].reset() elif split == "test": for k, v in self.test_status.items(): self.test_status[k].reset() else: raise ValueError("Wrong split string: {}".format(split)) def print_train_info(self): exp_name = self.params.model_dir.split('/')[-1] print_str = "{} Epoch: {:4d}, lr={:.4f} ".format(exp_name, self.epoch, self.scheduler.get_last_lr()[0]) print_str += "total loss: %.4f(%.4f)" % (self.loss_status['total'].val, self.loss_status['total'].avg) return print_str def print_metrics(self, split, title="Eval", color="red", only_best=False): if split == "val": metric_status = self.val_status is_best = self.cur_val_score < self.best_val_score elif split == "test": metric_status = self.test_status is_best = self.cur_test_score < self.best_test_score else: raise ValueError("Wrong split string: {}".format(split)) print_str = " | ".join("{}: {:4g}".format(k, v.avg) for k, v in metric_status.items()) if only_best: if is_best: self.logger.info(colored("Best Epoch: {}, {} Results: {}".format(self.epoch, title, print_str), color, attrs=["bold"])) else: self.logger.info(colored("Epoch: {}, {} Results: {}".format(self.epoch, title, print_str), color, attrs=["bold"])) def write_loss_to_tb(self, split): for k, v in self.loss_status.items(): if split == "train": self.local_loss_writter.add_scalar("train_Loss/{}".format(k), v.val, self.step) elif split == "val": self.local_loss_writter.add_scalar("val_Loss/{}".format(k), v.val, self.step) elif split == "test": self.local_loss_writter.add_scalar("test_Loss/{}".format(k), v.val, self.step) else: raise ValueError("Wrong split string: {}".format(split)) def write_metric_to_tb(self, split): if split == "val": for k, v in self.val_status.items(): self.local_metric_writter.add_scalar("val_Metric/{}".format(k), v.avg, self.epoch) elif split == "test": for k, v in self.test_status.items(): self.local_metric_writter.add_scalar("test_Metric/{}".format(k), v.avg, self.epoch) else: raise ValueError("Wrong split string: {}".format(split)) def
(self, save_latest_freq=5, save_best_after=50): state = { "state_dict": self.model.state_dict(), "optimizer": self.optimizer.state_dict(), "scheduler": self.scheduler.state_dict(), "step": self.step, "epoch": self.epoch, } if self.dataloaders["val"] is not None: state["best_val_score"] = self.best_val_score if self.dataloaders["test"] is not None: state["best_test_score"] = self.best_test_score # save latest checkpoint if self.epoch % save_latest_freq == 0: latest_ckpt_name = os.path.join(self.params.model_dir, "model_latest.pth") torch.save(state, latest_ckpt_name) self.logger.info("Saved latest checkpoint to: {}".format(latest_ckpt_name)) # save val latest metrics, and check if val is best checkpoints if self.dataloaders["val"] is not None: val_latest_metrics_name = os.path.join(self.params.model_dir, "val_metrics_latest.json") utils.save_dict_to_json(self.val_status, val_latest_metrics_name) is_best = self.cur_val_score < self.best_val_score if is_best: # save metrics self.best_val_score = self.cur_val_score best_metrics_name = os.path.join(self.params.model_dir, "val_metrics_best.json") utils.save_dict_to_json(self.val_status, best_metrics_name) self.logger.info("Current is val best, score={:.7f}".format(self.best_val_score)) # save checkpoint if self.epoch > save_best_after: best_ckpt_name = os.path.join(self.params.model_dir, "val_model_best.pth") torch.save(state, best_ckpt_name) self.logger.info("Saved val best checkpoint to: {}".format(best_ckpt_name)) # save test latest metrics, and check if test is best checkpoints if self.dataloaders["test"] is not None: test_latest_metrics_name = os.path.join(self.params.model_dir, "test_metrics_latest.json") utils.save_dict_to_json(self.test_status, test_latest_metrics_name) is_best = self.cur_test_score < self.best_test_score if is_best: # save metrics self.best_test_score = self.cur_test_score best_metrics_name = os.path.join(self.params.model_dir, "test_metrics_best.json") utils.save_dict_to_json(self.test_status, best_metrics_name) self.logger.info("Current is test best, score={:.7f}".format(self.best_test_score)) # save checkpoint if self.epoch > save_best_after: best_ckpt_name = os.path.join(self.params.model_dir, "test_model_best.pth") torch.save(state, best_ckpt_name) self.logger.info("Saved test best checkpoint to: {}".format(best_ckpt_name)) def load_checkpoints(self): state = torch.load(self.params.restore_file) ckpt_component = [] if "state_dict" in state and self.model is not None: try: self.model.load_state_dict(state["state_dict"]) except RuntimeError: print("Using custom loading net") net_dict = self.model.state_dict() if "module" not in list(state["state_dict"].keys())[0]: state_dict = {"module." + k: v for k, v in state["state_dict"].items() if "module." + k in net_dict.keys()} else: state_dict = {k: v for k, v in state["state_dict"].items() if k in net_dict.keys()} net_dict.update(state_dict) self.model.load_state_dict(net_dict, strict=False) ckpt_component.append("net") if not self.params.only_weights: if "optimizer" in state and self.optimizer is not None: try: self.optimizer.load_state_dict(state["optimizer"]) except RuntimeError: print("Using custom loading optimizer") optimizer_dict = self.optimizer.state_dict() state_dict = {k: v for k, v in state["optimizer"].items() if k in optimizer_dict.keys()} optimizer_dict.update(state_dict) self.optimizer.load_state_dict(optimizer_dict) ckpt_component.append("opt") if "scheduler" in state and self.train_status["scheduler"] is not None: try: self.scheduler.load_state_dict(state["scheduler"]) except RuntimeError: print("Using custom loading scheduler") scheduler_dict = self.scheduler.state_dict() state_dict = {k: v for k, v in state["scheduler"].items() if k in scheduler_dict.keys()} scheduler_dict.update(state_dict) self.scheduler.load_state_dict(scheduler_dict) ckpt_component.append("sch") if "step" in state: self.step = state["step"] + 1 ckpt_component.append("step") if "epoch" in state: self.epoch = state["epoch"] + 1 ckpt_component.append("epoch") if "best_val_score" in state: self.best_val_score = state["best_val_score"] ckpt_component.append("best val score: {:.3g}".format(self.best_val_score)) if "best_test_score" in state: self.best_test_score = state["best_test_score"] ckpt_component.append("best test score: {:.3g}".format(self.best_test_score)) ckpt_component = ", ".join(i for i in ckpt_component) self.logger.info("Loaded models from: {}".format(self.params.restore_file)) self.logger.info("Ckpt load: {}".format(ckpt_component))
check_best_save_last_checkpoints
configs.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import ml_collections def get_testing(): """Returns a minimal configuration for testing.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.hidden_size = 1 config.transformer = ml_collections.ConfigDict() config.transformer.mlp_dim = 1 config.transformer.num_heads = 1 config.transformer.num_layers = 1 config.transformer.attention_dropout_rate = 0.0 config.transformer.dropout_rate = 0.1 config.classifier = 'token' config.representation_size = None return config def get_b16_config(): """Returns the ViT-B/16 configuration.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.hidden_size = 768 config.transformer = ml_collections.ConfigDict() config.transformer.mlp_dim = 3072 config.transformer.num_heads = 12 config.transformer.num_layers = 12 config.transformer.attention_dropout_rate = 0.0 config.transformer.dropout_rate = 0.1 config.classifier = 'token' config.representation_size = None return config def get_b32_config(): """Returns the ViT-B/32 configuration.""" config = get_b16_config() config.patches.size = (32, 32) return config def get_l16_config(): """Returns the ViT-L/16 configuration.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (16, 16)}) config.hidden_size = 1024 config.transformer = ml_collections.ConfigDict() config.transformer.mlp_dim = 4096 config.transformer.num_heads = 16 config.transformer.num_layers = 24 config.transformer.attention_dropout_rate = 0.0 config.transformer.dropout_rate = 0.1 config.classifier = 'token' config.representation_size = None return config def get_l32_config(): """Returns the ViT-L/32 configuration.""" config = get_l16_config() config.patches.size = (32, 32) return config def get_h14_config(): """Returns the ViT-H/14 configuration.""" config = ml_collections.ConfigDict() config.patches = ml_collections.ConfigDict({'size': (14, 14)}) config.hidden_size = 1280
config.transformer = ml_collections.ConfigDict() config.transformer.mlp_dim = 5120 config.transformer.num_heads = 16 config.transformer.num_layers = 32 config.transformer.attention_dropout_rate = 0.0 config.transformer.dropout_rate = 0.1 config.classifier = 'token' config.representation_size = None return config
cursor.go
package bolt import ( "bytes" "fmt" "sort" ) // Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order. // Cursors see nested buckets with value == nil. // Cursors can be obtained from a transaction and are valid as long as the transaction is open. // // Keys and values returned from the cursor are only valid for the life of the transaction. // // Changing data while traversing with a cursor may cause it to be invalidated // and return unexpected keys and/or values. You must reposition your cursor // after mutating data. // Cursor其实只是保存了查找过程中的搜索路径而已。类似一个stack,栈底是搜索路径的起点, // 栈顶是搜索路径的终点。Cursor.seek(key)完成后,Cursor中就已经记录了到key的搜索路径。 type Cursor struct { bucket *Bucket // parent Bucket stack []elemRef // 遍历过程中记录走过的page-id或者node,elemRef中的page、node同时只能有一个存在 } // Bucket returns the bucket that this cursor was created from. func (c *Cursor) Bucket() *Bucket { return c.bucket } // First moves the cursor to the first item in the bucket and returns its key and value. // If the bucket is empty then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction. func (c *Cursor) First() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) c.first() // If we land on an empty page then move to the next value. // https://github.com/boltdb/bolt/issues/450 if c.stack[len(c.stack)-1].count() == 0 { c.next() } k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v } // Last moves the cursor to the last item in the bucket and returns its key and value. // If the bucket is empty then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction. func (c *Cursor) Last() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") c.stack = c.stack[:0] p, n := c.bucket.pageNode(c.bucket.root) ref := elemRef{page: p, node: n} ref.index = ref.count() - 1 c.stack = append(c.stack, ref) c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v } // Next moves the cursor to the next item in the bucket and returns its key and value. // If the cursor is at the end of the bucket then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction. func (c *Cursor) Next() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") k, v, flags := c.next() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v } // Prev moves the cursor to the previous item in the bucket and returns its key and value. // If the cursor is at the beginning of the bucket then a nil key and value are returned. // The returned key and value are only valid for the life of the transaction. func (c *Cursor) Prev() (key []byte, value []byte) { _assert(c.bucket.tx.db != nil, "tx closed") // Attempt to move back one element until we're successful. // Move up the stack as we hit the beginning of each page in our stack. for i := len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index > 0 { elem.index-- break } c.stack = c.stack[:i] } // If we've hit the end then return nil. if len(c.stack) == 0 { return nil, nil } // Move down the stack to find the last element of the last leaf under this branch. c.last() k, v, flags := c.keyValue() if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v } // Seek moves the cursor to a given key and returns it. // If the key does not exist then the next key is used. If no keys // follow, a nil key is returned. // The returned key and value are only valid for the life of the transaction. func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { k, v, flags := c.seek(seek) // If we ended up after the last element of a page then move to the next one. if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { k, v, flags = c.next() } if k == nil { return nil, nil } else if (flags & uint32(bucketLeafFlag)) != 0 { return k, nil } return k, v } // Delete removes the current key/value under the cursor from the bucket. // Delete fails if current key/value is a bucket or if the transaction is not writable. func (c *Cursor) Delete() error { if c.bucket.tx.db == nil { return ErrTxClosed } else if !c.bucket.Writable() { return ErrTxNotWritable } key, _, flags := c.keyValue() // Return an error if current value is a bucket. if (flags & bucketLeafFlag) != 0 { return ErrIncompatibleValue } c.node().del(key) return nil } // seek moves the cursor to a given key and returns it. // If the key does not exist then the next key is used. // seek移动游标到给定的key的位置并返回key/value // 如果没有找到,游标移动到可用的位置,该key直接可以使用了。 func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { _assert(c.bucket.tx.db != nil, "tx closed") // Start from root page/node and traverse to correct page. c.stack = c.stack[:0] // 从父Bucket的root开始,对于Inline Bucket,请记住其root一定是0 c.search(seek, c.bucket.root) ref := &c.stack[len(c.stack)-1] // If the cursor is pointing to the end of page/node then return nil. if ref.index >= ref.count() { return nil, nil, 0 } // If this is a bucket then return a nil value. return c.keyValue() } // first moves the cursor to the first leaf element under the last page in the stack. // 切换page/node func (c *Cursor) first() { for { // Exit when we hit a leaf page. // 后序遍历 var ref = &c.stack[len(c.stack)-1] if ref.isLeaf() { break } // Keep adding pages pointing to the first element to the stack. var pgid pgid if ref.node != nil { pgid = ref.node.inodes[ref.index].pgid } else { pgid = ref.page.branchPageElement(uint16(ref.index)).pgid } p, n := c.bucket.pageNode(pgid) c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) } } // last moves the cursor to the last leaf element under the last page in the stack. func (c *Cursor) last() { for { // Exit when we hit a leaf page. ref := &c.stack[len(c.stack)-1] if ref.isLeaf() { break } // Keep adding pages pointing to the last element in the stack. var pgid pgid if ref.node != nil { pgid = ref.node.inodes[ref.index].pgid } else { pgid = ref.page.branchPageElement(uint16(ref.index)).pgid } p, n := c.bucket.pageNode(pgid) var nextRef = elemRef{page: p, node: n} nextRef.index = nextRef.count() - 1 c.stack = append(c.stack, nextRef) } } // next moves to the next leaf element and returns the key and value. // If the cursor is at the last leaf element then it stays there and returns nil. func (c *Cursor) next() (key []byte, value []byte, flags uint32) { for { // Attempt to move over one element until we're successful. // Move up the stack as we hit the end of each page in our stack. // 还在同一个page/node中,下一个元素就是上一个元素的index+1 var i int for i = len(c.stack) - 1; i >= 0; i-- { elem := &c.stack[i] if elem.index < elem.count()-1 { elem.index++ break } } // If we've hit the root page then stop and return. This will leave the // cursor on the last element of the last page. // 说明已经遍历完了,上面的循环中没有找到一个可用的elem.index if i == -1 { return nil, nil, 0
// Otherwise start from where we left off in the stack and find the // first element of the first leaf page. // 弹出栈顶元素 c.stack = c.stack[:i+1] c.first() // If this is an empty page then restart and move back up the stack. // https://github.com/boltdb/bolt/issues/450 // 即将要遍历的page是空的 if c.stack[len(c.stack)-1].count() == 0 { continue } return c.keyValue() } } // search recursively performs a binary search against a given page/node until it finds a given key. func (c *Cursor) search(key []byte, pgid pgid) { // 这里是关键,对于InlineBucket pageNode返回的是bucket的root page // 根据pgid,返回对应的page/node ,如果之前该页已经读取过,就返回node,否则就返回p p, n := c.bucket.pageNode(pgid) if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 { panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags)) } e := elemRef{page: p, node: n} c.stack = append(c.stack, e) // If we're on a leaf page/node then find the specific node. if e.isLeaf() { c.nsearch(key) return } if n != nil { c.searchNode(key, n) return } c.searchPage(key, p) } func (c *Cursor) searchNode(key []byte, n *node) { var exact bool index := sort.Search(len(n.inodes), func(i int) bool { // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. // sort.Search() finds the lowest index where f() != -1 but we need the highest index. ret := bytes.Compare(n.inodes[i].key, key) if ret == 0 { exact = true } return ret != -1 }) if !exact && index > 0 { index-- } c.stack[len(c.stack)-1].index = index // Recursively search to the next page. c.search(key, n.inodes[index].pgid) } func (c *Cursor) searchPage(key []byte, p *page) { // Binary search for the correct range. inodes := p.branchPageElements() var exact bool // TODO 此处必须要用p.count来限制对inodes的访问,否则会发生越界访问 index := sort.Search(int(p.count), func(i int) bool { // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. // sort.Search() finds the lowest index where f() != -1 but we need the highest index. ret := bytes.Compare(inodes[i].key(), key) if ret == 0 { exact = true } return ret != -1 }) if !exact && index > 0 { index-- } c.stack[len(c.stack)-1].index = index // Recursively search to the next page. c.search(key, inodes[index].pgid) } // nsearch searches the leaf node on the top of the stack for a key. func (c *Cursor) nsearch(key []byte) { e := &c.stack[len(c.stack)-1] p, n := e.page, e.node // If we have a node then search its inodes. if n != nil { index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) e.index = index return } // If we have a page then search its leaf elements. inodes := p.leafPageElements() index := sort.Search(int(p.count), func(i int) bool { return bytes.Compare(inodes[i].key(), key) != -1 }) e.index = index } // keyValue returns the key and value of the current leaf element. func (c *Cursor) keyValue() ([]byte, []byte, uint32) { ref := &c.stack[len(c.stack)-1] if ref.count() == 0 || ref.index >= ref.count() { return nil, nil, 0 } // Retrieve value from node. if ref.node != nil { inode := &ref.node.inodes[ref.index] return inode.key, inode.value, inode.flags } // Or retrieve value from page. elem := ref.page.leafPageElement(uint16(ref.index)) return elem.key(), elem.value(), elem.flags } // node returns the node that the cursor is currently positioned on. // 将搜索路径上经过的所有结点都加载进内存,并返回当前游标指向的结点。 // 因为Cursor同时支持在page和node中搜索,因此存在搜索到的page尚未初始化为node的情况 // TODO 此处应该可以优化 func (c *Cursor) node() *node { _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") // If the top of the stack is a leaf node then just return it. if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { return ref.node } // Start from root and traverse down the hierarchy(层级,等级制度). var n = c.stack[0].node if n == nil { // 该page尚未被初始化为node n = c.bucket.node(c.stack[0].page.id, nil) } for _, ref := range c.stack[:len(c.stack)-1] { _assert(!n.isLeaf, "expected branch node") n = n.childAt(int(ref.index)) } _assert(n.isLeaf, "expected leaf node") return n } // elemRef represents a reference to an element on a given page/node. type elemRef struct { // page、node同时只能有一个存在 page *page node *node index int } // isLeaf returns whether the ref is pointing at a leaf page/node. func (r *elemRef) isLeaf() bool { if r.node != nil { return r.node.isLeaf } return (r.page.flags & leafPageFlag) != 0 } // count returns the number of inodes or page elements. func (r *elemRef) count() int { if r.node != nil { return len(r.node.inodes) } return int(r.page.count) }
}
process_set_governance_delegate.rs
//! Program state processor use borsh::BorshSerialize; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, pubkey::Pubkey, }; use crate::state::token_owner_record::get_token_owner_record_data; /// Processes SetGovernanceDelegate instruction pub fn process_set_governance_delegate( program_id: &Pubkey, accounts: &[AccountInfo], new_governance_delegate: &Option<Pubkey>, ) -> ProgramResult
{ let account_info_iter = &mut accounts.iter(); let governance_authority_info = next_account_info(account_info_iter)?; // 0 let token_owner_record_info = next_account_info(account_info_iter)?; // 1 let mut token_owner_record_data = get_token_owner_record_data(program_id, token_owner_record_info)?; token_owner_record_data.assert_token_owner_or_delegate_is_signer(governance_authority_info)?; token_owner_record_data.governance_delegate = *new_governance_delegate; token_owner_record_data.serialize(&mut *token_owner_record_info.data.borrow_mut())?; Ok(()) }
main.rs
use std::fs; fn part1() { let mut digits: Vec<i64> = fs::read_to_string("input.txt") .unwrap() .chars() .map(|c| c.to_string().parse::<i64>().unwrap()) .collect(); let base_pattern = vec![0, 1, 0, -1]; for _ in 0..100 { for i in 0..digits.len() - 1 { digits[i] = digits .iter() .enumerate() .skip(i) //optimization, since all will be * 0 .map(|(j, d)| d * base_pattern[((j + 1) / (i + 1)) % 4]) .sum::<i64>().abs()%10; } } println!("part1:{:?}", &digits[0..8]); } fn part2() { let input_chars: Vec<char> = fs::read_to_string("input.txt").unwrap().chars().collect(); let offset = input_chars .iter() .take(7) .collect::<String>() .parse::<usize>() .unwrap(); let mut digits: Vec<i64> = input_chars .iter() .map(|c| c.to_string().parse::<i64>().unwrap()) .cycle() .take(10000 * input_chars.len()) .skip(offset) .collect(); // This pattern only works on the 2nd half of the array // But lo and behold, the offset is in the 2nd half for _ in 0..100 { for i in (0..digits.len() - 1).rev() { digits[i] = (digits[i] + digits[i + 1]) % 10; } } println!("part2:{:?}", &digits[0..8]); } fn main()
{ part1(); part2(); }
namespace.go
package gatherers import ( "context" "github.com/stackrox/rox/pkg/telemetry" "github.com/stackrox/rox/pkg/telemetry/data" "github.com/stackrox/rox/sensor/kubernetes/listener/resources" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) type namespaceGatherer struct { k8sClient kubernetes.Interface deploymentStore *resources.DeploymentStore } func newNamespaceGatherer(k8sClient kubernetes.Interface, deploymentStore *resources.DeploymentStore) *namespaceGatherer
// Gather returns a list of stats about all the namespaces in the cluster this Sensor is monitoring func (n *namespaceGatherer) Gather(ctx context.Context) ([]*data.NamespaceInfo, []error) { var errList []error namespaceList, err := n.k8sClient.CoreV1().Namespaces().List(ctx, v1.ListOptions{}) if err != nil { errList = append(errList, err) return nil, errList } namespaceInfoList := make([]*data.NamespaceInfo, 0, len(namespaceList.Items)) for _, namespace := range namespaceList.Items { podsForNamespace := n.k8sClient.CoreV1().Pods(namespace.Name) pods, err := podsForNamespace.List(ctx, v1.ListOptions{}) if err != nil { errList = append(errList, err) continue } name := namespace.GetName() if !telemetry.WellKnownNamespaces.Contains(name) { name = "" } namespaceInfoList = append(namespaceInfoList, &data.NamespaceInfo{ ID: string(namespace.GetUID()), Name: name, NumPods: len(pods.Items), NumDeployments: n.deploymentStore.CountDeploymentsForNamespace(namespace.GetName()), }) } return namespaceInfoList, errList }
{ return &namespaceGatherer{ k8sClient: k8sClient, deploymentStore: deploymentStore, } }
pwba_plugin.py
from PyWebBrowserApp import PluginBase from PyWebBrowserApp import register_plugin_op class Plugin(PluginBase): def __init__(self):
@register_plugin_op def test_plugin_callback(self, op_data): # self.info(op_data.get('message', '')) print('Hello from ${P} callback') @register_plugin_op def roundtrip_from_js(self, op_data): alert_msg = op_data.get('alert_msg', '???') self.info('[Plugin "%s"] in roundtrip_from_js() method, got alert_msg "%s"' % (self.name, alert_msg)) self.plugin_to_webbrowser('roundtrip_from_python', {'alert_msg': alert_msg})
super(Plugin, self).__init__() self.name = '${P}'
resources.d.ts
export declare const CSS_UTILITY: { rtl: string;
};
norvig_spell.py
import re from collections import Counter def words(text): return re.findall(r'\w+', text.lower()) WORDS = Counter() TOTAL_WORDS = 0 def init(filename = 'big.txt'): global WORDS global TOTAL_WORDS #统计词频,并存储为词典 WORDS = Counter(words(open(filename).read())) #统计总词数 TOTAL_WORDS=sum(WORDS.values()) #统计每一个词的词频占比 def P(word, N=None): "Probability of `word`." N = N or TOTAL_WORDS return WORDS[word] / N def correction(word): if known([word]): return word cands = known(edits1(word)) or known(edits2(word)) if not cands: return word cands = sorted(cands, key=P, reverse=True) if cands[0] == word: return word return sorted(cands, key=P, reverse=True) #遍历每一个词并确保其在词典中 def known(words): "The subset of `words` that appear in the dictionary of WORDS." return set(w for w in words if w in WORDS) #编辑距离为1的单词 def edits1(word): "All edits that are one edit away from `word`." letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] replaces = [L + c + R[1:] for L, R in splits if R for c in letters] inserts = [L + c + R for L, R in splits for c in letters] return set(deletes + transposes + replaces + inserts) #编辑距离为2的单词 def edits2(word): "All edits that are two edits away from `word`." return (e2 for e1 in edits1(word) for e2 in edits1(e1))
pingrelay.go
package pingrelay import ( "encoding/json" "errors" "os" "sync" "github.com/tankbusta/haleakala" "github.com/tankbusta/haleakala/muxer" "github.com/asdine/storm" "github.com/bwmarrin/discordgo" zmq "github.com/pebbe/zmq4" ) type relayConfig struct { ZMQ struct { Address *string `json:"address"` EnableSecurity bool `json:"enable_security"` ServerPublic string `json:"curve_server_public"` ClientPublic string `json:"curve_client_public"` ClientPrivate string `json:"curve_client_private"` } `json:"zmq"` PingsFrom []string `json:"pings_from"` // User(s) who sends the pings MaxSimilarity float64 `json:"max_similarity"` // The maximum similarity between the last ping from this user and the current ping based on the levenshtein measure RelayMessages []struct { ChannelIDs []string `json:"channel_ids"` // Group of Channel IDs to broadcast to Group string `json:"group"` // Broadcast pings from this groups to the channel ids above } `json:"relay_groups"` SpamControl struct { Enable bool `json:"enabled"` TriggerWords []string `json:"words"` } `json:"spam_control"` } func init()
type plugin struct{} func (s plugin) Initialize(cfg haleakala.PluginConfigVars, ds *discordgo.Session, node storm.Node) (haleakala.IPlugin, error) { var rc relayConfig if err := json.Unmarshal(cfg, &rc); err != nil { return nil, err } if rc.ZMQ.Address == nil { // Do we have it as an environment variable? zmqenv := os.Getenv("BOT_ZMQ_ENDPOINT") if zmqenv == "" { return nil, errors.New("ping relay requires that address or the environment variable BOT_ZMQ_ENDPOINT to be set") } rc.ZMQ.Address = &zmqenv } sock, err := zmq.NewSocket(zmq.SUB) if err != nil { return nil, err } relay := &zncRelayPlugin{ ds: ds, stor: node, sock: sock, cfg: &rc, stop: make(chan bool, 1), wg: &sync.WaitGroup{}, cl: createLookupTable(rc), messageStats: make(map[string]*PingStat), mu: new(sync.RWMutex), } if err := relay.Start(); err != nil { return nil, err } return relay, nil } type zncRelayPlugin struct { ds *discordgo.Session stor storm.Node sock *zmq.Socket stop chan bool cfg *relayConfig wg *sync.WaitGroup mu *sync.RWMutex cl chanMap messageStats map[string]*PingStat } func (s *zncRelayPlugin) Destroy() error { close(s.stop) s.wg.Wait() return s.sock.Close() } func (s zncRelayPlugin) SupportsUnload() bool { return true } func (s zncRelayPlugin) Name() string { return "znc_relay" } func (s *zncRelayPlugin) clearCache(c *muxer.Context) { s.mu.Lock() for keyname := range s.messageStats { s.messageStats[keyname] = nil delete(s.messageStats, keyname) } s.messageStats = make(map[string]*PingStat) s.mu.Unlock() c.Send(":white_check_mark: Ping cache has been cleared successfully. Enjoy your Spam!") } func (s *zncRelayPlugin) InstallRoute(f haleakala.InstallFunc) error { f("ping_stats", "send statistics about current relayed pings", s.GetRelayStats) f("ping_config", "", haleakala.DefaultAdminMiddleware, s.UpdatePingConfig) f("ping_clear_cache", "", haleakala.DefaultAdminMiddleware, s.clearCache) return nil }
{ haleakala.Register("znc_relay", &plugin{}) }
PuzzleIso.ts
import { Point } from "./Point"; import { Puzzle_truncated_square } from "./PuzzleTruncatedSquare"; export class Puzzle_iso extends Puzzle_truncated_square { constructor(nx, ny, size) { //盤面情報 super(nx, ny, size, "iso"); this.gridtype = "iso"; this.nx = nx; this.ny = ny; this.nx0 = this.nx; this.ny0 = this.ny; this.margin = -1; //for arrow of number pointing outside of the grid this.width0 = this.nx + 6; this.height0 = this.ny + 6; this.width_c = this.width0; this.height_c = this.height0; this.width = this.width_c; this.height = this.height_c; this.canvasx = this.width_c * this.size; this.canvasy = this.height_c * this.size; this.space = []; this.size = size; this.onoff_symbolmode_list = { cross: 6, arrow_cross: 6, arrow_fourtip: 4, degital: 7, degital_f: 7, arrow_eight: 8, arrow_fouredge_B: 8, arrow_fouredge_G: 8, arrow_fouredge_E: 8, dice: 9, polyomino: 9, }; this.reset(); this.erase_buttons(); document.getElementById("sub_lineE2_lb").style.display = "inline-block"; } create_point() { var k = 0, k0; var nx = this.nx0; var r1, r2, angle; var adjacent, surround, type, use, neighbor; var point = []; adjacent = []; surround = []; neighbor = []; use = 1; var offsetx, offsety; //center for (var j = 0; j < nx; j++) { for (var i = 0; i < nx; i++) { k0 = k; type = 0; offsetx = i * 0.5 * Math.sqrt(3) - j * 0.5 * Math.sqrt(3); offsety = -i * 0.5 - j * 0.5; point[k] = new Point( offsetx * this.size, (offsety - 0.5) * this.size, type, adjacent, surround, use, neighbor, [], 1 ); k++; offsetx = -j * 0.5 * Math.sqrt(3); offsety = i - j * 0.5; point[k] = new Point( (offsetx - Math.sqrt(3) / 4) * this.size, (offsety + 0.25) * this.size, type, adjacent, surround, use, neighbor, [], 2 ); k++; offsetx = j * 0.5 * Math.sqrt(3); offsety = i - j * 0.5; point[k] = new Point( (offsetx + Math.sqrt(3) / 4) * this.size, (offsety + 0.25) * this.size, type, adjacent, surround, use, neighbor, [], 3 ); k++; type = 1; r1 = 0.5 * Math.sqrt(3); r2 = 0.5; for (var m = 0; m < 2; m++) { point[k] = new Point( point[k0].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 + 0)), point[k0].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 + 0)), type, adjacent, surround, use, neighbor ); point[k0].surround = point[k0].surround.concat([k]); point[k].surround = point[k].surround.concat([k0]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; point[k] = new Point( point[k0].x + r2 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 + 90)), point[k0].y + r2 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 + 90)), type, adjacent, surround, use, neighbor ); point[k0].surround = point[k0].surround.concat([k]); point[k].surround = point[k].surround.concat([k0]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; } for (var m = 0; m < 2; m++) { point[k] = new Point( point[k0 + 1].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 + 60)), point[k0 + 1].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 + 60)), type, adjacent, surround, use, neighbor ); point[k0 + 1].surround = point[k0 + 1].surround.concat([k]); point[k].surround = point[k].surround.concat([k0 + 1]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; point[k] = new Point( point[k0 + 1].x + r2 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 + 150)), point[k0 + 1].y + r2 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 + 150)), type, adjacent, surround, use, neighbor ); point[k0 + 1].surround = point[k0 + 1].surround.concat([k]); point[k].surround = point[k].surround.concat([k0 + 1]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; } for (var m = 0; m < 2; m++) { point[k] = new Point( point[k0 + 2].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 - 60)), point[k0 + 2].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 - 60)), type, adjacent, surround, use, neighbor ); point[k0 + 2].surround = point[k0 + 2].surround.concat([k]); point[k].surround = point[k].surround.concat([k0 + 2]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; point[k] = new Point( point[k0 + 2].x + r2 * this.size * Math.cos(((2 * Math.PI) / 360) * (m * 180 + 30)), point[k0 + 2].y + r2 * this.size * Math.sin(((2 * Math.PI) / 360) * (m * 180 + 30)), type, adjacent, surround, use, neighbor ); point[k0 + 2].surround = point[k0 + 2].surround.concat([k]); point[k].surround = point[k].surround.concat([k0 + 2]); if (m === 0) { point[k].adjacent_dia = point[k].adjacent_dia.concat([k + 2]); } else { point[k].adjacent_dia = point[k].adjacent_dia.concat([k - 2]); } k++; } type = 2; r1 = 0.5; angle = [30, 150, 210, 330]; for (var m = 0; m < 4; m++) { point[k] = new Point( point[k0].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * angle[m]), point[k0].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * angle[m]), type, adjacent, surround, use, neighbor ); point[k0].neighbor = point[k0].neighbor.concat([k]); if (m === 3) { point[k - 15].neighbor = point[k - 15].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } else { point[k - 11].neighbor = point[k - 11].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } k++; } angle = [30, 90, 210, 270]; for (var m = 0; m < 4; m++) { point[k] = new Point( point[k0 + 1].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * angle[m]), point[k0 + 1].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * angle[m]), type, adjacent, surround, use, neighbor ); point[k0 + 1].neighbor = point[k0 + 1].neighbor.concat([k]); if (m === 0) { point[k - 9].neighbor = point[k - 9].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } else { point[k - 13].neighbor = point[k - 13].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } k++; } angle = [-30, 90, 150, 270]; for (var m = 0; m < 4; m++) { point[k] = new Point( point[k0 + 2].x + r1 * this.size * Math.cos(((2 * Math.PI) / 360) * angle[m]), point[k0 + 2].y + r1 * this.size * Math.sin(((2 * Math.PI) / 360) * angle[m]), type, adjacent, surround, use, neighbor ); point[k0 + 2].neighbor = point[k0 + 2].neighbor.concat([k]); if (m === 3) { point[k - 15].neighbor = point[k - 15].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } else { point[k - 11].neighbor = point[k - 11].neighbor.concat([k]); point[k - 12].neighbor = point[k - 12].neighbor.concat([k]); } k++; } } } // 重複判定 for (var i = 0; i < point.length; i++) { if (!point[i]) { continue; } for (var j = i + 1; j < point.length; j++) { if (!point[j]) { continue; } if ( (point[i].x - point[j].x) ** 2 + (point[i].y - point[j].y) ** 2 < 0.01 ) { //surround,neighbor置換 for (var k = 0; k < point.length; k++) { if (!point[k]) { continue; } for (var n = 0; n < point[k].surround.length; n++) { if (point[k].surround[n] === j) { point[k].surround.splice(n, 1, i); } } for (var n = 0; n < point[k].neighbor.length; n++) { if (point[k].neighbor[n] === j) { if (point[k].neighbor.indexOf(i) === -1) { point[k].neighbor.splice(n, 1, i); //無ければ置き換え } else { point[k].neighbor.splice(n, 1); //あったら削除 } } } for (var n = 0; n < point[k].adjacent_dia.length; n++) { if (point[k].adjacent_dia[n] === j) { point[k].adjacent_dia.splice(n, 1, i); } } } for (var n = 0; n < point[j].surround.length; n++) { //削除された点のsurroundを移し替え if (point[i].surround.indexOf(point[j].surround[n]) === -1) { point[i].surround = point[i].surround.concat([ point[j].surround[n], ]); } } for (var n = 0; n < point[j].neighbor.length; n++) { //削除された点のneighborを移し替え if (point[i].neighbor.indexOf(point[j].neighbor[n]) === -1) { point[i].neighbor = point[i].neighbor.concat([ point[j].neighbor[n], ]); } } for (var n = 0; n < point[j].adjacent_dia.length; n++) { //削除された点のadjacent_diaを移し替え if ( point[i].adjacent_dia.indexOf(point[j].adjacent_dia[n]) === -1 ) { point[i].adjacent_dia = point[i].adjacent_dia.concat([ point[j].adjacent_dia[n], ]); } } delete point[j]; //置換ここまで } } } // adjacent作成 for (var i = 0; i < point.length; i++) { if (!point[i] || point[i].type != 0) { continue; } for (var j = i + 1; j < point.length; j++) { if (!point[j] || point[j].type != 0) { continue; } for (var k = 0; k < point[i].neighbor.length; k++) { if (point[j].neighbor.indexOf(point[i].neighbor[k]) != -1) { point[i].adjacent = point[i].adjacent.concat([j]); point[j].adjacent = point[j].adjacent.concat([i]); } } } } for (var i = 0; i < point.length; i++) { if (!point[i] || point[i].type != 1) { continue; } for (var j = i + 1; j < point.length; j++) { if (!point[j] || point[j].type != 1) { continue; } for (var k = 0; k < point[i].neighbor.length; k++) { if (point[j].neighbor.indexOf(point[i].neighbor[k]) != -1) { point[i].adjacent = point[i].adjacent.concat([j]); point[j].adjacent = point[j].adjacent.concat([i]); } } } } this.point = point; } reset_frame() { this.create_point(); this.space = []; this.centerlist = []; for (var i = 0; i < this.point.length; i++) { if ( this.point[i] && this.point[i].use === 1 && this.point[i].type === 0 ) { this.centerlist.push(i); } } this.search_center(); this.width_c = this.width; this.height_c = this.height; this.center_n0 = this.center_n; this.canvasxy_update(); this.canvas_size_setting(); this.point_move( this.canvasx * 0.5 - this.point[this.center_n].x + 0.5, this.canvasy * 0.5 - this.point[this.center_n].y + 0.5, this.theta ); this.make_frameline(); this.cursol = this.centerlist[0]; this.cursolS = 4 * this.nx0 * this.ny0 + 4 + 4 * this.nx0; } search_center() { var xmax = 0, xmin = 1e5; var ymax = 0, ymin = 1e5; for (var i of this.centerlist) { if (this.point[i].x > xmax) { xmax = this.point[i].x; } if (this.point[i].x < xmin) { xmin = this.point[i].x; } if (this.point[i].y > ymax) { ymax = this.point[i].y; } if (this.point[i].y < ymin) { ymin = this.point[i].y; } } var x = (xmax + xmin) / 2; var y = (ymax + ymin) / 2; this.width = (xmax - xmin) / this.size + 2.5; this.height = (ymax - ymin) / this.size + 2.5; var min0, min = 10e6; var num = 0; for (const index in this.point) { const i = parseInt(i); min0 = (x - this.point[i].x) ** 2 + (y - this.point[i].y) ** 2; if (min0 < min) { min = min0; num = i; } } this.center_n = Math.floor(num); } type_set() { var type; switch (this.mode[this.mode.qa].edit_mode) { case "surface": case "board": type = [0]; break; case "symbol": case "move": if (document.getElementById("edge_button").textContent === "OFF") { type = [0]; } else { type = [0, 1, 2]; } break; case "number": if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "2" ) { type = [0]; } else if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "3" ) { type = [5]; } else if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "9" ) { type = [6]; } else { if (document.getElementById("edge_button").textContent === "OFF") { type = [0]; } else { type = [0, 1, 2]; } } break; case "line": if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "4" ) { type = [2]; } else if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "2" ) { type = [0, 1]; } else if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "5" ) { type = [0, 2]; } else { type = [0]; } break; case "lineE": if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "4" ) { type = [2]; } else if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "2" ) { type = [0, 1]; } else { type = [1]; } break; case "special": if ( this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0] === "polygon" ) { type = [1]; } else { type = [0, 1]; } break; case "combi": switch (this.mode[this.mode.qa][this.mode[this.mode.qa].edit_mode][0]) { case "tents": case "linex": type = [0, 2]; break; case "edgexoi": type = [0, 1, 2]; break; case "blpo": case "blwh": case "battleship": case "star": case "magnets": case "lineox": case "yajilin": case "hashi": case "arrowS": case "shaka": case "numfl": case "alfl": type = [0]; break; case "edgesub": type = [0, 1]; break; } break; } return type; } recalculate_num(x, y, num) { var min0, min = 10e6; var num0 = 0; var r0 = (0.5 * Math.sqrt(2)) / Math.cos(((2 * Math.PI) / 360) * 22.5); var r1 = Math.sqrt(2) - 1; if (this.point[num].type != 1) { return num; } for (var i = 0; i < this.point.length; i++) { if ( this.point[i] && this.point[i].type === 1 && this.point[i].use === 1 ) { min0 = (x - this.point[i].x) ** 2 + (y - this.point[i].y) ** 2; if (min0 < min) { if (this.point[i].type2 === 0 && min0 > (r0 * this.size) ** 2) { continue; } //円形の内側に入っていなければ更新しない if (this.point[i].type2 === 1 && min0 > (r1 * this.size) ** 2) { continue; } min = min0; num = i; } } } return parseInt(num); } coord_p_edgex(x, y) { var min0, min = 10e6; var num = 0; for (var i = 0; i < this.point.length; i++) { if (this.point[i] && this.type.indexOf(this.point[i].type) != -1) { min0 = (x - this.point[i].x) ** 2 + (y - this.point[i].y) ** 2; if (min0 < min) { if (this.point[i].type === 2 || this.point[i].type === 3) { if (min0 > (0.3 * this.size) ** 2) { continue; } } min = min0; num = i; } } } return Math.floor(num); } rotate_left() { this.theta = (this.theta - 30 * this.reflect[0] * this.reflect[1] + 360) % 360; this.point_move(0, 0, -30); this.redraw(); } rotate_right() { this.theta = (this.theta + 30 * this.reflect[0] * this.reflect[1] + 360) % 360; this.point_move(0, 0, +30); this.redraw(); } direction_arrow8(x, y, x0, y0) { var angle = (Math.atan2(y - y0, x - x0) * 360) / 2 / Math.PI + 180; if (this.reflect[0] === -1) { angle = (180 - angle + 360) % 360; } if (this.reflect[1] === -1) { angle = (360 - angle + 360) % 360; } angle = (angle - this.theta + 360) % 360; angle -= 180; var a; if (angle < -120) { a = 0; } else if (angle > -120 && angle < -60) { a = 1; } else if (angle > -60 && angle < 0) { a = 2; } else if (angle > 0 && angle < 60) { a = 3; } else if (angle > 60 && angle < 120) { a = 4; } else if (angle > 120) { a = 5; } return a; } ////////////////draw///////////////////// draw() { this.draw_surface("pu_q"); this.draw_surface("pu_a"); // this.draw_squareframe("pu_q"); // this.draw_squareframe("pu_a"); // this.draw_thermo("pu_q"); // this.draw_thermo("pu_a"); // this.draw_arrowsp("pu_q"); // this.draw_arrowsp("pu_a"); this.draw_symbol("pu_q", 1); this.draw_symbol("pu_a", 1); // this.draw_wall("pu_q"); // this.draw_wall("pu_a"); this.draw_frame(); this.draw_polygonsp("pu_q"); this.draw_polygonsp("pu_a"); this.draw_freeline("pu_q"); this.draw_freeline("pu_a"); this.draw_line("pu_q"); this.draw_line("pu_a"); //this.draw_direction("pu_q"); //this.draw_direction("pu_a"); this.draw_lattice(); this.draw_frameBold(); this.draw_symbol("pu_q", 2); this.draw_symbol("pu_a", 2); //this.draw_cage("pu_q"); //this.draw_cage("pu_a"); this.draw_number("pu_q"); this.draw_number("pu_a"); this.draw_cursol(); this.draw_freecircle(); //this.draw_point(); } draw_point() { set_font_style(this.ctx, (0.2 * this.size).toString(), 1); for (var i in this.point) { if (this.point[i].type === 0) { this.ctx.fillStyle = "#000"; if (this.point[i].use === 1) { this.ctx.text(i, this.point[i].x, this.point[i].y, 0.8 * this.size); } } else if (this.point[i].type === 1) { this.ctx.fillStyle = "blue"; if (this.point[i].use === 1) { this.ctx.text(i, this.point[i].x, this.point[i].y, 0.8 * this.size); } } else if (this.point[i].type === 2) { this.ctx.fillStyle = "red"; if (this.point[i].use === 1) { this.ctx.text(i, this.point[i].x, this.point[i].y, 0.8 * this.size); } this.ctx.fillStyle = "rgba(0,0,0,0)"; } else if (this.point[i].type === 3) { this.ctx.fillStyle = "orange"; if (this.point[i].use === 1) { this.ctx.text(i, this.point[i].x, this.point[i].y, 0.8 * this.size); } this.ctx.fillStyle = "rgba(0,0,0,0)"; } else if (this.point[i].type === 4) { this.ctx.fillStyle = "green"; if (this.point[i].use === 1) { this.ctx.text(i, this.point[i].x, this.point[i].y, 0.8 * this.size); } this.ctx.fillStyle = "rgba(0,0,0,0)"; } else if (this.point[i].type === 5) { this.ctx.fillStyle = "green"; //this.ctx.text(i,this.point[i].x,this.point[i].y,0.8*this.size); this.ctx.fillStyle = "rgba(0,0,0,0)"; } this.ctx.beginPath(); //this.ctx.arc(this.point[i].x,this.point[i].y,2.5,0,2*Math.PI,true); this.ctx.fill(); } } draw_line(pu) { for (var i in this[pu].line) { if (this[pu].line[i] === 98) { var r = 0.2; var x = this.point[i].x; var y = this.point[i].y; set_line_style(this.ctx, 98); this.ctx.beginPath(); this.ctx.moveTo( x + r * Math.cos(45 * (Math.PI / 180)) * this.size, y + r * Math.sin(45 * (Math.PI / 180)) * this.size ); this.ctx.lineTo( x + r * Math.cos(225 * (Math.PI / 180)) * this.size, y + r * Math.sin(225 * (Math.PI / 180)) * this.size ); this.ctx.stroke(); this.ctx.beginPath(); this.ctx.moveTo( x + r * Math.cos(135 * (Math.PI / 180)) * this.size, y + r * Math.sin(135 * (Math.PI / 180)) * this.size ); this.ctx.lineTo( x + r * Math.cos(315 * (Math.PI / 180)) * this.size, y + r * Math.sin(315 * (Math.PI / 180)) * this.size ); this.ctx.stroke(); } else { set_line_style(this.ctx, this[pu].line[i]); var i1 = i.split(",")[0]; var i2 = i.split(",")[1]; var i3; //search neighbor for (var j = 0; j < 4; j++) { if ( this.point[i2].neighbor.indexOf(this.point[i1].neighbor[j]) != -1 ) { i3 = this.point[i1].neighbor[j]; } } this.ctx.beginPath(); if (this[pu].line[i] === 40) { var r = 0.6; var x1 = r * this.point[i1].x + (1 - r) * this.point[i3].x; var y1 = r * this.point[i1].y + (1 - r) * this.point[i3].y; var x2 = (1 - r) * this.point[i3].x + r * this.point[i2].x; var y2 = (1 - r) * this.point[i3].y + r * this.point[i2].y; this.ctx.moveTo(x1, y1); this.ctx.lineTo(this.point[i3].x, this.point[i3].y); this.ctx.lineTo(x2, y2); } else if (this[pu].line[i] === 30) { var r = 0.15 * this.size; var dx = this.point[i1].x - this.point[i2].x; var dy = this.point[i1].y - this.point[i2].y; var d = Math.sqrt(dx ** 2 + dy ** 2); this.ctx.moveTo( this.point[i1].x - (r / d) * dy, this.point[i1].y + (r / d) * dx ); this.ctx.lineTo( this.point[i2].x - (r / d) * dy, this.point[i2].y + (r / d) * dx ); this.ctx.stroke(); this.ctx.moveTo( this.point[i1].x + (r / d) * dy, this.point[i1].y - (r / d) * dx ); this.ctx.lineTo( this.point[i2].x + (r / d) * dy, this.point[i2].y - (r / d) * dx ); } else { if (this.point[i1].type === 2 || this.point[i1].type === 3) { //for centerline this.ctx.moveTo(this.point[i2].x, this.point[i2].y); this.ctx.lineTo( (this.point[i1].x + this.point[i2].x) * 0.5, (this.point[i1].y + this.point[i2].y) * 0.5 ); this.ctx.stroke(); this.ctx.lineCap = "butt"; } else if (this.point[i2].type === 2 || this.point[i2].type === 3) { this.ctx.moveTo(this.point[i1].x, this.point[i1].y); this.ctx.lineTo( (this.point[i1].x + this.point[i2].x) * 0.5, (this.point[i1].y + this.point[i2].y) * 0.5 ); this.ctx.stroke(); this.ctx.lineCap = "butt"; } this.ctx.moveTo(this.point[i1].x, this.point[i1].y); this.ctx.lineTo(this.point[i3].x, this.point[i3].y); this.ctx.lineTo(this.point[i2].x, this.point[i2].y); } this.ctx.stroke(); } } for (var i in this[pu].lineE) { if (this[pu].lineE[i] === 98) { var r = 0.2; var x = this.point[i].x; var y = this.point[i].y; set_line_style(this.ctx, 98); this.ctx.beginPath(); this.ctx.moveTo( x + r * Math.cos(45 * (Math.PI / 180)) * this.size, y + r * Math.sin(45 * (Math.PI / 180)) * this.size ); this.ctx.lineTo( x + r * Math.cos(225 * (Math.PI / 180)) * this.size, y + r * Math.sin(225 * (Math.PI / 180)) * this.size ); this.ctx.stroke(); this.ctx.beginPath(); this.ctx.moveTo( x + r * Math.cos(135 * (Math.PI / 180)) * this.size, y + r * Math.sin(135 * (Math.PI / 180)) * this.size ); this.ctx.lineTo( x + r * Math.cos(315 * (Math.PI / 180)) * this.size, y + r * Math.sin(315 * (Math.PI / 180)) * this.size ); this.ctx.stroke(); } else { set_line_style(this.ctx, this[pu].lineE[i]); var i1 = i.split(",")[0]; var i2 = i.split(",")[1]; this.ctx.beginPath(); if (this[pu].lineE[i] === 30) { var r = 0.15 * this.size; var dx = this.point[i1].x - this.point[i2].x; var dy = this.point[i1].y - this.point[i2].y; var d = Math.sqrt(dx ** 2 + dy ** 2); this.ctx.moveTo( this.point[i1].x - (r / d) * dy, this.point[i1].y + (r / d) * dx ); this.ctx.lineTo( this.point[i2].x - (r / d) * dy, this.point[i2].y + (r / d) * dx ); this.ctx.stroke(); this.ctx.moveTo( this.point[i1].x + (r / d) * dy, this.point[i1].y - (r / d) * dx ); this.ctx.lineTo( this.point[i2].x + (r / d) * dy, this.point[i2].y - (r / d) * dx ); } else { this.ctx.moveTo(this.point[i1].x, this.point[i1].y); this.ctx.lineTo(this.point[i2].x, this.point[i2].y); } this.ctx.stroke(); } } } draw_number(pu) { /*number*/ for (var i in this[pu].number) { switch (this[pu].number[i][2]) { case "1": //normal this.draw_numbercircle(pu, i, 0.42); set_font_style( this.ctx, (0.7 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0], this.point[i].x, this.point[i].y + 0.06 * this.size, this.size * 0.8 ); break; case "2": //arrow var arrowlength = 0.7; this.draw_numbercircle(pu, i, 0.42); set_font_style( this.ctx, (0.65 * this.size).toString(10), this[pu].number[i][1] ); var direction = { _0: 150, _1: 90, _2: 30, _3: 330, _4: 270, _5: 210, }; direction = (direction[this[pu].number[i][0].slice(-2)] - this.theta + 360) % 360; if (this.reflect[0] === -1) { direction = (180 - direction + 360) % 360; } if (this.reflect[1] === -1) { direction = (360 - direction + 360) % 360; } switch (direction) { case 120: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.1 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (arrowlength * 0.25 + 0.15) * this.size, this.point[i].y + (arrowlength * 0.25 * Math.sqrt(3) - 0.15) * this.size, this.point[i].x + (-arrowlength * 0.25 + 0.15) * this.size, this.point[i].y + (-arrowlength * 0.25 * Math.sqrt(3) - 0.15) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 300: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.1 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (-arrowlength * 0.25 + 0.2) * this.size, this.point[i].y + (-arrowlength * 0.25 * Math.sqrt(3) - 0.1) * this.size, this.point[i].x + (arrowlength * 0.25 + 0.2) * this.size, this.point[i].y + (arrowlength * 0.25 * Math.sqrt(3) - 0.1) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 60: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.1 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x - (arrowlength * 0.25 + 0.15) * this.size, this.point[i].y + (arrowlength * 0.25 * Math.sqrt(3) - 0.15) * this.size, this.point[i].x - (-arrowlength * 0.25 + 0.15) * this.size, this.point[i].y + (-arrowlength * 0.25 * Math.sqrt(3) - 0.15) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 240: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.1 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x - (-arrowlength * 0.25 + 0.2) * this.size, this.point[i].y + (-arrowlength * 0.25 * Math.sqrt(3) - 0.1) * this.size, this.point[i].x - (arrowlength * 0.25 + 0.2) * this.size, this.point[i].y + (arrowlength * 0.25 * Math.sqrt(3) - 0.1) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 180: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (arrowlength * 0.5 + 0.0) * this.size, this.point[i].y + (arrowlength * 0.0 - 0.3) * this.size, this.point[i].x + (-arrowlength * 0.5 + 0.0) * this.size, this.point[i].y + (-arrowlength * 0.0 - 0.3) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 0: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x - (arrowlength * 0.5 + 0.0) * this.size, this.point[i].y + (arrowlength * 0.0 - 0.3) * this.size, this.point[i].x - (-arrowlength * 0.5 + 0.0) * this.size, this.point[i].y + (-arrowlength * 0.0 - 0.3) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 150: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (arrowlength * 0.25 * Math.sqrt(3) + 0.1) * this.size, this.point[i].y + (arrowlength * 0.25 - 0.2) * this.size, this.point[i].x + (-arrowlength * 0.25 * Math.sqrt(3) + 0.1) * this.size, this.point[i].y + (-arrowlength * 0.25 - 0.2) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 330: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (-arrowlength * 0.25 * Math.sqrt(3) + 0.15) * this.size, this.point[i].y + (-arrowlength * 0.25 - 0.15) * this.size, this.point[i].x + (arrowlength * 0.25 * Math.sqrt(3) + 0.15) * this.size, this.point[i].y + (arrowlength * 0.25 - 0.15) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 30: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x - (arrowlength * 0.25 * Math.sqrt(3) + 0.1) * this.size, this.point[i].y + (arrowlength * 0.25 - 0.2) * this.size, this.point[i].x - (-arrowlength * 0.25 * Math.sqrt(3) + 0.1) * this.size, this.point[i].y + (-arrowlength * 0.25 - 0.2) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 210: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x + 0.0 * this.size, this.point[i].y + 0.15 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x - (-arrowlength * 0.25 * Math.sqrt(3) + 0.15) * this.size, this.point[i].y + (-arrowlength * 0.25 - 0.15) * this.size, this.point[i].x - (arrowlength * 0.25 * Math.sqrt(3) + 0.15) * this.size, this.point[i].y + (arrowlength * 0.25 - 0.15) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 90: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.1 * this.size, this.point[i].y + 0.05 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (arrowlength * 0.0 + 0.25) * this.size, this.point[i].y + (arrowlength * 0.5 - 0.0) * this.size, this.point[i].x + (-arrowlength * 0.0 + 0.25) * this.size, this.point[i].y + (-arrowlength * 0.5 - 0.0) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; case 270: this.ctx.text( this[pu].number[i][0].slice(0, -2), this.point[i].x - 0.1 * this.size, this.point[i].y + 0.05 * this.size, this.size * 0.7 ); this.ctx.beginPath(); this.ctx.arrow( this.point[i].x + (arrowlength * 0.0 + 0.25) * this.size, this.point[i].y + (-arrowlength * 0.5 - 0.0) * this.size, this.point[i].x + (-arrowlength * 0.0 + 0.25) * this.size, this.point[i].y + (arrowlength * 0.5 - 0.0) * this.size, [0, 1, -0.25 * this.size, 1, -0.25 * this.size, 3] ); this.ctx.stroke(); this.ctx.fill(); break; default: set_font_style( this.ctx, (0.7 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0], this.point[i].x, this.point[i].y + 0.06 * this.size, this.size * 0.8 ); break; } break; case "4": //tapa this.draw_numbercircle(pu, i, 0.44); if (this[pu].number[i][0].length === 1) { set_font_style( this.ctx, (0.7 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0], this.point[i].x, this.point[i].y + 0.06 * this.size, this.size * 0.8 ); } else if (this[pu].number[i][0].length === 2) { set_font_style( this.ctx, (0.48 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0].slice(0, 1), this.point[i].x - 0.16 * this.size, this.point[i].y - 0.15 * this.size, this.size * 0.8 ); this.ctx.text( this[pu].number[i][0].slice(1, 2), this.point[i].x + 0.18 * this.size, this.point[i].y + 0.19 * this.size, this.size * 0.8 ); } else if (this[pu].number[i][0].length === 3) { set_font_style( this.ctx, (0.45 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0].slice(0, 1), this.point[i].x - 0.22 * this.size, this.point[i].y - 0.14 * this.size, this.size * 0.8
this.point[i].x + 0.24 * this.size, this.point[i].y - 0.05 * this.size, this.size * 0.8 ); this.ctx.text( this[pu].number[i][0].slice(2, 3), this.point[i].x - 0.0 * this.size, this.point[i].y + 0.3 * this.size, this.size * 0.8 ); } else if (this[pu].number[i][0].length === 4) { set_font_style( this.ctx, (0.4 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0].slice(0, 1), this.point[i].x - 0.0 * this.size, this.point[i].y - 0.22 * this.size, this.size * 0.8 ); this.ctx.text( this[pu].number[i][0].slice(1, 2), this.point[i].x - 0.26 * this.size, this.point[i].y + 0.04 * this.size, this.size * 0.8 ); this.ctx.text( this[pu].number[i][0].slice(2, 3), this.point[i].x + 0.26 * this.size, this.point[i].y + 0.04 * this.size, this.size * 0.8 ); this.ctx.text( this[pu].number[i][0].slice(3, 4), this.point[i].x - 0.0 * this.size, this.point[i].y + 0.3 * this.size, this.size * 0.8 ); } break; case "5": //small this.draw_numbercircle(pu, i, 0.17); set_font_style( this.ctx, (0.25 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0], this.point[i].x, this.point[i].y + 0.02 * this.size, this.size * 0.8 ); break; case "6": //medium this.draw_numbercircle(pu, i, 0.25); set_font_style( this.ctx, (0.4 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( this[pu].number[i][0], this.point[i].x, this.point[i].y + 0.03 * this.size, this.size * 0.8 ); break; case "7": //sudoku this.draw_numbercircle(pu, i, 0.42); var sum = 0, pos = 0; for (var j = 0; j < 9; j++) { if (this[pu].number[i][0][j] === 1) { sum += 1; pos = j; } } if (sum === 1) { set_font_style( this.ctx, (0.7 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.text( (pos + 1).toString(), this.point[i].x, this.point[i].y + 0.06 * this.size, this.size * 0.8 ); } else { set_font_style( this.ctx, (0.3 * this.size).toString(10), this[pu].number[i][1] ); for (var j = 0; j < 9; j++) { if (this[pu].number[i][0][j] === 1) { this.ctx.text( (j + 1).toString(), this.point[i].x + ((j % 3) - 1) * 0.25 * this.size, this.point[i].y + ((((j / 3) | 0) - 1) * 0.25 + 0.01) * this.size ); } } } break; case "8": //long if (this[pu].number[i][1] === 5) { set_font_style( this.ctx, (0.5 * this.size).toString(10), this[pu].number[i][1] ); set_circle_style(this.ctx, 7); this.ctx.fillRect( this.point[i].x - 0.2 * this.size, this.point[i].y - 0.25 * this.size, this.ctx.measureText(this[pu].number[i][0]).width, 0.5 * this.size ); } set_font_style( this.ctx, (0.5 * this.size).toString(10), this[pu].number[i][1] ); this.ctx.textAlign = "left"; this.ctx.text( this[pu].number[i][0], this.point[i].x - 0.2 * this.size, this.point[i].y ); break; } } for (var i in this[pu].numberS) { if (this[pu].numberS[i][1] === 5) { set_circle_style(this.ctx, 7); this.draw_circle(this.ctx, this.point[i].x, this.point[i].y, 0.15); } else if (this[pu].numberS[i][1] === 6) { set_circle_style(this.ctx, 1); this.draw_circle(this.ctx, this.point[i].x, this.point[i].y, 0.15); } else if (this[pu].numberS[i][1] === 7) { set_circle_style(this.ctx, 2); this.draw_circle(this.ctx, this.point[i].x, this.point[i].y, 0.15); } if (true) { set_font_style( this.ctx, (0.26 * this.size).toString(10), this[pu].numberS[i][1] ); this.ctx.textAlign = "center"; this.ctx.text( this[pu].numberS[i][0], this.point[i].x, this.point[i].y + 0.03 * this.size, 0.3 * this.size ); } } } draw_cross(ctx, num, x, y) { for (var i = 0; i < 6; i++) { if (num[i] === 1) { var th = this.rotate_theta(i * 60 - 150); ctx.beginPath(); ctx.moveTo( x + ctx.lineWidth * 0.3 * Math.cos(th), y + ctx.lineWidth * 0.3 * Math.sin(th) ); ctx.lineTo( x - 0.5 * this.size * Math.cos(th), y - 0.5 * this.size * Math.sin(th) ); ctx.stroke(); } } } draw_inequality(ctx, num, x, y) { var th; var len = 0.14; switch (num) { case 1: case 2: case 3: case 4: case 5: case 6: ctx.beginPath(); th = this.rotate_theta((num - 1) * 60 + 75); ctx.moveTo( x + len * Math.sqrt(2) * this.size * Math.cos(th), y + len * Math.sqrt(2) * this.size * Math.sin(th) ); th = this.rotate_theta((num - 1) * 60 + 210); ctx.lineTo( x + len * this.size * Math.cos(th), y + len * this.size * Math.sin(th) ); th = this.rotate_theta((num - 1) * 60 + 345); ctx.lineTo( x + len * Math.sqrt(2) * this.size * Math.cos(th), y + len * Math.sqrt(2) * this.size * Math.sin(th) ); ctx.fill(); ctx.stroke(); break; } } draw_arrowGP(ctx, num, x, y) { var len1 = 0.35; //nemoto var len2 = 0.35; //tip var w1 = 0.12; var w2 = 0.23; var w3 = 0.34; var r1 = -0.33; var r2 = -0.44; var r3 = -0.32; var th; if (num > 0 && num <= 6) { th = this.rotate_theta((num - 1) * 60 - 150); ctx.beginPath(); ctx.arrow( x - len1 * this.size * Math.cos(th), y - len1 * this.size * Math.sin(th), x + len2 * this.size * Math.cos(th), y + len2 * this.size * Math.sin(th), [ 0, w1 * this.size, r1 * this.size, w1 * this.size, r2 * this.size, w2 * this.size, r3 * this.size, w3 * this.size, ] ); ctx.fill(); ctx.stroke(); } } draw_arrowGP_C(ctx, num, x, y) { if (num > 0 && num <= 6) { var th = this.rotate_theta((num - 1) * 60 - 150); this.draw_circle(ctx, x, y, 0.35); this.draw_arrowGP( ctx, num, x + 0.5 * this.size * Math.cos(th), y + 0.5 * this.size * Math.sin(th) ); } } draw_arrow(ctx, num, x, y, len1, len2, w1, w2, ri) { var th; if (num > 0 && num <= 6) { th = this.rotate_theta((num - 1) * 60 - 150); ctx.beginPath(); ctx.arrow( x - len1 * this.size * Math.cos(th), y - len1 * this.size * Math.sin(th), x + len2 * this.size * Math.cos(th), y + len2 * this.size * Math.sin(th), [ 0, w1 * this.size, ri * this.size, w1 * this.size, ri * this.size, w2 * this.size, ] ); ctx.fill(); ctx.stroke(); } } draw_arrowcross(ctx, num, x, y) { var w1 = 0.025; var w2 = 0.12; var len1 = 0.5 * w1; //nemoto var len2 = 0.45; //tip var ri = -0.18; var th; for (var i = 0; i < 6; i++) { if (num[i] === 1) { th = this.rotate_theta(i * 60 - 150); ctx.beginPath(); ctx.arrow( x - len1 * this.size * Math.cos(th), y - len1 * this.size * Math.sin(th), x + len2 * this.size * Math.cos(th), y + len2 * this.size * Math.sin(th), [ 0, w1 * this.size, ri * this.size, w1 * this.size, ri * this.size, w2 * this.size, ] ); ctx.fill(); } } } draw_arroweight(ctx, num, x, y) { var len1 = -0.2; //nemoto var len2 = 0.45; //tip var w1 = 0.025; var w2 = 0.1; var ri = -0.15; for (var i = 0; i < 6; i++) { if (num[i] === 1) { this.draw_arrow(ctx, i + 1, x, y, len1, len2, w1, w2, ri); } } } rotate_theta(th) { th = th + this.theta; if (this.reflect[0] === -1) { th = (180 - th + 360) % 360; } if (this.reflect[1] === -1) { th = (360 - th + 360) % 360; } th = (th / 180) * Math.PI; return th; } }
); this.ctx.text( this[pu].number[i][0].slice(1, 2),
format.go
package authres import ( "sort" ) // Format formats an Authentication-Results header. func Format(identity string, results []Result) string { s := identity if len(results) == 0 { s += "; none" return s } for _, r := range results { method := resultMethod(r) value, params := r.format() s += "; " + method + "=" + string(value) + " " + formatParams(params) } return s } func resultMethod(r Result) string { switch r := r.(type) { case *AuthResult: return "auth" case *DKIMResult: return "dkim" case *DomainKeysResult: return "domainkeys" case *IPRevResult: return "iprev" case *SenderIDResult: return "sender-id" case *SPFResult: return "spf" case *GenericResult: return r.Method default: return "" } } func formatParams(params map[string]string) string { keys := make([]string, 0, len(params)) for k := range params { keys = append(keys, k) } sort.Strings(keys) s := "" i := 0 for _, k := range keys { if params[k] == ""
if i > 0 { s += " " } s += k + "=" + params[k] i++ } return s }
{ continue }
config.js
import '@storybook/addon-console'; import { configure, addDecorator } from '@storybook/react'; import { withPropsTable } from 'storybook-addon-react-docgen'; import { withKnobs } from '@storybook/addon-knobs'; addDecorator(withPropsTable); addDecorator(withKnobs); function
() { require('../stories'); // eslint-disable-line global-require } configure(loadStories, module);
loadStories
vpn_site.py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._inputs import * __all__ = ['VpnSiteArgs', 'VpnSite'] @pulumi.input_type class VpnSiteArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], address_space: Optional[pulumi.Input['AddressSpaceArgs']] = None, bgp_properties: Optional[pulumi.Input['BgpSettingsArgs']] = None, device_properties: Optional[pulumi.Input['DevicePropertiesArgs']] = None, id: Optional[pulumi.Input[str]] = None, ip_address: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, site_key: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, virtual_wan: Optional[pulumi.Input['SubResourceArgs']] = None, vpn_site_name: Optional[pulumi.Input[str]] = None): """ The set of arguments for constructing a VpnSite resource. :param pulumi.Input[str] resource_group_name: The resource group name of the VpnSite. :param pulumi.Input['AddressSpaceArgs'] address_space: The AddressSpace that contains an array of IP address ranges. :param pulumi.Input['BgpSettingsArgs'] bgp_properties: The set of bgp properties. :param pulumi.Input['DevicePropertiesArgs'] device_properties: The device properties :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] ip_address: The ip-address for the vpn-site. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] site_key: The key for vpn-site that can be used for connections. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. :param pulumi.Input['SubResourceArgs'] virtual_wan: The VirtualWAN to which the vpnSite belongs :param pulumi.Input[str] vpn_site_name: The name of the VpnSite being created or updated. """ pulumi.set(__self__, "resource_group_name", resource_group_name) if address_space is not None: pulumi.set(__self__, "address_space", address_space) if bgp_properties is not None: pulumi.set(__self__, "bgp_properties", bgp_properties) if device_properties is not None: pulumi.set(__self__, "device_properties", device_properties) if id is not None: pulumi.set(__self__, "id", id) if ip_address is not None: pulumi.set(__self__, "ip_address", ip_address) if location is not None: pulumi.set(__self__, "location", location) if site_key is not None: pulumi.set(__self__, "site_key", site_key) if tags is not None: pulumi.set(__self__, "tags", tags) if virtual_wan is not None: pulumi.set(__self__, "virtual_wan", virtual_wan) if vpn_site_name is not None: pulumi.set(__self__, "vpn_site_name", vpn_site_name) @property @pulumi.getter(name="resourceGroupName") def resource_group_name(self) -> pulumi.Input[str]: """ The resource group name of the VpnSite. """ return pulumi.get(self, "resource_group_name") @resource_group_name.setter def resource_group_name(self, value: pulumi.Input[str]): pulumi.set(self, "resource_group_name", value) @property @pulumi.getter(name="addressSpace") def address_space(self) -> Optional[pulumi.Input['AddressSpaceArgs']]: """ The AddressSpace that contains an array of IP address ranges. """ return pulumi.get(self, "address_space") @address_space.setter def address_space(self, value: Optional[pulumi.Input['AddressSpaceArgs']]): pulumi.set(self, "address_space", value) @property @pulumi.getter(name="bgpProperties") def bgp_properties(self) -> Optional[pulumi.Input['BgpSettingsArgs']]:
@bgp_properties.setter def bgp_properties(self, value: Optional[pulumi.Input['BgpSettingsArgs']]): pulumi.set(self, "bgp_properties", value) @property @pulumi.getter(name="deviceProperties") def device_properties(self) -> Optional[pulumi.Input['DevicePropertiesArgs']]: """ The device properties """ return pulumi.get(self, "device_properties") @device_properties.setter def device_properties(self, value: Optional[pulumi.Input['DevicePropertiesArgs']]): pulumi.set(self, "device_properties", value) @property @pulumi.getter def id(self) -> Optional[pulumi.Input[str]]: """ Resource ID. """ return pulumi.get(self, "id") @id.setter def id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "id", value) @property @pulumi.getter(name="ipAddress") def ip_address(self) -> Optional[pulumi.Input[str]]: """ The ip-address for the vpn-site. """ return pulumi.get(self, "ip_address") @ip_address.setter def ip_address(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "ip_address", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: """ Resource location. """ return pulumi.get(self, "location") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "location", value) @property @pulumi.getter(name="siteKey") def site_key(self) -> Optional[pulumi.Input[str]]: """ The key for vpn-site that can be used for connections. """ return pulumi.get(self, "site_key") @site_key.setter def site_key(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "site_key", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ Resource tags. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "tags", value) @property @pulumi.getter(name="virtualWAN") def virtual_wan(self) -> Optional[pulumi.Input['SubResourceArgs']]: """ The VirtualWAN to which the vpnSite belongs """ return pulumi.get(self, "virtual_wan") @virtual_wan.setter def virtual_wan(self, value: Optional[pulumi.Input['SubResourceArgs']]): pulumi.set(self, "virtual_wan", value) @property @pulumi.getter(name="vpnSiteName") def vpn_site_name(self) -> Optional[pulumi.Input[str]]: """ The name of the VpnSite being created or updated. """ return pulumi.get(self, "vpn_site_name") @vpn_site_name.setter def vpn_site_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "vpn_site_name", value) class VpnSite(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None, bgp_properties: Optional[pulumi.Input[pulumi.InputType['BgpSettingsArgs']]] = None, device_properties: Optional[pulumi.Input[pulumi.InputType['DevicePropertiesArgs']]] = None, id: Optional[pulumi.Input[str]] = None, ip_address: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, site_key: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, virtual_wan: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, vpn_site_name: Optional[pulumi.Input[str]] = None, __props__=None): """ VpnSite Resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[pulumi.InputType['AddressSpaceArgs']] address_space: The AddressSpace that contains an array of IP address ranges. :param pulumi.Input[pulumi.InputType['BgpSettingsArgs']] bgp_properties: The set of bgp properties. :param pulumi.Input[pulumi.InputType['DevicePropertiesArgs']] device_properties: The device properties :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] ip_address: The ip-address for the vpn-site. :param pulumi.Input[str] location: Resource location. :param pulumi.Input[str] resource_group_name: The resource group name of the VpnSite. :param pulumi.Input[str] site_key: The key for vpn-site that can be used for connections. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags. :param pulumi.Input[pulumi.InputType['SubResourceArgs']] virtual_wan: The VirtualWAN to which the vpnSite belongs :param pulumi.Input[str] vpn_site_name: The name of the VpnSite being created or updated. """ ... @overload def __init__(__self__, resource_name: str, args: VpnSiteArgs, opts: Optional[pulumi.ResourceOptions] = None): """ VpnSite Resource. :param str resource_name: The name of the resource. :param VpnSiteArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(VpnSiteArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None, bgp_properties: Optional[pulumi.Input[pulumi.InputType['BgpSettingsArgs']]] = None, device_properties: Optional[pulumi.Input[pulumi.InputType['DevicePropertiesArgs']]] = None, id: Optional[pulumi.Input[str]] = None, ip_address: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, site_key: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, virtual_wan: Optional[pulumi.Input[pulumi.InputType['SubResourceArgs']]] = None, vpn_site_name: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = VpnSiteArgs.__new__(VpnSiteArgs) __props__.__dict__["address_space"] = address_space __props__.__dict__["bgp_properties"] = bgp_properties __props__.__dict__["device_properties"] = device_properties __props__.__dict__["id"] = id __props__.__dict__["ip_address"] = ip_address __props__.__dict__["location"] = location if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["site_key"] = site_key __props__.__dict__["tags"] = tags __props__.__dict__["virtual_wan"] = virtual_wan __props__.__dict__["vpn_site_name"] = vpn_site_name __props__.__dict__["etag"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20180701:VpnSite"), pulumi.Alias(type_="azure-native:network:VpnSite"), pulumi.Alias(type_="azure-nextgen:network:VpnSite"), pulumi.Alias(type_="azure-native:network/v20180401:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20180401:VpnSite"), pulumi.Alias(type_="azure-native:network/v20180601:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20180601:VpnSite"), pulumi.Alias(type_="azure-native:network/v20180801:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20180801:VpnSite"), pulumi.Alias(type_="azure-native:network/v20181001:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20181001:VpnSite"), pulumi.Alias(type_="azure-native:network/v20181101:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20181101:VpnSite"), pulumi.Alias(type_="azure-native:network/v20181201:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20181201:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190201:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190201:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190401:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190401:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190601:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190601:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190701:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190701:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190801:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190801:VpnSite"), pulumi.Alias(type_="azure-native:network/v20190901:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20190901:VpnSite"), pulumi.Alias(type_="azure-native:network/v20191101:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20191101:VpnSite"), pulumi.Alias(type_="azure-native:network/v20191201:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20191201:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200301:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200301:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200401:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200401:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200501:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200501:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200601:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200601:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200701:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200701:VpnSite"), pulumi.Alias(type_="azure-native:network/v20200801:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20200801:VpnSite"), pulumi.Alias(type_="azure-native:network/v20201101:VpnSite"), pulumi.Alias(type_="azure-nextgen:network/v20201101:VpnSite")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(VpnSite, __self__).__init__( 'azure-native:network/v20180701:VpnSite', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'VpnSite': """ Get an existing VpnSite resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = VpnSiteArgs.__new__(VpnSiteArgs) __props__.__dict__["address_space"] = None __props__.__dict__["bgp_properties"] = None __props__.__dict__["device_properties"] = None __props__.__dict__["etag"] = None __props__.__dict__["ip_address"] = None __props__.__dict__["location"] = None __props__.__dict__["name"] = None __props__.__dict__["provisioning_state"] = None __props__.__dict__["site_key"] = None __props__.__dict__["tags"] = None __props__.__dict__["type"] = None __props__.__dict__["virtual_wan"] = None return VpnSite(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="addressSpace") def address_space(self) -> pulumi.Output[Optional['outputs.AddressSpaceResponse']]: """ The AddressSpace that contains an array of IP address ranges. """ return pulumi.get(self, "address_space") @property @pulumi.getter(name="bgpProperties") def bgp_properties(self) -> pulumi.Output[Optional['outputs.BgpSettingsResponse']]: """ The set of bgp properties. """ return pulumi.get(self, "bgp_properties") @property @pulumi.getter(name="deviceProperties") def device_properties(self) -> pulumi.Output[Optional['outputs.DevicePropertiesResponse']]: """ The device properties """ return pulumi.get(self, "device_properties") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: """ Gets a unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter(name="ipAddress") def ip_address(self) -> pulumi.Output[Optional[str]]: """ The ip-address for the vpn-site. """ return pulumi.get(self, "ip_address") @property @pulumi.getter def location(self) -> pulumi.Output[str]: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter(name="siteKey") def site_key(self) -> pulumi.Output[Optional[str]]: """ The key for vpn-site that can be used for connections. """ return pulumi.get(self, "site_key") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="virtualWAN") def virtual_wan(self) -> pulumi.Output[Optional['outputs.SubResourceResponse']]: """ The VirtualWAN to which the vpnSite belongs """ return pulumi.get(self, "virtual_wan")
""" The set of bgp properties. """ return pulumi.get(self, "bgp_properties")
factory.go
// Copyright 2022 The hyperfunction Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by informer-gen. DO NOT EDIT. package externalversions import ( reflect "reflect" sync "sync" time "time" versioned "github.com/hyperfunction/hyperfunction/pkg/client/clientset/versioned" core "github.com/hyperfunction/hyperfunction/pkg/client/informers/externalversions/core" internalinterfaces "github.com/hyperfunction/hyperfunction/pkg/client/informers/externalversions/internalinterfaces" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" ) // SharedInformerOption defines the functional option type for SharedInformerFactory. type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory type sharedInformerFactory struct { client versioned.Interface namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc lock sync.Mutex defaultResync time.Duration customResync map[reflect.Type]time.Duration informers map[reflect.Type]cache.SharedIndexInformer // startedInformers is used for tracking which informers have been started. // This allows Start() to be called multiple times safely. startedInformers map[reflect.Type]bool } // WithCustomResyncConfig sets a custom resync period for the specified informer types. func
(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { for k, v := range resyncConfig { factory.customResync[reflect.TypeOf(k)] = v } return factory } } // WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { factory.tweakListOptions = tweakListOptions return factory } } // WithNamespace limits the SharedInformerFactory to the specified namespace. func WithNamespace(namespace string) SharedInformerOption { return func(factory *sharedInformerFactory) *sharedInformerFactory { factory.namespace = namespace return factory } } // NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { return NewSharedInformerFactoryWithOptions(client, defaultResync) } // NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. // Listers obtained via this SharedInformerFactory will be subject to the same filters // as specified here. // Deprecated: Please use NewSharedInformerFactoryWithOptions instead func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) } // NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { factory := &sharedInformerFactory{ client: client, namespace: v1.NamespaceAll, defaultResync: defaultResync, informers: make(map[reflect.Type]cache.SharedIndexInformer), startedInformers: make(map[reflect.Type]bool), customResync: make(map[reflect.Type]time.Duration), } // Apply all options for _, opt := range options { factory = opt(factory) } return factory } // Start initializes all requested informers. func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { f.lock.Lock() defer f.lock.Unlock() for informerType, informer := range f.informers { if !f.startedInformers[informerType] { go informer.Run(stopCh) f.startedInformers[informerType] = true } } } // WaitForCacheSync waits for all started informers' cache were synced. func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { informers := func() map[reflect.Type]cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informers := map[reflect.Type]cache.SharedIndexInformer{} for informerType, informer := range f.informers { if f.startedInformers[informerType] { informers[informerType] = informer } } return informers }() res := map[reflect.Type]bool{} for informType, informer := range informers { res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) } return res } // InternalInformerFor returns the SharedIndexInformer for obj using an internal // client. func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informerType := reflect.TypeOf(obj) informer, exists := f.informers[informerType] if exists { return informer } resyncPeriod, exists := f.customResync[informerType] if !exists { resyncPeriod = f.defaultResync } informer = newFunc(f.client, resyncPeriod) f.informers[informerType] = informer return informer } // SharedInformerFactory provides shared informers for resources in all known // API group versions. type SharedInformerFactory interface { internalinterfaces.SharedInformerFactory ForResource(resource schema.GroupVersionResource) (GenericInformer, error) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool Core() core.Interface } func (f *sharedInformerFactory) Core() core.Interface { return core.New(f, f.namespace, f.tweakListOptions) }
WithCustomResyncConfig
config.rs
use crate::Feerate; use bitcoin::secp256k1::rand::{CryptoRng, RngCore}; use bitcoin::Network; use minimint_api::config::GenerateConfig; use minimint_api::{CompressedPublicKey, PeerId, PegInDescriptor}; use miniscript::descriptor::Wsh; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WalletConfig { pub network: Network, pub peg_in_descriptor: PegInDescriptor, pub peer_peg_in_keys: BTreeMap<PeerId, CompressedPublicKey>, pub peg_in_key: secp256k1::SecretKey, pub finalty_delay: u32, pub default_fee: Feerate, pub btc_rpc_address: String, pub btc_rpc_user: String, pub btc_rpc_pass: String, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WalletClientConfig { pub peg_in_descriptor: PegInDescriptor, pub network: Network, } impl GenerateConfig for WalletConfig { type Params = (); type ClientConfig = WalletClientConfig; fn
( peers: &[PeerId], max_evil: usize, _params: &Self::Params, mut rng: impl RngCore + CryptoRng, ) -> (BTreeMap<PeerId, Self>, Self::ClientConfig) { let secp = secp256k1::Secp256k1::new(); let btc_pegin_keys = peers .iter() .map(|&id| (id, secp.generate_keypair(&mut rng))) .collect::<Vec<_>>(); let peg_in_descriptor = PegInDescriptor::Wsh( Wsh::new_sortedmulti( peers.len() - max_evil, btc_pegin_keys .iter() .map(|(_, (_, pk))| CompressedPublicKey { key: *pk }) .collect(), ) .unwrap(), ); let wallet_cfg = btc_pegin_keys .iter() .map(|(id, (sk, _))| { let cfg = WalletConfig { network: Network::Regtest, peg_in_descriptor: peg_in_descriptor.clone(), // TODO: remove redundancy? peer_peg_in_keys: btc_pegin_keys .iter() .map(|(peer_id, (_, pk))| (*peer_id, CompressedPublicKey { key: *pk })) .collect(), peg_in_key: *sk, finalty_delay: 10, default_fee: Feerate { sats_per_kvb: 2000 }, btc_rpc_address: "127.0.0.1:18443".to_string(), btc_rpc_user: "bitcoin".to_string(), btc_rpc_pass: "bitcoin".to_string(), }; (*id, cfg) }) .collect(); let client_cfg = WalletClientConfig { peg_in_descriptor, network: Network::Regtest, }; (wallet_cfg, client_cfg) } }
trusted_dealer_gen