code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace MF\QueryBuilderComposer; use Doctrine\ORM\QueryBuilder; interface Modifier { public function __invoke(QueryBuilder $queryBuilder): QueryBuilder; }
MortalFlesh/php-query-builder-composer
src/Modifier.php
PHP
mit
170
package backup // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // ProtectionPolicyOperationStatusesClient is the open API 2.0 Specs for Azure RecoveryServices Backup service type ProtectionPolicyOperationStatusesClient struct { BaseClient } // NewProtectionPolicyOperationStatusesClient creates an instance of the ProtectionPolicyOperationStatusesClient // client. func NewProtectionPolicyOperationStatusesClient(subscriptionID string) ProtectionPolicyOperationStatusesClient { return NewProtectionPolicyOperationStatusesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewProtectionPolicyOperationStatusesClientWithBaseURI creates an instance of the // ProtectionPolicyOperationStatusesClient client using a custom endpoint. Use this when interacting with an Azure // cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewProtectionPolicyOperationStatusesClientWithBaseURI(baseURI string, subscriptionID string) ProtectionPolicyOperationStatusesClient { return ProtectionPolicyOperationStatusesClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get provides the status of the asynchronous operations like backup, restore. The status can be in progress, // completed // or failed. You can refer to the Operation Status enum for all the possible states of an operation. Some operations // create jobs. This method returns the list of jobs associated with operation. // Parameters: // vaultName - the name of the recovery services vault. // resourceGroupName - the name of the resource group where the recovery services vault is present. // policyName - backup policy name whose operation's status needs to be fetched. // operationID - operation ID which represents an operation whose status needs to be fetched. func (client ProtectionPolicyOperationStatusesClient) Get(ctx context.Context, vaultName string, resourceGroupName string, policyName string, operationID string) (result OperationStatus, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ProtectionPolicyOperationStatusesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, vaultName, resourceGroupName, policyName, operationID) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionPolicyOperationStatusesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "backup.ProtectionPolicyOperationStatusesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "backup.ProtectionPolicyOperationStatusesClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client ProtectionPolicyOperationStatusesClient) GetPreparer(ctx context.Context, vaultName string, resourceGroupName string, policyName string, operationID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "operationId": autorest.Encode("path", operationID), "policyName": autorest.Encode("path", policyName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vaultName": autorest.Encode("path", vaultName), } const APIVersion = "2021-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}/operations/{operationId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ProtectionPolicyOperationStatusesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ProtectionPolicyOperationStatusesClient) GetResponder(resp *http.Response) (result OperationStatus, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
Azure/azure-sdk-for-go
services/recoveryservices/mgmt/2021-12-01/backup/protectionpolicyoperationstatuses.go
GO
mit
5,253
package servicebus // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // QueuesClient is the client for the Queues methods of the Servicebus service. type QueuesClient struct { BaseClient } // NewQueuesClient creates an instance of the QueuesClient client. func NewQueuesClient(subscriptionID string) QueuesClient { return NewQueuesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewQueuesClientWithBaseURI creates an instance of the QueuesClient client using a custom endpoint. Use this when // interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewQueuesClientWithBaseURI(baseURI string, subscriptionID string) QueuesClient { return QueuesClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates a Service Bus queue. This operation is idempotent. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // parameters - parameters supplied to create or update a queue resource. func (client QueuesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (result SBQueue, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, queueName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure responding to request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client QueuesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (*http.Request, error) { pathParameters := map[string]interface{}{ "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } parameters.SystemData = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client QueuesClient) CreateOrUpdateResponder(resp *http.Response) (result SBQueue, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // CreateOrUpdateAuthorizationRule creates an authorization rule for a queue. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // authorizationRuleName - the authorization rule name. // parameters - the shared access authorization rule. func (client QueuesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (result SBAuthorizationRule, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.CreateOrUpdateAuthorizationRule") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: authorizationRuleName, Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties.Rights", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", err.Error()) } req, err := client.CreateOrUpdateAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateAuthorizationRuleSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure sending request") return } result, err = client.CreateOrUpdateAuthorizationRuleResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure responding to request") return } return } // CreateOrUpdateAuthorizationRulePreparer prepares the CreateOrUpdateAuthorizationRule request. func (client QueuesClient) CreateOrUpdateAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationRuleName": autorest.Encode("path", authorizationRuleName), "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } parameters.SystemData = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateAuthorizationRuleSender sends the CreateOrUpdateAuthorizationRule request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) CreateOrUpdateAuthorizationRuleSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateAuthorizationRuleResponder handles the response to the CreateOrUpdateAuthorizationRule request. The method always // closes the http.Response Body. func (client QueuesClient) CreateOrUpdateAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes a queue from the specified namespace in a resource group. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. func (client QueuesClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result autorest.Response, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Delete") defer func() { sc := -1 if result.Response != nil { sc = result.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, queueName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure responding to request") return } return } // DeletePreparer prepares the Delete request. func (client QueuesClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) DeleteSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client QueuesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // DeleteAuthorizationRule deletes a queue authorization rule. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // authorizationRuleName - the authorization rule name. func (client QueuesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result autorest.Response, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.DeleteAuthorizationRule") defer func() { sc := -1 if result.Response != nil { sc = result.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: authorizationRuleName, Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "DeleteAuthorizationRule", err.Error()) } req, err := client.DeleteAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", nil, "Failure preparing request") return } resp, err := client.DeleteAuthorizationRuleSender(req) if err != nil { result.Response = resp err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure sending request") return } result, err = client.DeleteAuthorizationRuleResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure responding to request") return } return } // DeleteAuthorizationRulePreparer prepares the DeleteAuthorizationRule request. func (client QueuesClient) DeleteAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationRuleName": autorest.Encode("path", authorizationRuleName), "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteAuthorizationRuleSender sends the DeleteAuthorizationRule request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) DeleteAuthorizationRuleSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DeleteAuthorizationRuleResponder handles the response to the DeleteAuthorizationRule request. The method always // closes the http.Response Body. func (client QueuesClient) DeleteAuthorizationRuleResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get returns a description for the specified queue. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. func (client QueuesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBQueue, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, queueName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client QueuesClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client QueuesClient) GetResponder(resp *http.Response) (result SBQueue, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetAuthorizationRule gets an authorization rule for a queue by rule name. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // authorizationRuleName - the authorization rule name. func (client QueuesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.GetAuthorizationRule") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: authorizationRuleName, Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "GetAuthorizationRule", err.Error()) } req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", nil, "Failure preparing request") return } resp, err := client.GetAuthorizationRuleSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure sending request") return } result, err = client.GetAuthorizationRuleResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure responding to request") return } return } // GetAuthorizationRulePreparer prepares the GetAuthorizationRule request. func (client QueuesClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationRuleName": autorest.Encode("path", authorizationRuleName), "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always // closes the http.Response Body. func (client QueuesClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListAuthorizationRules gets all authorization rules for a queue. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. func (client QueuesClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules") defer func() { sc := -1 if result.sarlr.Response.Response != nil { sc = result.sarlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "ListAuthorizationRules", err.Error()) } result.fn = client.listAuthorizationRulesNextResults req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName, queueName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", nil, "Failure preparing request") return } resp, err := client.ListAuthorizationRulesSender(req) if err != nil { result.sarlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure sending request") return } result.sarlr, err = client.ListAuthorizationRulesResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure responding to request") return } if result.sarlr.hasNextLink() && result.sarlr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request. func (client QueuesClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always // closes the http.Response Body. func (client QueuesClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listAuthorizationRulesNextResults retrieves the next set of results, if any. func (client QueuesClient) listAuthorizationRulesNextResults(ctx context.Context, lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { req, err := lastResults.sBAuthorizationRuleListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListAuthorizationRulesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request") } result, err = client.ListAuthorizationRulesResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request") } return } // ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required. func (client QueuesClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListAuthorizationRules") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName, queueName) return } // ListByNamespace gets the queues within a namespace. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // skip - skip is only used if a previous operation returned a partial result. If a previous response contains // a nextLink element, the value of the nextLink element will include a skip parameter that specifies a // starting point to use for subsequent calls. // top - may be used to limit the number of results to the most recent N usageDetails. func (client QueuesClient) ListByNamespace(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace") defer func() { sc := -1 if result.sqlr.Response.Response != nil { sc = result.sqlr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: skip, Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, {Target: "skip", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}, }}}}, {TargetValue: top, Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, {Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, }}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "ListByNamespace", err.Error()) } result.fn = client.listByNamespaceNextResults req, err := client.ListByNamespacePreparer(ctx, resourceGroupName, namespaceName, skip, top) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", nil, "Failure preparing request") return } resp, err := client.ListByNamespaceSender(req) if err != nil { result.sqlr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure sending request") return } result.sqlr, err = client.ListByNamespaceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure responding to request") return } if result.sqlr.hasNextLink() && result.sqlr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListByNamespacePreparer prepares the ListByNamespace request. func (client QueuesClient) ListByNamespacePreparer(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "namespaceName": autorest.Encode("path", namespaceName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if skip != nil { queryParameters["$skip"] = autorest.Encode("query", *skip) } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByNamespaceSender sends the ListByNamespace request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) ListByNamespaceSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByNamespaceResponder handles the response to the ListByNamespace request. The method always // closes the http.Response Body. func (client QueuesClient) ListByNamespaceResponder(resp *http.Response) (result SBQueueListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByNamespaceNextResults retrieves the next set of results, if any. func (client QueuesClient) listByNamespaceNextResults(ctx context.Context, lastResults SBQueueListResult) (result SBQueueListResult, err error) { req, err := lastResults.sBQueueListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByNamespaceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure sending next results request") } result, err = client.ListByNamespaceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure responding to next results request") } return } // ListByNamespaceComplete enumerates all values, automatically crossing page boundaries as required. func (client QueuesClient) ListByNamespaceComplete(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListByNamespace") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByNamespace(ctx, resourceGroupName, namespaceName, skip, top) return } // ListKeys primary and secondary connection strings to the queue. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // authorizationRuleName - the authorization rule name. func (client QueuesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result AccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.ListKeys") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: authorizationRuleName, Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "ListKeys", err.Error()) } req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", nil, "Failure preparing request") return } resp, err := client.ListKeysSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure sending request") return } result, err = client.ListKeysResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure responding to request") return } return } // ListKeysPreparer prepares the ListKeys request. func (client QueuesClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationRuleName": autorest.Encode("path", authorizationRuleName), "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/ListKeys", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListKeysSender sends the ListKeys request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) ListKeysSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListKeysResponder handles the response to the ListKeys request. The method always // closes the http.Response Body. func (client QueuesClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // RegenerateKeys regenerates the primary or secondary connection strings to the queue. // Parameters: // resourceGroupName - name of the Resource group within the Azure subscription. // namespaceName - the namespace name // queueName - the queue name. // authorizationRuleName - the authorization rule name. // parameters - parameters supplied to regenerate the authorization rule. func (client QueuesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (result AccessKeys, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/QueuesClient.RegenerateKeys") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: namespaceName, Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, {TargetValue: queueName, Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: authorizationRuleName, Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("servicebus.QueuesClient", "RegenerateKeys", err.Error()) } req, err := client.RegenerateKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", nil, "Failure preparing request") return } resp, err := client.RegenerateKeysSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure sending request") return } result, err = client.RegenerateKeysResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure responding to request") return } return } // RegenerateKeysPreparer prepares the RegenerateKeys request. func (client QueuesClient) RegenerateKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationRuleName": autorest.Encode("path", authorizationRuleName), "namespaceName": autorest.Encode("path", namespaceName), "queueName": autorest.Encode("path", queueName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-06-01-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/regenerateKeys", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RegenerateKeysSender sends the RegenerateKeys request. The method will close the // http.Response Body if it receives an error. func (client QueuesClient) RegenerateKeysSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // RegenerateKeysResponder handles the response to the RegenerateKeys request. The method always // closes the http.Response Body. func (client QueuesClient) RegenerateKeysResponder(resp *http.Response) (result AccessKeys, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
Azure/azure-sdk-for-go
services/preview/servicebus/mgmt/2021-06-01-preview/servicebus/queues.go
GO
mit
49,392
<?php return array ( 'id' => 'docomo_n2701c_ver1', 'fallback' => 'docomo_generic_jap_ver2', 'capabilities' => array ( 'columns' => '11', 'max_image_width' => '121', 'rows' => '11', 'resolution_width' => '176', 'resolution_height' => '198', 'max_image_height' => '190', 'flash_lite_version' => '', ), );
cuckata23/wurfl-data
data/docomo_n2701c_ver1.php
PHP
mit
342
<?php namespace HMLB\Date\Tests\Localization; /* * This file is part of the Date package. * * (c) Hugues Maignol <hugues@hmlb.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use HMLB\Date\Date; use HMLB\Date\Tests\AbstractTestCase; class ItTest extends AbstractTestCase { public function testDiffForHumansLocalizedInItalian() { Date::setLocale('it'); $scope = $this; $this->wrapWithTestNow( function () use ($scope) { $d = Date::now()->addYear(); $scope->assertSame('1 anno da adesso', $d->diffForHumans()); $d = Date::now()->addYears(2); $scope->assertSame('2 anni da adesso', $d->diffForHumans()); } ); } }
hmlb/date
tests/Localization/ItTest.php
PHP
mit
840
// http://www.w3.org/2010/05/video/mediaevents.html var poppy = popcorn( [ vid_elem_ref | 'id_string' ] ); poppy // pass-through video control methods .load() .play() .pause() // property setters .currentTime( time ) // skip forward or backwards `time` seconds .playbackRate( rate ) .volume( delta ) .mute( [ state ] ) // sugar? .rewind() // to beginning + stop?? .loop( [ state ] ) // toggle looping // queuing (maybe unnecessary): // enqueue method w/ optional args .queue( 'method', args ) // enqueue arbitrary callback .queue(function(next){ /* do stuff */ next(); }) // clear the queue .clearQueue() // execute arbitrary code @ time poppy.exec( 1.23, function(){ // exec code }); // plugin factory sample popcorn.plugin( 'myPlugin' [, super_plugin ], init_options ); // call plugin (defined above) poppy.myPlugin( time, options ); // define subtitle plugin popcorn.plugin( 'subtitle', { }); poppy .subtitle( 1.5, { html: '<p>SUPER AWESOME MEANING</p>', duration: 5 }) .subtitle({ start: 1.5, end: 6.5, html: '<p>SUPER AWESOME MEANING</p>' }) .subtitle([ { start: 1.5, html: '<p>SUPER AWESOME MEANING</p>' }, { start: 2.5, end: 3.5, html: '<p>OTHER NEAT TEXT</p>' } ]) .data([ { subtitle: [ { start: 1.5, html: '<p>SUPER AWESOME MEANING</p>' }, { start: 2.5, end: 3.5, html: '<p>OTHER NEAT TEXT</p>' } ] } ]); // jQuery-dependent plugin, using $.ajax - extend popcorn.data popcorn.plugin( 'data', popcorn.data, { _setup: function( options ) { // called when plugin is first registered (?) }, _add: function( options ) { // called when popcorn.data is called // this == plugin (?) if ( typeof options === 'string' ) { $.ajax({ url: options // stuff }); } else { return this.super.data.apply( this, arguments ); } } }); poppy.data( '/data.php' ) // data.php returns JSON? /* poppy.twitter( dom_elem | 'id_of_dom_elem', options ); // multiple twitters?? FAIL poppy.twitter( 'load', options ); */ var widget1 = $(dom_elem).twitter( options ); // ui widget factory initializes twitter widget poppy.jQuery( 5.9, { elem: widget1, method: 'twitter', args: [ 'search', '@cowboy' ] }) poppy.jQuery( time, selector, methodname [, args... ] ); poppy.jQuery( 5.9, widget1, 'twitter', 'search', '@cowboy' ); poppy.jQuery( 5.9, '.div', 'css', 'color', 'red' ); poppy.jQuery( 5.9, '#form', 'submit' ); // sugar methods for jQuery $(selector).popcorn( time, methodname [, args... ] ); $(selector).popcorn( time, fn ); // another idea, using jQuery special events api $(selector).bind( 'popcorn', { time: 5.9 }, function(e){ $(this).css( 'color', 'red' ); }); // does $.fn[ methodname ].apply( $(selector), args );
rwaldron/butter
popcorn-js/popcorn-api-notes.js
JavaScript
mit
2,970
/* _____ __ _____________ _______ ______ ___________ / \| | \____ \__ \\_ __ \/ ___// __ \_ __ \ | Y Y \ | / |_> > __ \| | \/\___ \\ ___/| | \/ |__|_| /____/| __(____ /__| /____ >\___ >__| \/ |__| \/ \/ \/ Copyright (C) 2004 - 2020 Ingo Berg 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. 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. */ #if defined(MUPARSER_DLL) #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #include <windows.h> #endif #include <cassert> #include "muParserDLL.h" #include "muParser.h" #include "muParserInt.h" #include "muParserError.h" #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 26812) #endif #define MU_TRY \ try \ { #define MU_CATCH \ } \ catch (muError_t &e) \ { \ ParserTag *pTag = static_cast<ParserTag*>(a_hParser); \ pTag->exc = e; \ pTag->bError = true; \ if (pTag->errHandler) \ (pTag->errHandler)(a_hParser); \ } \ catch (...) \ { \ ParserTag *pTag = static_cast<ParserTag*>(a_hParser); \ pTag->exc = muError_t(mu::ecINTERNAL_ERROR); \ pTag->bError = true; \ if (pTag->errHandler) \ (pTag->errHandler)(a_hParser); \ } /** \file \brief This file contains the implementation of the DLL interface of muparser. */ typedef mu::ParserBase::exception_type muError_t; typedef mu::ParserBase muParser_t; int g_nBulkSize; class ParserTag { public: ParserTag(int nType) : pParser((nType == muBASETYPE_FLOAT) ? (mu::ParserBase*)new mu::Parser() : (nType == muBASETYPE_INT) ? (mu::ParserBase*)new mu::ParserInt() : nullptr) , exc() , errHandler(nullptr) , bError(false) , m_nParserType(nType) {} ~ParserTag() { delete pParser; } mu::ParserBase* pParser; mu::ParserBase::exception_type exc; muErrorHandler_t errHandler; bool bError; private: ParserTag(const ParserTag& ref); ParserTag& operator=(const ParserTag& ref); int m_nParserType; }; static muChar_t s_tmpOutBuf[2048]; //--------------------------------------------------------------------------- // // // unexported functions // // //--------------------------------------------------------------------------- inline muParser_t* AsParser(muParserHandle_t a_hParser) { return static_cast<ParserTag*>(a_hParser)->pParser; } inline ParserTag* AsParserTag(muParserHandle_t a_hParser) { return static_cast<ParserTag*>(a_hParser); } #if defined(_WIN32) BOOL APIENTRY DllMain(HANDLE /*hModule*/, DWORD ul_reason_for_call, LPVOID /*lpReserved*/) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif //--------------------------------------------------------------------------- // // // exported functions // // //--------------------------------------------------------------------------- API_EXPORT(void) mupSetVarFactory(muParserHandle_t a_hParser, muFacFun_t a_pFactory, void* pUserData) { MU_TRY muParser_t* p(AsParser(a_hParser)); p->SetVarFactory(a_pFactory, pUserData); MU_CATCH } /** \brief Create a new Parser instance and return its handle. */ API_EXPORT(muParserHandle_t) mupCreate(int nBaseType) { switch (nBaseType) { case muBASETYPE_FLOAT: return (void*)(new ParserTag(muBASETYPE_FLOAT)); case muBASETYPE_INT: return (void*)(new ParserTag(muBASETYPE_INT)); default: return nullptr; } } /** \brief Release the parser instance related with a parser handle. */ API_EXPORT(void) mupRelease(muParserHandle_t a_hParser) { MU_TRY ParserTag* p = static_cast<ParserTag*>(a_hParser); delete p; MU_CATCH } API_EXPORT(const muChar_t*) mupGetVersion(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); #ifndef _UNICODE sprintf(s_tmpOutBuf, "%s", p->GetVersion().c_str()); #else wsprintf(s_tmpOutBuf, _T("%s"), p->GetVersion().c_str()); #endif return s_tmpOutBuf; MU_CATCH return _T(""); } /** \brief Evaluate the expression. */ API_EXPORT(muFloat_t) mupEval(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); return p->Eval(); MU_CATCH return 0; } API_EXPORT(muFloat_t*) mupEvalMulti(muParserHandle_t a_hParser, int* nNum) { MU_TRY if (nNum == nullptr) throw std::runtime_error("Argument is null!"); muParser_t* const p(AsParser(a_hParser)); return p->Eval(*nNum); MU_CATCH return 0; } API_EXPORT(void) mupEvalBulk(muParserHandle_t a_hParser, muFloat_t* a_res, int nSize) { MU_TRY muParser_t* p(AsParser(a_hParser)); p->Eval(a_res, nSize); MU_CATCH } API_EXPORT(void) mupSetExpr(muParserHandle_t a_hParser, const muChar_t* a_szExpr) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->SetExpr(a_szExpr); MU_CATCH } API_EXPORT(void) mupRemoveVar(muParserHandle_t a_hParser, const muChar_t* a_szName) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->RemoveVar(a_szName); MU_CATCH } /** \brief Release all parser variables. \param a_hParser Handle to the parser instance. */ API_EXPORT(void) mupClearVar(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->ClearVar(); MU_CATCH } /** \brief Release all parser variables. \param a_hParser Handle to the parser instance. */ API_EXPORT(void) mupClearConst(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->ClearConst(); MU_CATCH } /** \brief Clear all user defined operators. \param a_hParser Handle to the parser instance. */ API_EXPORT(void) mupClearOprt(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->ClearOprt(); MU_CATCH } API_EXPORT(void) mupClearFun(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->ClearFun(); MU_CATCH } API_EXPORT(void) mupDefineFun0(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun0_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun1(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun1_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun2(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun2_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun3(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun3_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun4(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun4_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun5(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun5_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun6(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun6_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun7(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun7_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun8(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun8_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun9(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun9_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineFun10(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun10_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineBulkFun0(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun0_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun1(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun1_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun2(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun2_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun3(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun3_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun4(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun4_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun5(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun5_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun6(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun6_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun7(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun7_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun8(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun8_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun9(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun9_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineBulkFun10(muParserHandle_t a_hParser, const muChar_t* a_szName, muBulkFun10_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineStrFun1(muParserHandle_t a_hParser, const muChar_t* a_szName, muStrFun1_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineStrFun2(muParserHandle_t a_hParser, const muChar_t* a_szName, muStrFun2_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineStrFun3(muParserHandle_t a_hParser, const muChar_t* a_szName, muStrFun3_t a_pFun) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, false); MU_CATCH } API_EXPORT(void) mupDefineMultFun(muParserHandle_t a_hParser, const muChar_t* a_szName, muMultFun_t a_pFun, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineFun(a_szName, a_pFun, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineOprt(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun2_t a_pFun, muInt_t a_nPrec, muInt_t a_nOprtAsct, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineOprt(a_szName, a_pFun, a_nPrec, (mu::EOprtAssociativity)a_nOprtAsct, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineVar(muParserHandle_t a_hParser, const muChar_t* a_szName, muFloat_t* a_pVar) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineVar(a_szName, a_pVar); MU_CATCH } API_EXPORT(void) mupDefineBulkVar(muParserHandle_t a_hParser, const muChar_t* a_szName, muFloat_t* a_pVar) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineVar(a_szName, a_pVar); MU_CATCH } API_EXPORT(void) mupDefineConst(muParserHandle_t a_hParser, const muChar_t* a_szName, muFloat_t a_fVal) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineConst(a_szName, a_fVal); MU_CATCH } API_EXPORT(void) mupDefineStrConst(muParserHandle_t a_hParser, const muChar_t* a_szName, const muChar_t* a_szVal) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineStrConst(a_szName, a_szVal); MU_CATCH } API_EXPORT(const muChar_t*) mupGetExpr(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); // C# explodes when pMsg is returned directly. For some reason it can't access // the memory where the message lies directly. #ifndef _UNICODE sprintf(s_tmpOutBuf, "%s", p->GetExpr().c_str()); #else wsprintf(s_tmpOutBuf, _T("%s"), p->GetExpr().c_str()); #endif return s_tmpOutBuf; MU_CATCH return _T(""); } API_EXPORT(void) mupDefinePostfixOprt(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun1_t a_pOprt, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefinePostfixOprt(a_szName, a_pOprt, a_bAllowOpt != 0); MU_CATCH } API_EXPORT(void) mupDefineInfixOprt(muParserHandle_t a_hParser, const muChar_t* a_szName, muFun1_t a_pOprt, muBool_t a_bAllowOpt) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->DefineInfixOprt(a_szName, a_pOprt, a_bAllowOpt != 0); MU_CATCH } // Define character sets for identifiers API_EXPORT(void) mupDefineNameChars(muParserHandle_t a_hParser, const muChar_t* a_szCharset) { muParser_t* const p(AsParser(a_hParser)); p->DefineNameChars(a_szCharset); } API_EXPORT(void) mupDefineOprtChars(muParserHandle_t a_hParser, const muChar_t* a_szCharset) { muParser_t* const p(AsParser(a_hParser)); p->DefineOprtChars(a_szCharset); } API_EXPORT(void) mupDefineInfixOprtChars(muParserHandle_t a_hParser, const muChar_t* a_szCharset) { muParser_t* const p(AsParser(a_hParser)); p->DefineInfixOprtChars(a_szCharset); } /** \brief Get the number of variables defined in the parser. \param a_hParser [in] Must be a valid parser handle. \return The number of used variables. \sa mupGetExprVar */ API_EXPORT(int) mupGetVarNum(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::varmap_type VarMap = p->GetVar(); return (int)VarMap.size(); MU_CATCH return 0; // never reached } /** \brief Return a variable that is used in an expression. \param a_hParser [in] A valid parser handle. \param a_iVar [in] The index of the variable to return. \param a_szName [out] Pointer to the variable name. \param a_pVar [out] Pointer to the variable. \throw nothrow Prior to calling this function call mupGetExprVarNum in order to get the number of variables in the expression. If the parameter a_iVar is greater than the number of variables both a_szName and a_pVar will be set to zero. As a side effect this function will trigger an internal calculation of the expression undefined variables will be set to zero during this calculation. During the calculation user defined callback functions present in the expression will be called, this is unavoidable. */ API_EXPORT(void) mupGetVar(muParserHandle_t a_hParser, unsigned a_iVar, const muChar_t** a_szName, muFloat_t** a_pVar) { // A static buffer is needed for the name since i can't return the // pointer from the map. static muChar_t szName[1024]; MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::varmap_type VarMap = p->GetVar(); if (a_iVar >= VarMap.size()) { *a_szName = 0; *a_pVar = 0; return; } mu::varmap_type::const_iterator item; item = VarMap.begin(); for (unsigned i = 0; i < a_iVar; ++i) ++item; #ifndef _UNICODE strncpy(szName, item->first.c_str(), sizeof(szName)); #else wcsncpy(szName, item->first.c_str(), sizeof(szName)); #endif szName[sizeof(szName) - 1] = 0; *a_szName = &szName[0]; *a_pVar = item->second; return; MU_CATCH * a_szName = 0; *a_pVar = 0; } /** \brief Get the number of variables used in the expression currently set in the parser. \param a_hParser [in] Must be a valid parser handle. \return The number of used variables. \sa mupGetExprVar */ API_EXPORT(int) mupGetExprVarNum(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::varmap_type VarMap = p->GetUsedVar(); return (int)VarMap.size(); MU_CATCH return 0; // never reached } /** \brief Return a variable that is used in an expression. Prior to calling this function call mupGetExprVarNum in order to get the number of variables in the expression. If the parameter a_iVar is greater than the number of variables both a_szName and a_pVar will be set to zero. As a side effect this function will trigger an internal calculation of the expression undefined variables will be set to zero during this calculation. During the calculation user defined callback functions present in the expression will be called, this is unavoidable. \param a_hParser [in] A valid parser handle. \param a_iVar [in] The index of the variable to return. \param a_szName [out] Pointer to the variable name. \param a_pVar [out] Pointer to the variable. \throw nothrow */ API_EXPORT(void) mupGetExprVar(muParserHandle_t a_hParser, unsigned a_iVar, const muChar_t** a_szName, muFloat_t** a_pVar) { // A static buffer is needed for the name since i can't return the // pointer from the map. static muChar_t szName[1024]; MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::varmap_type VarMap = p->GetUsedVar(); if (a_iVar >= VarMap.size()) { *a_szName = 0; *a_pVar = 0; return; } mu::varmap_type::const_iterator item; item = VarMap.begin(); for (unsigned i = 0; i < a_iVar; ++i) ++item; #ifndef _UNICODE strncpy(szName, item->first.c_str(), sizeof(szName)); #else wcsncpy(szName, item->first.c_str(), sizeof(szName)); #endif szName[sizeof(szName) - 1] = 0; *a_szName = &szName[0]; *a_pVar = item->second; return; MU_CATCH * a_szName = 0; *a_pVar = 0; } /** \brief Return the number of constants defined in a parser. */ API_EXPORT(int) mupGetConstNum(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::valmap_type ValMap = p->GetConst(); return (int)ValMap.size(); MU_CATCH return 0; // never reached } API_EXPORT(void) mupSetArgSep(muParserHandle_t a_hParser, const muChar_t cArgSep) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->SetArgSep(cArgSep); MU_CATCH } API_EXPORT(void) mupResetLocale(muParserHandle_t a_hParser) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->ResetLocale(); MU_CATCH } API_EXPORT(void) mupSetDecSep(muParserHandle_t a_hParser, const muChar_t cDecSep) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->SetDecSep(cDecSep); MU_CATCH } API_EXPORT(void) mupSetThousandsSep(muParserHandle_t a_hParser, const muChar_t cThousandsSep) { MU_TRY muParser_t* const p(AsParser(a_hParser)); p->SetThousandsSep(cThousandsSep); MU_CATCH } //--------------------------------------------------------------------------- /** \brief Retrieve name and value of a single parser constant. \param a_hParser [in] a valid parser handle \param a_iVar [in] Index of the constant to query \param a_pszName [out] pointer to a null terminated string with the constant name \param [out] The constant value */ API_EXPORT(void) mupGetConst(muParserHandle_t a_hParser, unsigned a_iVar, const muChar_t** a_pszName, muFloat_t* a_fVal) { // A static buffer is needed for the name since i can't return the // pointer from the map. static muChar_t szName[1024]; MU_TRY muParser_t* const p(AsParser(a_hParser)); const mu::valmap_type ValMap = p->GetConst(); if (a_iVar >= ValMap.size()) { *a_pszName = 0; *a_fVal = 0; return; } mu::valmap_type::const_iterator item; item = ValMap.begin(); for (unsigned i = 0; i < a_iVar; ++i) ++item; #ifndef _UNICODE strncpy(szName, item->first.c_str(), sizeof(szName)); #else wcsncpy(szName, item->first.c_str(), sizeof(szName)); #endif szName[sizeof(szName) - 1] = 0; *a_pszName = &szName[0]; *a_fVal = item->second; return; MU_CATCH * a_pszName = 0; *a_fVal = 0; } /** \brief Add a custom value recognition function. */ API_EXPORT(void) mupAddValIdent(muParserHandle_t a_hParser, muIdentFun_t a_pFun) { MU_TRY muParser_t* p(AsParser(a_hParser)); p->AddValIdent(a_pFun); MU_CATCH } /** \brief Query if an error occurred. After querying the internal error bit will be reset. So a consecutive call will return false. */ API_EXPORT(muBool_t) mupError(muParserHandle_t a_hParser) { bool bError(AsParserTag(a_hParser)->bError); AsParserTag(a_hParser)->bError = false; return bError; } /** \brief Reset the internal error flag. */ API_EXPORT(void) mupErrorReset(muParserHandle_t a_hParser) { AsParserTag(a_hParser)->bError = false; } API_EXPORT(void) mupSetErrorHandler(muParserHandle_t a_hParser, muErrorHandler_t a_pHandler) { AsParserTag(a_hParser)->errHandler = a_pHandler; } /** \brief Return the message associated with the last error. */ API_EXPORT(const muChar_t*) mupGetErrorMsg(muParserHandle_t a_hParser) { ParserTag* const p(AsParserTag(a_hParser)); const muChar_t* pMsg = p->exc.GetMsg().c_str(); // C# explodes when pMsg is returned directly. For some reason it can't access // the memory where the message lies directly. #ifndef _UNICODE sprintf(s_tmpOutBuf, "%s", pMsg); #else wsprintf(s_tmpOutBuf, _T("%s"), pMsg); #endif return s_tmpOutBuf; } /** \brief Return the message associated with the last error. */ API_EXPORT(const muChar_t*) mupGetErrorToken(muParserHandle_t a_hParser) { ParserTag* const p(AsParserTag(a_hParser)); const muChar_t* pToken = p->exc.GetToken().c_str(); // C# explodes when pMsg is returned directly. For some reason it can't access // the memory where the message lies directly. #ifndef _UNICODE sprintf(s_tmpOutBuf, "%s", pToken); #else wsprintf(s_tmpOutBuf, _T("%s"), pToken); #endif return s_tmpOutBuf; } /** \brief Return the code associated with the last error. */ API_EXPORT(int) mupGetErrorCode(muParserHandle_t a_hParser) { return AsParserTag(a_hParser)->exc.GetCode(); } /** \brief Return the position associated with the last error. */ API_EXPORT(int) mupGetErrorPos(muParserHandle_t a_hParser) { return (int)AsParserTag(a_hParser)->exc.GetPos(); } API_EXPORT(muFloat_t*) mupCreateVar() { return new muFloat_t(0); } API_EXPORT(void) mupReleaseVar(muFloat_t* ptr) { delete ptr; } #if defined(_MSC_VER) #pragma warning(pop) #endif #endif // MUPARSER_DLL
Siv3D/OpenSiv3D
Siv3D/src/ThirdParty/muparser/muParserDLL.cpp
C++
mit
25,026
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DoctrineMongoDBBundle\Command; use Doctrine\ODM\MongoDB\Mapping\MappingException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Show information about mapped documents * * @author Benjamin Eberlei <kontakt@beberlei.de> * @author Jonathan H. Wage <jonwage@gmail.com> */ class InfoDoctrineODMCommand extends DoctrineODMCommand { protected function configure() { $this ->setName('doctrine:mongodb:mapping:info') ->addOption('dm', null, InputOption::VALUE_OPTIONAL, 'The document manager to use for this command.') ->setDescription('Show basic information about all mapped documents.') ->setHelp(<<<EOT The <info>doctrine:mapping:info</info> shows basic information about which documents exist and possibly if their mapping information contains errors or not. <info>./app/console doctrine:mapping:info</info> If you are using multiple document managers you can pick your choice with the <info>--dm</info> option: <info>./app/console doctrine:mapping:info --dm=default</info> EOT ); } protected function execute(InputInterface $input, OutputInterface $output) { $documentManagerName = $input->getOption('dm') ? $input->getOption('dm') : $this->container->getParameter('doctrine.odm.mongodb.default_document_manager'); $documentManagerService = sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName); /* @var $documentManager Doctrine\ODM\MongoDB\DocumentManager */ $documentManager = $this->container->get($documentManagerService); $documentClassNames = $documentManager->getConfiguration() ->getMetadataDriverImpl() ->getAllClassNames(); if (!$entityClassNames) { throw new \Exception( 'You do not have any mapped Doctrine MongoDB ODM documents for any of your bundles. '. 'Create a class inside the Document namespace of any of your bundles and provide '. 'mapping information for it with Annotations directly in the classes doc blocks '. 'or with XML/YAML in your bundles Resources/config/doctrine/metadata/mongodb directory.' ); } $output->write(sprintf("Found <info>%d</info> documents mapped in document manager <info>%s</info>:\n", count($documentClassNames), $documentManagerName), true); foreach ($documentClassNames AS $documentClassName) { try { $cm = $documentManager->getClassMetadata($documentClassName); $output->write("<info>[OK]</info> " . $documentClassName, true); } catch(MappingException $e) { $output->write("<error>[FAIL]</error> " . $documentClassName, true); $output->write("<comment>" . $e->getMessage()."</comment>", true); $output->write("", true); } } } }
ajessu/jobeet
vendor/symfony/src/Symfony/Bundle/DoctrineMongoDBBundle/Command/InfoDoctrineODMCommand.php
PHP
mit
3,442
module LiveScript module Source VERSION = '1.5.0' end end
Roonin-mx/livescript-source
lib/livescript/source/version.rb
Ruby
mit
66
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Topup extends MY_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */ public function __construct() { parent::__construct(); $this->load->model(array('admin_model','user_model')); getCurrentAccountStatus($role_id = array(1)); } public function index() { $session_data = $this->session->userdata('user_logged_in'); $role_id = $session_data['role_id']; $user_id = $session_data['user_id']; if($role_id == 1) { $this->load->library('form_validation'); $this->form_validation->set_rules('amount', 'Amount', 'trim|is_numeric|required|xss_clean|callback_amountchk'); $amount = $this->input->post('amount'); if($this->form_validation->run() == FALSE) { $data['title'] = 'Dashboard'; $data['content'] = 'super_admin/admin_home'; $this->load->view($this->layout_client,$data); } else { $topup_data=array( 'admin_id' => $user_id, 'topup_amount' => $amount, 'topup_status' => 1 ); $topup_id = topupAdminData($topup_data); if($topup_id){ redirect('super_admin/admin_home'); return "topup sucess"; } else { return "topup unsuccess"; } } }else { var_dump("incorrect url"); die(); } } public function amountchk() { if($this->input->post('amount')<0) { $this->form_validation->set_message('amount', 'Cant enter lessthan 0'); } } }
seegan/Myproj
application/controllers/super_admin/topup.php
PHP
mit
1,936
define(['myweb/jquery'], function ($) { 'use strict'; var error = function (message) { $('.form-feedback').removeClass('form-success').addClass('form-error').text(message).fadeIn(200); }; var success = function (message) { $('.form-feedback').removeClass('form-error').addClass('form-success').text(message).fadeIn(200); }; var clear = function () { $('.form-feedback').hide().removeClass('form-success form-error').empty(); }; return { error: error, success: success, clear: clear }; });
broekema41/Device-lab-access-point
static/js/message.js
JavaScript
mit
576
# encoding: UTF-8 include Vorax describe 'tablezip layout' do before(:each) do# {{{ @sp = Sqlplus.new('sqlplus') @sp.default_convertor = :tablezip @prep = [VORAX_CSTR, "set tab off", "set linesize 10000", "set markup html on", "set echo off", "set pause off", "set define &", "set termout on", "set verify off", "set pagesize 4"].join("\n") @result = "" end# }}} it 'should work with multiple statements' do# {{{ @sp.exec("select dummy d from dual;\nselect * from departments where id <= 2;", :prep => @prep) @result << @sp.read_output(32767) while @sp.busy? expected = <<OUTPUT SQL> D - X SQL> ID NAME DESCRIPTION -- ----------- ----------------------------------- 1 Bookkeeping This department is responsible for: - financial reporting - analysis - other boring tasks 2 Marketing   SQL> SQL> OUTPUT #puts @result @result.should eq(expected) end# }}} it 'should work with multi line records' do# {{{ @sp.exec("select * from departments where id <= 10;", :prep => @prep) @result << @sp.read_output(32767) while @sp.busy? expected = <<OUTPUT SQL> ID NAME DESCRIPTION -- ---------------- ----------------------------------- 1 Bookkeeping This department is responsible for: - financial reporting - analysis - other boring tasks 2 Marketing   3 Deliveries   4 CRM   ID NAME DESCRIPTION -- ---------------- ----------------------------------- 5 Legal Stuff   6 Management The bad guys department 7 Cooking   8 Public Relations   ID NAME DESCRIPTION -- ---------------- ----------------------------------- 9 Aquisitions   10 Cleaning   10 rows selected. SQL> SQL> OUTPUT #puts @result @result.should eq(expected) end# }}} it 'should work with accept prompts' do# {{{ begin pack_file = Tempfile.new(['vorax', '.sql']) @sp.exec("accept var prompt \"Enter var: \"\nprompt &var", :prep => @prep, :pack_file => pack_file.path) Timeout::timeout(10) { @result << @sp.read_output(32767) while @result !~ /Enter var: \z/ @sp.send_text("muci\n") @result << @sp.read_output(32767) while @result !~ /muci\n\z/ } ensure pack_file.unlink end end# }}} it 'should work with <pre> tags' do# {{{ @sp.exec("set autotrace traceonly explain\nselect * from dual;", :prep => @prep) @result << @sp.read_output(32767) while @sp.busy? @result.should match(/SELECT STATEMENT/) end# }}} after(:each) do# {{{ @sp.terminate end# }}} end
talek/vorax4
vorax/ruby/spec/tablezip_spec.rb
Ruby
mit
2,817
from django.contrib.admin.models import LogEntry from django.contrib.auth.models import User, Group, Permission from simple_history import register from celsius.tools import register_for_permission_handling register(User) register(Group) register_for_permission_handling(User) register_for_permission_handling(Group) register_for_permission_handling(Permission) register_for_permission_handling(LogEntry)
cytex124/celsius-cloud-backend
src/addons/management_user/admin.py
Python
mit
408
<!DOCTYPE html> <!--[if IE 8]> <html class="ie ie8"> <![endif]--> <!--[if IE 9]> <html class="ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html> <!--<![endif]--> <head> <!-- Basic --> <meta charset="utf-8"> <title>VirUCA</title> <meta name="keywords" content="" /> <meta name="description" content=""> <meta name="author" content=""> <!-- Mobile Metas --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Web Fonts --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800%7CShadows+Into+Light" rel="stylesheet" type="text/css"> <!-- Libs CSS --> <link rel="stylesheet" href="<?=base_url()?>vendor/bootstrap/css/bootstrap.css"> <link rel="stylesheet" href="<?=base_url()?>vendor/font-awesome/css/font-awesome.css"> <link rel="stylesheet" href="<?=base_url()?>vendor/owl-carousel/owl.carousel.css" media="screen"> <link rel="stylesheet" href="<?=base_url()?>vendor/owl-carousel/owl.theme.css" media="screen"> <link rel="stylesheet" href="<?=base_url()?>vendor/magnific-popup/magnific-popup.css" media="screen"> <link rel="stylesheet" href="<?=base_url()?>vendor/isotope/jquery.isotope.css" media="screen"> <link rel="stylesheet" href="<?=base_url()?>vendor/mediaelement/mediaelementplayer.css" media="screen"> <!-- Theme CSS --> <link rel="stylesheet" href="<?=base_url()?>css/theme.css"> <link rel="stylesheet" href="<?=base_url()?>css/theme-elements.css"> <link rel="stylesheet" href="<?=base_url()?>css/theme-blog.css"> <link rel="stylesheet" href="<?=base_url()?>css/theme-shop.css"> <link rel="stylesheet" href="<?=base_url()?>css/theme-animate.css"> <link rel="stylesheet" href="<?=base_url()?>css/panel.css?id=124"> <link rel="stylesheet" href="<?=base_url()?>css/tooltip.css"> <!-- Responsive CSS --> <link rel="stylesheet" href="<?=base_url()?>css/theme-responsive.css" /> <!-- Skin CSS --> <link rel="stylesheet" href="<?=base_url()?>css/skins/default.css"> <!-- Custom CSS --> <link rel="stylesheet" href="<?=base_url()?>css/custom.css"> <!-- Custom Loader --> <link rel="stylesheet" href="<?=base_url()?>css/loader.css"> <!-- Libs --> <script src="<?=base_url()?>vendor/jquery.js"></script> <!-- Custom JS --> <script src="<?=base_url()?>js/custom.js"></script> <!-- Head Libs --> <script src="<?=base_url()?>vendor/modernizr.js"></script> <!--[if IE]> <link rel="stylesheet" href="css/ie.css"> <![endif]--> <!--[if lte IE 8]> <script src="vendor/respond.js"></script> <![endif]--> <script type="text/javascript"> function AddFicha(idDiv, Texto) { document.getElementById(idDiv).innerHTML += Texto; } </script> </head> <body> <div id="preloader"><div id="loader">&nbsp;</div></div> <div class="body"> <?php $this->load->view('menuj_view');?> <div role="main" class="main"> <div class="container"> <!-- Errores de inserción. --> <?php if($this->session->flashdata('respuesta_ok')) { ?> <div class="modal"> <div class="ventana"> <div class="alert alert-success"> <?php echo $this->session->flashdata('respuesta_ok');?> </div> <span class="cerrar">Cerrar</span> </div> </div> <?php } ?> <?php if($this->session->flashdata('respuesta_ko')) { ?> <div class="modal"> <div class="ventana"> <div class="alert alert-danger"> <?php echo $this->session->flashdata('respuesta_ko'); ?> <span class="cerrar">Cerrar</span> </div> </div> </div> <?php } ?> <!-- Fin errores --> <!-- Información de la partida --> <?php foreach ($partida as $jugador) { $nJugadores = $jugador->nGrupos; $iId_Partida = $jugador->iId; $iTurno = $jugador->iTurno; $iId_Panel = $jugador->iId_Panel; $bFinalizada = $jugador->bFinalizada; } ?> <?php if ($bFinalizada) { echo "<br><blockquote><strong>La partida ha finalizado</strong>. En la siguiente tabla puedes ver cómo han quedado los grupos</blockquote>"; } ?> <div class="featured-box featured-box-primary"> <div class="box-content"> <?php echo "<div>"; // Hay que restablecer la partida. foreach ($resumen as $equipo) { echo "<div style='float:left; padding-left:30px;'>"; if ($equipo->iGrupo == $iTurno) echo "<span class='rojo'><b>Grupo ".$equipo->iGrupo."</b></span><br>"; else echo "<span>Grupo ".$equipo->iGrupo."</span><br>"; echo "<img src='".base_url()."/assets/img/".$equipo->iGrupo.".png' aling='center'><br>"; if ($equipo->iCasilla == 0) echo "Inicio"; else { // Comprobamos si hay que poner las medallas y regalos. echo "<div style='padding-top:5px;''>"; switch ($equipo->iPosJuego) { case '1': echo "<img src='".base_url()."/assets/img/gold.png' aling='center'><br>"; break; case '2': echo "<img src='".base_url()."/assets/img/silver.png' aling='center'><br>"; break; case '3': echo "<img src='".base_url()."/assets/img/bronze.png' aling='center'><br>"; break; default: if ($equipo->iPosJuego != 0) echo "<img src='".base_url()."/assets/img/gift.png' aling='center'><br>"; break; } echo "</div>"; if ($equipo->iPosJuego == 0) echo $equipo->iCasilla; } echo "</div>"; } echo "</div>"; ?> <br class="clear"> </div> </div> <!-- panel --> <?php // Botones if ($bFinalizada == 0) { ?> <input type="hidden" data-bb="pregunta"> <input type="button" class="btn btn-warning" data-bb="confirm" data-pn="<?=$iId_Panel;?>" data-id="<?=$iId_Partida;?>" data-gr="<?=$iTurno;?>" value="Tirar Dado"> <input type="button" class="btn btn-warning" data-bb="confirm2" data-id="<?=$iId_Partida;?>" value="Finalizar partida"> <input type="button" class="btn btn-warning" value="Salir" onclick="location.href='<?=base_url()?>index.php/jugar/salir/<?=$iId_Partida?>'"> <?php } else { ?> <input type="button" class="btn btn-warning" value="Listado de partidas" onclick="location.href='<?=base_url()?>index.php/partidas'"> <?php } if (!$bFinalizada) { // Pintamos el panel $contCasilla = 1; echo "<br class='clear'><br><div data-toggle='tooltip' title='Inicio' class='test fade' style='float:left;'> <img src='".base_url()."/assets/img/inicio.png' aling='center'></div>"; foreach ($casillas as $casilla) { // Pinto la casilla. echo "<div data-toggle='tooltip' title='".$casilla->sCategoria."' id='casilla".$contCasilla."' class='test circulo fade' style='background:".$casilla->sColor."; border: 1px dotted black;'>"; echo "<h4 style='margin:0 !important;' class='fuego'><b>".$contCasilla."</b></h4>"; // Dependiendo de la función de la casilla, pintaremos esa función. switch ($casilla->eFuncion) { case 'Viento': echo "<div style='padding-left:30px;'><img src='".base_url()."/assets/img/wind.png' aling='center'></div>"; break; case 'Retroceder': echo "<div style='padding-left:30px;'><img src='".base_url()."/assets/img/syringe.png' aling='center'></div>"; default: # code... break; } echo "</div>"; $contCasilla++; } echo "<div data-toggle='tooltip' title='Meta!' class='test fade' style='float:left;'> <img src='".base_url()."/assets/img/meta.png' aling='center'></div>"; // Ahora colocamos las fichas en sus celdas. echo "<div>"; // Hay que restablecer la partida. foreach ($resumen as $equipo) { if ($equipo->iCasilla != 0) { // Hay que colocar la ficha en la celda. $ficha = '<div class=ficha><img src='.base_url().'assets/img/'.$equipo->iGrupo.'.png?id=6></div>'; echo "<script>"; echo "AddFicha('casilla$equipo->iCasilla', '$ficha')"; echo "</script>"; } } // Fin de colocación de fichas. ?> <br class="clear"> <hr class="short"> <!-- Leyenda --> <blockquote> <h4>Leyenda.</h4> <ul> <li><img src="<?=base_url()?>assets/img/6.png" align="middle">&nbsp;&nbsp;Indica, según tu color, la posición en la que estás en el juego.</li> <li><img src="<?=base_url()?>assets/img/syringe.png" align="middle">&nbsp;&nbsp;Si aciertas la pregunta, guardas la posición, si no la aciertas vuelves a la casilla de <b>inicio</b></li> <li><img src="<?=base_url()?>assets/img/wind.png" align="middle">&nbsp;&nbsp;Si aciertas la pregunta, vas a la siguiente casilla de <b>viento</b>. Si no aciertas, vuelves a la casilla anterior.</li> </ul> </blockquote> <!-- Resumen de la partida --> <?php } // Cierra el if de la partida finalizada. if ($bFinalizada == 0) { ?> <input type="hidden" data-bb="pregunta"> <input type="button" class="btn btn-warning" data-bb="confirm" data-pn="<?=$iId_Panel;?>" data-id="<?=$iId_Partida;?>" data-gr="<?=$iTurno;?>" value="Tirar Dado"> <input type="button" class="btn btn-warning" data-bb="confirm2" data-id="<?=$iId_Partida;?>" value="Finalizar partida"> <input type="button" class="btn btn-warning" value="Salir" onclick="location.href='<?=base_url()?>index.php/jugar/salir/<?=$iId_Partida?>'"> <?php } else { ?> <input type="button" class="btn btn-warning" value="Listado de partidas" onclick="location.href='<?=base_url()?>index.php/partidas'"> <?php } ?> </div> </div> <?php $this->load->view('footer');?> </div> <script src="<?=base_url()?>vendor/jquery.appear.js"></script> <script src="<?=base_url()?>vendor/jquery.easing.js"></script> <script src="<?=base_url()?>vendor/jquery.cookie.js"></script> <script src="<?=base_url()?>vendor/bootstrap/js/bootstrap.js"></script> <?php if ($this->session->flashdata('respuesta_ok') || $this->session->flashdata('respuesta_ko')) { echo "<script type='text/javascript'>"; echo "$(document).ready(function(){"; echo "$('.modal').fadeIn();"; echo "$('.cerrar').click(function(){"; echo "$('.modal').fadeOut(300);"; echo "});});"; echo "</script>"; } ?> <script type="text/javascript"> $(window).load(function() { $('#preloader').fadeOut('slow'); $('body').css({'overflow':'visible'}); }); $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); </script> <!-- BOOT BOX --> <script src="<?=base_url()?>js/bootbox/boot.activate.js"></script> <script src="<?=base_url()?>js/bootbox/bootbox.min.js"></script> <script type="text/javascript"> function aleatorio(a,b) {return Math.round(Math.random()*(b-a)+parseInt(a));} bootbox.setDefaults({ locale: "es" }); $(function() { var cajas = {}; var forzar = {}; $(document).on("click", "input[data-bb]", function(e) { e.preventDefault(); var type = $(this).data("bb"); // Partida en curso var iId_Partida = $(this).data("id"); // Grupo que tiene el turno var iId_Grupo = $(this).data("gr"); // Panel var iId_Panel = $(this).data("pn"); if (typeof cajas[type] === 'function') { cajas[type](iId_Partida, iId_Grupo, iId_Panel); } else { if (typeof forzar[type] === 'function') forzar[type](iId_Partida, iId_Grupo, iId_Panel); } }); cajas.confirm = function(id, gr, pn) { var tirada = aleatorio(1,6); //var tirada = 1; var innerTxt = ""; innerTxt = innerTxt + '<div style="float:left; padding-left:5px; width:150px;"><img src="' + '<?=base_url()?>' + 'assets/img/dado'+tirada+'.png' + '"></div>'; innerTxt = innerTxt + '<div style="float:left; padding-left:10px; width:300px;"><blockquote><b>Grupo '+ gr +'</b>, has avanzado <b>'+tirada+'</b> posicion/es, a continuación vamos a formularte una pregunta ... ¿Preparado? </blockquote></div>'; innerTxt += "<br class='clear'>"; // Si confirma la tirada de dado, vamos a la página de preguntas. bootbox.confirm(innerTxt, function(result) { if (result == true) { location.href = '<?=base_url()?>index.php/jugar/' + id + '/' + pn + '/' + gr + '/' + tirada; } }); }; cajas.confirm2 = function(id, gr, pn) { var innerTxt = "Si finalizas la partida, no podrás volver a jugarla, el ranking de los jugadores quedará como hasta ahora. ¿Estás seguro/a que desea finalizar la partida de todos modos?"; innerTxt += "<br class='clear'>"; // Si confirma la tirada de dado, vamos a la página de preguntas. bootbox.confirm(innerTxt, function(result) { if (result == true) { location.href = '<?=base_url()?>index.php/jugar/finalizar/' + id; } }); }; }); </script> <!-- FIN BOOT --> </body> </html>
mariamartinmarin/virUCA
application/views/jugar.php
PHP
mit
17,711
namespace ConsoleStudentSystem.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class User { private ICollection<UserProfile> userProfiles; public User() { this.userProfiles = new HashSet<UserProfile>(); } public virtual ICollection<UserProfile> UserProfiles { get { return userProfiles; } set { userProfiles = value; } } } }
studware/Ange-Git
MyTelerikAcademyHomeWorks/DataBase/12.EntityFrameworkCodeFirst/ConsoleStudentSystem/ConsoleStudentSystem.Models/Student.cs
C#
mit
492
const gulp = require('gulp'), zip = require('gulp-zip'); /** * Metadata about the plugin. * * @var object */ const plugin = { name: 'example-plugin', directory: '.' } gulp.task('distribute', function () { let paths = [ 'vendor/twig/**/*', 'vendor/composer/**/*', 'vendor/autoload.php', 'src/**/*' ] let src = gulp.src(paths, { base: './' }) let archive = src.pipe(zip(`${plugin.name}.zip`)) return archive.pipe(gulp.dest(plugin.directory)) });
p810/wordpress-plugin-scaffold
gulpfile.js
JavaScript
mit
542
package com.management.dao.impl.calcs; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.management.bean.calculate.ProjectCalc; import com.management.bean.calculate.ProjectCalcs; import com.management.dao.calcs.ProjectCalcDao; import com.management.util.DBUtil; public class ProjectCalcDaoImpl implements ProjectCalcDao { @Override public List<ProjectCalc> find() { try { Connection conn = DBUtil.getConnection(); String sql = "select * from project_calc"; QueryRunner qr = new QueryRunner(); return qr.query(conn, sql, new BeanListHandler<>(ProjectCalc.class)); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void add(ProjectCalc c) { try { Connection conn = DBUtil.getConnection(); String sql = "insert into project_calc(rank,category,weight,high,low) values(?,?,?,?,?)"; QueryRunner qr = new QueryRunner(); Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow()}; qr.update(conn, sql, params); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void update(ProjectCalc c) { try { Connection conn = DBUtil.getConnection(); String sql = "update project_calc set rank=?,category=?,weight=?,high=?,low=? where id=?"; QueryRunner qr = new QueryRunner(); Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow(),c.getId()}; qr.update(conn, sql, params); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void delete(int id) { try { Connection conn = DBUtil.getConnection(); String sql = "delete from project_calc where id=?"; QueryRunner qr = new QueryRunner(); qr.update(conn, sql,id); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } }
ztmark/managementsystem
src/com/management/dao/impl/calcs/ProjectCalcDaoImpl.java
Java
mit
2,035
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Windows; using System.Windows.Forms; using System.Windows.Forms.Integration; using System.Windows.Media; using WPFControls; namespace FormsApp { partial class Form1 : Form { private ElementHost _ctrlHost; private SolidColorBrush _initBackBrush; private FontFamily _initFontFamily; private double _initFontSize; private FontStyle _initFontStyle; private FontWeight _initFontWeight; private SolidColorBrush _initForeBrush; private MyControl _wpfAddressCtrl; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { _ctrlHost = new ElementHost {Dock = DockStyle.Fill}; panel1.Controls.Add(_ctrlHost); _wpfAddressCtrl = new MyControl(); _wpfAddressCtrl.InitializeComponent(); _ctrlHost.Child = _wpfAddressCtrl; _wpfAddressCtrl.OnButtonClick += avAddressCtrl_OnButtonClick; _wpfAddressCtrl.Loaded += avAddressCtrl_Loaded; } private void avAddressCtrl_Loaded(object sender, EventArgs e) { _initBackBrush = _wpfAddressCtrl.MyControlBackground; _initForeBrush = _wpfAddressCtrl.MyControlForeground; _initFontFamily = _wpfAddressCtrl.MyControlFontFamily; _initFontSize = _wpfAddressCtrl.MyControlFontSize; _initFontWeight = _wpfAddressCtrl.MyControlFontWeight; _initFontStyle = _wpfAddressCtrl.MyControlFontStyle; } private void avAddressCtrl_OnButtonClick( object sender, MyControlEventArgs args) { if (args.IsOk) { lblAddress.Text = @"Street Address: " + args.MyStreetAddress; lblCity.Text = @"City: " + args.MyCity; lblName.Text = "Name: " + args.MyName; lblState.Text = "State: " + args.MyState; lblZip.Text = "Zip: " + args.MyZip; } else { lblAddress.Text = "Street Address: "; lblCity.Text = "City: "; lblName.Text = "Name: "; lblState.Text = "State: "; lblZip.Text = "Zip: "; } } private void radioBackgroundOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlBackground = _initBackBrush; } private void radioBackgroundLightGreen_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlBackground = new SolidColorBrush(Colors.LightGreen); } private void radioBackgroundLightSalmon_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlBackground = new SolidColorBrush(Colors.LightSalmon); } private void radioForegroundOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlForeground = _initForeBrush; } private void radioForegroundRed_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlForeground = new SolidColorBrush(Colors.Red); } private void radioForegroundYellow_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlForeground = new SolidColorBrush(Colors.Yellow); } private void radioFamilyOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontFamily = _initFontFamily; } private void radioFamilyTimes_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontFamily = new FontFamily("Times New Roman"); } private void radioFamilyWingDings_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontFamily = new FontFamily("WingDings"); } private void radioSizeOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontSize = _initFontSize; } private void radioSizeTen_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontSize = 10; } private void radioSizeTwelve_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontSize = 12; } private void radioStyleOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontStyle = _initFontStyle; } private void radioStyleItalic_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontStyle = FontStyles.Italic; } private void radioWeightOriginal_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontWeight = _initFontWeight; } private void radioWeightBold_CheckedChanged(object sender, EventArgs e) { _wpfAddressCtrl.MyControlFontWeight = FontWeights.Bold; } } } // </snippet1>
Microsoft/WPF-Samples
Migration and Interoperability/WindowsFormsHostingWpfControl/FormsApp/Form1.cs
C#
mit
5,369
using System.Collections.Immutable; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using Microsoft.Extensions.Primitives; namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceDefinitions.Reading; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public sealed class MoonDefinition : HitCountingResourceDefinition<Moon, int> { private readonly IClientSettingsProvider _clientSettingsProvider; protected override ResourceDefinitionExtensibilityPoints ExtensibilityPointsToTrack => ResourceDefinitionExtensibilityPoints.Reading; public MoonDefinition(IResourceGraph resourceGraph, IClientSettingsProvider clientSettingsProvider, ResourceDefinitionHitCounter hitCounter) : base(resourceGraph, hitCounter) { // This constructor will be resolved from the container, which means // you can take on any dependency that is also defined in the container. _clientSettingsProvider = clientSettingsProvider; } public override IImmutableSet<IncludeElementExpression> OnApplyIncludes(IImmutableSet<IncludeElementExpression> existingIncludes) { base.OnApplyIncludes(existingIncludes); if (!_clientSettingsProvider.IsMoonOrbitingPlanetAutoIncluded || existingIncludes.Any(include => include.Relationship.Property.Name == nameof(Moon.OrbitsAround))) { return existingIncludes; } RelationshipAttribute orbitsAroundRelationship = ResourceType.GetRelationshipByPropertyName(nameof(Moon.OrbitsAround)); return existingIncludes.Add(new IncludeElementExpression(orbitsAroundRelationship)); } public override QueryStringParameterHandlers<Moon> OnRegisterQueryableHandlersForQueryStringParameters() { base.OnRegisterQueryableHandlersForQueryStringParameters(); return new QueryStringParameterHandlers<Moon> { ["isLargerThanTheSun"] = FilterByRadius }; } private static IQueryable<Moon> FilterByRadius(IQueryable<Moon> source, StringValues parameterValue) { bool isFilterOnLargerThan = bool.Parse(parameterValue); return isFilterOnLargerThan ? source.Where(moon => moon.SolarRadius > 1m) : source.Where(moon => moon.SolarRadius <= 1m); } }
json-api-dotnet/JsonApiDotNetCore
test/JsonApiDotNetCoreTests/IntegrationTests/ResourceDefinitions/Reading/MoonDefinition.cs
C#
mit
2,427
/* * Author: Minho Kim (ISKU) * Date: March 3, 2018 * E-mail: minho.kim093@gmail.com * * https://github.com/ISKU/Algorithm * https://www.acmicpc.net/problem/13169 */ import java.util.*; public class Main { private static long[] array; private static int N; public static void main(String... args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); array = new long[N]; for (int i = 0; i < N; i++) array[i] = sc.nextInt(); System.out.print(sum(0, 0)); } private static long sum(int i, long value) { if (i == N) return value; return sum(i + 1, value + array[i]) ^ sum(i + 1, value); } }
ISKU/Algorithm
BOJ/13169/Main.java
Java
mit
630
from django import forms from miniURL.models import Redirection #Pour faire un formulaire depuis un modèle. (/!\ héritage différent) class RedirectionForm(forms.ModelForm): class Meta: model = Redirection fields = ('real_url', 'pseudo') # Pour récupérer des données cel apeut ce faire avec un POST # ou directement en donnant un objet du modele : #form = ArticleForm(instance=article) # article est bien entendu un objet d'Article quelconque dans la base de données # Le champs est ainsi préremplit. # Quand on a recu une bonne formeModele il suffit de save() pour la mettre en base
guillaume-havard/testdjango
sitetest/miniURL/forms.py
Python
mit
615
package pp.iloc.model; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import pp.iloc.model.Num.NumKind; import pp.iloc.model.Operand.Type; import pp.iloc.parse.FormatException; /** ILOC program. * @author Arend Rensink */ public class Program { /** Indexed list of all instructions in the program. */ private final List<Instr> instrList; /** * Indexed list of all operations in the program. * This is the flattened list of instructions. */ private final List<Op> opList; /** Mapping from labels defined in the program to corresponding * index locations. */ private final Map<Label, Integer> labelMap; /** (Partial) mapping from symbolic constants used in the program * to corresponding numeric values. */ private final Map<Num, Integer> symbMap; /** Creates a program with an initially empty instruction list. */ public Program() { this.instrList = new ArrayList<>(); this.opList = new ArrayList<>(); this.labelMap = new LinkedHashMap<>(); this.symbMap = new LinkedHashMap<>(); } /** Adds an instruction to the instruction list of this program. * @throws IllegalArgumentException if the instruction has a known label */ public void addInstr(Instr instr) { instr.setProgram(this); instr.setLine(this.opList.size()); if (instr.hasLabel()) { registerLabel(instr); } this.instrList.add(instr); for (Op op : instr) { this.opList.add(op); } } /** Registers the label of a given instruction. */ void registerLabel(Instr instr) { Label label = instr.getLabel(); Integer loc = this.labelMap.get(label); if (loc != null) { throw new IllegalArgumentException(String.format( "Label %s already occurred at location %d", label, loc)); } this.labelMap.put(label, instr.getLine()); } /** Returns the current list of instructions of this program. */ public List<Instr> getInstr() { return Collections.unmodifiableList(this.instrList); } /** Returns the operation at a given line number. */ public Op getOpAt(int line) { return this.opList.get(line); } /** Returns the size of the program, in number of operations. */ public int size() { return this.opList.size(); } /** * Returns the location at which a given label is defined, if any. * @return the location of an instruction with the label, or {@code -1} * if the label is undefined */ public int getLine(Label label) { Integer result = this.labelMap.get(label); return result == null ? -1 : result; } /** Assigns a fixed numeric value to a symbolic constant. * It is an error to assign to the same constant twice. * @param name constant name, without preceding '@' */ public void setSymb(Num symb, int value) { if (this.symbMap.containsKey(symb)) { throw new IllegalArgumentException("Constant '" + symb + "' already assigned"); } this.symbMap.put(symb, value); } /** * Returns the value with which a given symbol has been * initialised, if any. */ public Integer getSymb(Num symb) { return this.symbMap.get(symb); } /** * Returns the value with which a given named symbol has been * initialised, if any. * @param name name of the symbol, without '@'-prefix */ public Integer getSymb(String name) { return getSymb(new Num(name)); } /** * Checks for internal consistency, in particular whether * all used labels are defined. */ public void check() throws FormatException { List<String> messages = new ArrayList<>(); for (Instr instr : getInstr()) { for (Op op : instr) { messages.addAll(checkOpnds(op.getLine(), op.getArgs())); } } if (!messages.isEmpty()) { throw new FormatException(messages); } } private List<String> checkOpnds(int loc, List<Operand> opnds) { List<String> result = new ArrayList<>(); for (Operand opnd : opnds) { if (opnd instanceof Label) { if (getLine((Label) opnd) < 0) { result.add(String.format("Line %d: Undefined label '%s'", loc, opnd)); } } } return result; } /** * Returns a mapping from registers to line numbers * in which they appear. */ public Map<String, Set<Integer>> getRegLines() { Map<String, Set<Integer>> result = new LinkedHashMap<>(); for (Op op : this.opList) { for (Operand opnd : op.getArgs()) { if (opnd.getType() == Type.REG) { Set<Integer> ops = result.get(((Reg) opnd).getName()); if (ops == null) { result.put(((Reg) opnd).getName(), ops = new LinkedHashSet<>()); } ops.add(op.getLine()); } } } return result; } /** * Returns a mapping from (symbolic) variables to line numbers * in which they appear. */ public Map<String, Set<Integer>> getSymbLines() { Map<String, Set<Integer>> result = new LinkedHashMap<>(); for (Op op : this.opList) { for (Operand opnd : op.getArgs()) { if (!(opnd instanceof Num)) { continue; } if (((Num) opnd).getKind() != NumKind.SYMB) { continue; } String name = ((Num) opnd).getName(); Set<Integer> lines = result.get(name); if (lines == null) { result.put(name, lines = new LinkedHashSet<>()); } lines.add(op.getLine()); } } return result; } /** Returns a line-by-line printout of this program. */ @Override public String toString() { StringBuilder result = new StringBuilder(); for (Map.Entry<Num, Integer> symbEntry : this.symbMap.entrySet()) { result.append(String.format("%s <- %d%n", symbEntry.getKey() .getName(), symbEntry.getValue())); } for (Instr instr : getInstr()) { result.append(instr.toString()); result.append('\n'); } return result.toString(); } @Override public int hashCode() { return this.instrList.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Program)) { return false; } Program other = (Program) obj; if (!this.instrList.equals(other.instrList)) { return false; } return true; } /** Returns a string consisting of this program in a nice layout. */ public String prettyPrint() { StringBuilder result = new StringBuilder(); // first print the symbolic declaration map int idSize = 0; for (Num symb : this.symbMap.keySet()) { idSize = Math.max(idSize, symb.getName().length()); } for (Map.Entry<Num, Integer> symbEntry : this.symbMap.entrySet()) { result.append(String.format("%-" + idSize + "s <- %d%n", symbEntry .getKey().getName(), symbEntry.getValue())); } if (idSize > 0) { result.append('\n'); } // then print the instructions int labelSize = 0; int sourceSize = 0; int targetSize = 0; for (Instr i : getInstr()) { labelSize = Math.max(labelSize, i.toLabelString().length()); if (i instanceof Op && ((Op) i).getOpCode() != OpCode.out) { Op op = (Op) i; sourceSize = Math.max(sourceSize, op.toSourceString().length()); targetSize = Math.max(targetSize, op.toTargetString().length()); } } for (Instr i : getInstr()) { result.append(i.prettyPrint(labelSize, sourceSize, targetSize)); } return result.toString(); } }
tcoenraad/compiler-construction
lib/pp/iloc/model/Program.java
Java
mit
7,199
import { IHiveMindNeuron, IHiveMindNeurons } from './HiveMindNeurons'; import { UserInput } from '../../BasicUserInput'; import { RequestContext } from '../../BasicRequestContext'; import { INeuronsResponse, ISingleNeuronsResponse, SingleNeuronsResponse } from './NeuronsResponse'; import { INeuronResponse } from '../../neurons/responses/SimpleResponse'; import { NeuronsResponseFactory } from './NeuronsResponseFactory'; export class PureEmergentHiveMindNeurons implements IHiveMindNeurons { private neurons: IHiveMindNeuron[]; constructor(neurons: IHiveMindNeuron[]) { this.neurons = neurons; } public findMatch(userInput: UserInput, context: RequestContext,): Promise<INeuronsResponse> { return new Promise((resolve) => { let responses: ISingleNeuronsResponse[] = []; const neuronResponses: Array<Promise<INeuronResponse>> = []; for (let i = 0; i < this.neurons.length; i++) { const neuron = this.neurons[i]; const promiseResponse = neuron.process(userInput, context); neuronResponses.push(promiseResponse); promiseResponse.then((response: INeuronResponse) => { if (response.hasAnswer()) { responses.push(new SingleNeuronsResponse(neuron, response)); } }).catch(error => { console.error('FATAL Neuron: ' + neuron + ' rejected...' + error); }); } Promise.all( neuronResponses, ).then((allResolved: INeuronResponse[]) => { const toResolve = NeuronsResponseFactory.createMultiple(responses); this.placeNeuronsToTop(toResolve.getResponses().map(response => response.getFiredNeuron())); resolve(toResolve); }).catch(error => { console.error('A neuron rejected instead of resolved, ' + 'neurons are never allowed to reject. If this happens ' + 'the neuron either needs to be fixed with error handling to ' + 'make it resolve a Silence() response or the neuron should ' + 'be removed. Error: ' + error); }); }); } private placeNeuronsToTop(neurons: IHiveMindNeuron[]) { // reverse the neurons from highest to lowest -> lowest to highest, so the highest certainty is placed to the top // last, making it the new top neuron const neuronsReversed = neurons.concat([]).reverse(); neuronsReversed.forEach(toTop => { if (this.neurons.indexOf(toTop) > 0) { this.neurons = this.neurons.filter(neuron => neuron !== toTop); this.neurons = [toTop].concat(this.neurons); } }); } }
OFTechLabs/oratio
src/emergent/hivemind/neurons/PureEmergentHiveMindNeurons.ts
TypeScript
mit
2,881
require_relative 'spec_helper' require_relative '../lib/nixonpi/animations/easing' describe NixonPi::Easing do before :each do @object = Object.new @object.extend(NixonPi::Easing) end # @param [Object] x percent complete (0.0 - 1.0) # @param [Object] t elapsed time ms # @param [Object] b start value # @param [Object] c end value # @param [Object] d total duration in ms it 'should provide quadratic easing' do 1000.times.with_index do |x| # percent complete - val - start - end - max puts @object.ease_in_out_quad(x.to_f, 0.0, 255.0, 1000.0) end end end
danielkummer/nixon-pi
spec/easing_spec.rb
Ruby
mit
604
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 21:11:45 2017 @author: hubert """ import numpy as np import matplotlib.pyplot as plt class LiveBarGraph(object): """ """ def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'], ch_names=['TP9', 'AF7', 'AF8', 'TP10']): """ """ self.band_names = band_names self.ch_names = ch_names self.n_bars = self.band_names * self.ch_names self.x = self.fig, self.ax = plt.subplots() self.ax.set_ylim((0, 1)) y = np.zeros((self.n_bars,)) x = range(self.n_bars) self.rects = self.ax.bar(x, y) def update(self, new_y): [rect.set_height(y) for rect, y in zip(self.rects, new_y)] if __name__ == '__main__': bar = LiveBarGraph() plt.show() while True: bar.update(np.random.random(10)) plt.pause(0.1)
bcimontreal/bci_workshop
python/extra_stuff/livebargraph.py
Python
mit
940
require 'spec_helper' describe 'ssh::default' do let(:chef_run){ ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '12.04').converge(described_recipe) } it 'should include the ssh::client recipe' do expect(chef_run).to include_recipe('ssh::client') end it 'should include the ssh::server recipe' do expect(chef_run).to include_recipe('ssh::server') end end
ersmith/cookbook-ssh
spec/default_spec.rb
Ruby
mit
373
<?php namespace Ekyna\Bundle\CartBundle\Provider; use Ekyna\Bundle\CartBundle\Model\CartProviderInterface; use Ekyna\Bundle\OrderBundle\Entity\OrderRepository; use Ekyna\Component\Sale\Order\OrderInterface; use Ekyna\Component\Sale\Order\OrderTypes; use Symfony\Component\HttpFoundation\Session\SessionInterface; /** * Class CartProvider * @package Ekyna\Bundle\CartBundle\Provider * @author Étienne Dauvergne <contact@ekyna.com> */ class CartProvider implements CartProviderInterface { const KEY = 'cart_id'; /** * @var SessionInterface */ protected $session; /** * @var OrderRepository */ protected $repository; /** * @var OrderInterface */ protected $cart; /** * @var string */ protected $key; /** * Constructor. * * @param SessionInterface $session * @param OrderRepository $repository * @param string $key */ public function __construct(SessionInterface $session, OrderRepository $repository, $key = self::KEY) { $this->session = $session; $this->repository = $repository; $this->key = $key; } /** * {@inheritdoc} */ public function setCart(OrderInterface $cart) { $this->cart = $cart; $this->cart->setType(OrderTypes::TYPE_CART); $this->session->set($this->key, $cart->getId()); } /** * {@inheritdoc} */ public function clearCart() { $this->cart = null; $this->session->set($this->key, null); } /** * {@inheritdoc} */ public function hasCart() { if (null !== $this->cart) { return true; } if (null !== $cartId = $this->session->get($this->key, null)) { /** @var \Ekyna\Component\Sale\Order\OrderInterface $cart */ $cart = $this->repository->findOneBy([ 'id' => $cartId, 'type' => OrderTypes::TYPE_CART ]); if (null !== $cart) { $this->setCart($cart); return true; } else { $this->clearCart(); } } return false; } /** * {@inheritdoc} */ public function getCart() { if (!$this->hasCart()) { if (null === $this->cart) { $this->newCart(); } } return $this->cart; } /** * Creates a new cart. * * @return \Ekyna\Component\Sale\Order\OrderInterface */ private function newCart() { $this->clearCart(); $this->setCart($this->repository->createNew(OrderTypes::TYPE_CART)); return $this->cart; } }
ekyna/CartBundle
Provider/CartProvider.php
PHP
mit
2,736
<h1><?php echo $titulo_pagina; ?></h1> <p>Usuários cadastrados no sistema</p> <p class="alert bg-danger" style="display:none;"><strong>Mensagem!</strong> <span></span></p> <p><a href="<?php echo base_url().'admin/usuarios/cadastrar'; ?>" class="btn btn-primary">Cadastrar</a></p> <table class="table table-bordered table-hover table-condensed tablesorter" id="usuarios"> <thead> <tr> <th class="header col-md-6">Nome</th> <th class="header">Email</th> <th colspan="2" class="txtCenter">Ações</th> </tr> </thead> <tbody> <?php if(!empty($usuarios)) { foreach($usuarios as $key => $value) { echo ' <tr> <td>'.$value->nome.'</td> <td>'.$value->email.'</td> <td class="col-md-1"><a href="'.base_url().'admin/usuarios/cadastrar/'.$value->id.'" class="btn btn-default" title="Editar"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a></td> <td class="col-md-1"><a href="'.base_url().'admin/usuarios/excluir/'.$value->id.'" class="btn btn-danger" title="Excluir" onclick="return confirmar_exclusao(\'Usuário\')"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a></td> </tr> '; } } else { echo '<tr><td colspan="4"><em>Não há Usuários Cadastrados</em></td></tr>'; } ?> </tbody> <?php if($total_registros > $itens_por_pagina) { ?> <tfoot> <tr> <td colspan="4"><?php echo $paginador; ?></td> </tr> </tfoot> <?php } ?> </table>
bmarquesn/bmnprojetopiloto
application/views/admin/usuarios/listar.php
PHP
mit
1,435
# -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop()
KMPSUJ/lego_robot
pilot.py
Python
mit
4,781
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using Windows.Foundation.Collections; using Windows.Media; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using MixedRemoteViewCompositor.Network; namespace Viewer { public sealed partial class Playback : Page { private MediaExtensionManager mediaExtensionManager = null; private Connector connector = null; private Connection connection = null; public Playback() { this.InitializeComponent(); } private async void bnConnect_Click(object sender, RoutedEventArgs e) { ushort port = 0; if (UInt16.TryParse(this.txPort.Text, out port)) { if (string.IsNullOrEmpty(this.txAddress.Text)) { this.txAddress.Text = this.txAddress.PlaceholderText; } this.connector = new Connector(this.txAddress.Text, port); if (this.connector != null) { this.connection = await this.connector.ConnectAsync(); if(this.connection != null) { this.bnConnect.IsEnabled = false; this.bnClose.IsEnabled = true; this.bnStart.IsEnabled = true; this.bnStop.IsEnabled = false; this.connection.Disconnected += Connection_Disconnected; var propertySet = new PropertySet(); var propertySetDictionary = propertySet as IDictionary<string, object>; propertySet["Connection"] = this.connection; RegisterSchemeHandler(propertySet); } } } } private void bnClose_Click(object sender, RoutedEventArgs e) { CloseConnection(); } private void bnStart_Click(object sender, RoutedEventArgs e) { StartPlayback(); } private void bnStop_Click(object sender, RoutedEventArgs e) { StopPlayback(); } private void Connection_Disconnected(Connection sender) { CloseConnection(); } private void CloseConnection() { StopPlayback(); this.bnStart.IsEnabled = false; this.bnConnect.IsEnabled = true; this.bnClose.IsEnabled = false; if (this.connection != null) { this.connection.Disconnected -= Connection_Disconnected; this.connection.Uninitialize(); this.connection = null; } if (this.connector != null) { this.connector.Uninitialize(); this.connector = null; } } private void StartPlayback() { this.videoPlayer.Source = new Uri(string.Format("mrvc://{0}:{1}", this.txAddress.Text, this.txPort.Text)); this.bnStart.IsEnabled = false; this.bnStop.IsEnabled = true; } private void StopPlayback() { this.videoPlayer.Stop(); this.videoPlayer.Source = null; this.bnStart.IsEnabled = true; this.bnStop.IsEnabled = false; } public void RegisterSchemeHandler(PropertySet propertySet) { if (this.mediaExtensionManager == null) { this.mediaExtensionManager = new MediaExtensionManager(); } this.mediaExtensionManager.RegisterSchemeHandler("MixedRemoteViewCompositor.Media.MrvcSchemeHandler", "mrvc:", propertySet); } } }
jimshalo10/HoloLensCompanionKit
MixedRemoteViewCompositor/Samples/LowLatencyMRC/UWP/Viewer/Playback.xaml.cs
C#
mit
4,072
<?php class ModelTask { public $Model; public $MethodName; public $Request; public $ResponseInfo; public $Response; public $Headers; public static function Prepare(&$model, $methodName) { $newTask = new self; $newTask->Model = &$model; $newTask->MethodName = $methodName; $newTask->Request = null; $newTask->ResponseInfo = null; $newTask->Response = null; $newTask->Headers = null; return $newTask; } }
lekster/md_new
libraries/common/Rest/class.ModelTask.php
PHP
mit
431
/* * This code it's help you to check JS plugin function (e.g. jQuery) exist. * When function not exist, the code will auto reload JS plugin from your setting. * * plugin_name: It's your plugin function name (e.g. jQuery). The type is string. * reload_url: It's your reload plugin function URL. The type is string. * * Copyright 2015, opoepev (Matt, Paul.Lu, Yi-Chun Lu) * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ //Main code var checkJSPluginExist = function (plugin_name, reload_url, depend_plugin_name) { //window[plugin_name] || document.write('<script src="' + reload_url + '">\x3C/script>'); if (typeof depend_plugin_name !== 'undefined') { if (typeof window[depend_plugin_name][plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } } else { if (typeof window[plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } } return true; };
opoepev/checkJSPluginExist
checkJSPluginExist.js
JavaScript
mit
1,273
# -*- coding: utf-8 -*- from django.db import models from Corretor.base import CorretorException from Corretor.base import ExecutorException from Corretor.base import CompiladorException from Corretor.base import ComparadorException from Corretor.base import LockException from model_utils import Choices class RetornoCorrecao(models.Model): """Um modelo que possui informacoes sobre o retorno da correcao de uma questao(ou questao de avaliacao). """ TIPOS = Choices( (0,'loading',u'Loading'), (1,'compilacao',u'Compilação'), (2,'execucao',u'Execução'), (3,'comparacao',u'Comparação'), (4,'lock',u'Lock'), (5,'correto',u'Correto'), ) tipo = models.SmallIntegerField(u"Tipo",choices=TIPOS, default=TIPOS.loading) msg = models.TextField(u"Mensagem",blank=True,null=True) task_id = models.CharField(max_length=350,blank=True,null=True) class Meta: verbose_name = u'Retorno Correção' app_label = 'Corretor' def __unicode__(self): return "%s: %s" %(self.TIPOS[self.tipo][1],self.msg) def altera_dados(self,sucesso=True,erroException=None): """ Altera os dados do retorno atual para pegar os dados de erro ou para por a mensagem que foi com sucesso. """ tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" # print ">>altera_dados" # print ">>isinstance(erroException,CorretorException)",isinstance(erroException,CorretorException) if sucesso == True: # print ">>retorno.successful()" tipo = RetornoCorrecao.TIPOS.correto correcao_msg = "Correto!" elif isinstance(erroException,CorretorException): # print "erro: %s" % erroException.message if isinstance(erroException,ExecutorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.execucao if isinstance(erroException,CompiladorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.compilacao if isinstance(erroException,ComparadorException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.comparacao if isinstance(erroException,LockException): correcao_msg = erroException.message tipo = RetornoCorrecao.TIPOS.lock self.tipo = tipo self.msg = correcao_msg
arruda/amao
AMAO/apps/Corretor/models/retorno.py
Python
mit
2,633
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ur_PK" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;ShadowCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The BlackCoin developers Copyright © 2014 The ShadowCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>ایڈریس یا لیبل میں ترمیم کرنے پر ڈبل کلک کریں</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>نیا ایڈریس بنائیں</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your ShadowCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>چٹ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation> پتہ</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>چٹ کے بغیر</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>پاس فریز داخل کریں</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>نیا پاس فریز</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>نیا پاس فریز دہرائیں</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>بٹوا ان لاک</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>خفیہ کشائی کر یںبٹوے کے</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>پاس فریز تبدیل کریں</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>ShadowCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+280"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+242"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-308"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+250"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-247"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Send coins to a ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Modify configuration options for ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-200"/> <source>ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+178"/> <source>&amp;About ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>ShadowCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to ShadowCoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-284"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+288"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid ShadowCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. ShadowCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>رقم</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation> پتہ</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>چٹ کے بغیر</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid ShadowCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>ShadowCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start ShadowCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start ShadowCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the ShadowCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the ShadowCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting ShadowCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show ShadowCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting ShadowCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the ShadowCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the ShadowCoin-Qt help message to get a list with possible ShadowCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>ShadowCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>ShadowCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the ShadowCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the ShadowCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 SDC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>بیلنس:</translation> </message> <message> <location line="+16"/> <source>123.456 SDC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a ShadowCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>چٹ کے بغیر</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a ShadowCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified ShadowCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a ShadowCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter ShadowCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>رقم</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>ٹائپ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation> پتہ</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>رقم</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>کو بھیجا</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / A)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>تمام</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>آج</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>اس ہفتے</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>اس مہینے</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>پچھلے مہینے</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>اس سال</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>دیگر</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>کو بھیجا</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>ٹائپ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>چٹ</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation> پتہ</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>رقم</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>ShadowCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or shadowcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: shadowcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: shadowcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 32112 or testnet: 22112)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 51736 or testnet: 51996)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong ShadowCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=shadowcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;ShadowCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>یہ مدد کا پیغام</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. ShadowCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of ShadowCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart ShadowCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>غلط رقم</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>ناکافی فنڈز</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. ShadowCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation>نقص</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
hansacoin/hansacoin
src/qt/locale - Copy/bitcoin_ur_PK.ts
TypeScript
mit
107,848
<?php include $_SERVER['DOCUMENT_ROOT'] . '/snippets/document/header/index.php'; ?> <div class="layout-project"> <div class="project project_glow context-content"> <section class="project__layout"> <header class="project__header"> <div class="container"> <h1 class="project__title">Glow</h1> </div> </header> <main class="project__main"> <div class="project__image project__image_desktop"> <div class="container"> <div class="image"> <img class="image__tag" src="../assets/images/glow__home__1440-1600-browser.png" alt="Glowcon Layout Home"> </div> </div> </div> <div class="project__info"> <div class="container"> <div class="project__facts"> <ul class="list list_facts"> <li class="list__item">Project - WordPress Website</li> <li class="list__item">Role - Development</li> <li class="list__item">Agency - Bleech</li> <li class="list__item">Year - 2019</li> </ul> </div> </div> </div> <div class="project__image project__image_desktop"> <div class="container"> <div class="image"> <img class="image__tag" src="../assets/images/glow__media__1440-1600-browser.png" alt="Glowcon Media Example"> </div> </div> </div> </main> <footer class="project__footer"> <div class="container"> <a class="button button_circle" aria-label="Open Project URL" href="https://www.glowcon.de/" target="_blank" rel="noreferrer noopener"> <svg aria-hidden="true" width="44" height="44" viewBox="0 0 44 44" xmlns="https://www.w3.org/2000/svg"><path d="M29.22 25.1L44 10.32 33.68 0 18.9 14.78l4.457 4.456-4.12 4.12-4.457-4.455L0 33.68 10.32 44 25.1 29.22l-4.457-4.456 4.12-4.12 4.457 4.455zm-6.934 4.12L10.32 41.187 2.812 33.68 14.78 21.715l3.05 3.05-6.48 6.48 1.406 1.406 6.48-6.48 3.05 3.05zm-.572-14.44L33.68 2.813l7.507 7.506L29.22 22.285l-3.05-3.05 6.48-6.48-1.407-1.406-6.48 6.48-3.05-3.05z" fill-rule="evenodd"/></svg> </a> </div> </footer> </section> </div> </div> <?php include $_SERVER['DOCUMENT_ROOT'] . '/snippets/document/footer/index.php'; ?>
Booozz/portfolio-m
app/templates/project-glow.php
PHP
mit
2,356
<?php require "../zxcd9.php"; //$stmt = $db->prepare("SELECT * from fin_allotments where hrdbid=:id"); //$stmt->bindParam(':id', $_SESSION['id']); //$stmt->execute(); //$rowfa = $stmt->fetch(PDO::FETCH_ASSOC); //echo $rowfa['hrdbid']; // echo $_SESSION['id']; // while ($rowfa = $stmt->fetch(PDO::FETCH_ASSOC)) { // echo $rowfa['hrdbid'].'<br>'; // } $regionz = array("NCR", "CAR", "REGION I", "REGION II", "REGION III", "REGION IV-A", "REGION IV-B", "REGION V", "REGION VI", "REGION VII", "REGION VIII", "REGION IX", "REGION X", "REGION XI", "REGION XII", "CARAGA", "ARMM", "NIR"); //SELECT COUNT(region)as region,re FROM `fin_allotments` WHERE type="CMF" and region="NCR" $cmf = []; foreach ($regionz as $regvalue) { $stmt = $db->prepare("SELECT COUNT(region) as regioncount FROM fin_allotments WHERE region = '".$regvalue."' and type='CMF' "); $stmt->execute(); $row = $stmt->fetch(); $cmf[] = intval($row['regioncount']); } $dr = []; foreach ($regionz as $regvalue) { $stmt = $db->prepare("SELECT COUNT(region) as regioncount FROM fin_allotments WHERE region = '".$regvalue."' and type='DR'"); $stmt->execute(); $row = $stmt->fetch(); $dr[] = intval($row['regioncount']); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>SLP Online</title> <meta name="description" content="SLP DSWD Livelihood"/> <meta name="viewport" content="width=1000, initial-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="../imgs/favicon.ico" type="image/x-icon"> <link rel="icon" href="../imgs/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="../css/flatbootstrap.css"/> <script src="../js/jquery-1.10.2.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"></script> <script type="text/javascript" language="javascript" src="../js/jquery.dataTables.js"></script> <style> body { background-color: #f7f9fb; background-size: cover; font-family: "Lato"; } .navbar-nav > li > a, .navbar-brand { padding-top:15px !important; padding-bottom:0 !important; height: 40px; } .navbar {min-height:45px !important;background-color: #000} #bootstrapSelectForm .selectContainer .form-control-feedback { right: -15px; } .disabled { background:rgba(1,1,1,0.2); border:0px solid; cursor:progress; } .vcenter { min-height: 90%; min-height: 90vh; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-align : center; -webkit-align-items : center; -moz-box-align : center; -ms-flex-align : center; align-items : center; width: 100%; -webkit-box-pack : center; -moz-box-pack : center; -ms-flex-pack : center; -webkit-justify-content : center; justify-content : center; } table { border-collapse: inherit; } .slpdrop { margin-bottom:1em; } .slpdropsub { background: #000; color:#fff; } .slpdropsub li a { background: #000; color:#fff; } -webkit-tap-highlight-color: rgba(0,0,0,0); button { outline: none; } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { background: #000; } .dashpanel { border:solid 1px #c5d6de;margin:1em;margin-top:0;background:#fff;text-align: center; height:100%; border-radius: 4px; } .bluetext { color: #00ADDe; } .padfix { padding-right: 0; margin-bottom:1em; margin-right: 1em; } .padfix2{ padding-right:0em; padding-left: 1em; } .padfix3 { padding-left:1em; padding-right:0; } .padfix4 { padding: 1em; padding-right:0; } .dashpanelheader { font-weight:900;padding-top:0.5em;padding-left:1em;font-size:18px; margin-bottom: 0;text-align: left; } @media (min-width: 990px) { .slpdrop { font-weight:900; font-size:22px; } .padfix { padding-right: 0; margin-right: 0; margin-bottom: 0; } .padfix2{ padding-right:0em; padding-left: 2em; } .padfix3 { padding-left:0; padding-right: 1em; } .padfix4 { padding: 1em; padding-right:1em; } } .dashpanelsubhead { text-align:left;padding-left:1.2em;margin-bottom:0;padding-bottom:0; } thead th { text-align: center; cursor: pointer; } .dataTables_paginate { line-height:22px; text-align:left; } h3 { font-weight: 400 } .nopad { margin:0; padding:0; padding-top:4px; } .nopad::after { color: #ccc; content: attr(data-bg-text); display: block; font-size: 12px; text-align:right; line-height: 1; padding:0; margin:0; margin-top: 0px; position: relative; bottom: 0px; right: 0px; } .labelhover:hover { background: #000; color: #fff; } tr { text-align: center; } .glyphcenter { font-size:12px; padding-right:2px; } .dataTables_filter, .dataTables_info { display: none; } </style> </head> <body> <?php require "navfin.php"; ?> <script> $(function () { var colors = Highcharts.getOptions().colors; regtot = [2,3,34,5,3,2,3,2,2,2,2,2,2,22,34]; regconf = [2,3,34,5,3,2,3,2,2,2,2,2,2,22,3]; $('#cont1').highcharts({ chart: { type: 'column', backgroundColor: null, height: 150 }, title: { text: '' }, subtitle: { text: '' }, credits: { enabled: false }, legend: { enabled: false }, tooltip: { formatter: function() { var point = this.point, s = '<b>'+this.x+'</b><br>Total: <b>'+point.total+'</b><br>'+point.series.name+': <b>'+point.y.toFixed(0)+'</b>'; return s; }, hideDelay: 0 }, xAxis: { categories: [ 'NCR', 'CAR', 'I', 'II', 'III', 'IV-A', 'IV-B', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII', 'CARAGA', 'ARMM', 'NIR' ], crosshair: true, minorGridLineWidth: 0, minorTickWidth: 0, tickWidth: 0, labels: { enabled: true, style: { fontSize:'5px' } } }, yAxis: { min: 0, gridLineWidth: 0, title: '', labels: { enabled: false } }, plotOptions: { column: { pointPadding: 0, borderWidth: 0 }, series: { stacking: 'normal' } }, // series: [{ // name: 'CMF', // color: colors[3], // data: [23,23,55,23,15,09,18,20,50,33,38,21,12,10,40,20] // },{ // name: 'DR', // color: colors[8], // data: [43,12,44,22,10,08,25,67,32,10,29,56,19,10,40,20] //}] series: [{ name: 'CMF', color: colors[3], data: [<?php echo $cmf[0].",".$cmf[1].",".$cmf[2].",".$cmf[3].",".$cmf[4].",".$cmf[5].",".$cmf[6].",".$cmf[7].",".$cmf[8].",".$cmf[9].",".$cmf[10].",".$cmf[11].",".$cmf[12].",".$cmf[13].",".$cmf[14].",".$cmf[15].",".$cmf[16].",".$cmf[17]; ?>] },{ name: 'DR', color: colors[8], data: [<?php echo $dr[0].",".$dr[1].",".$dr[2].",".$dr[3].",".$dr[4].",".$dr[5].",".$dr[6].",".$dr[7].",".$dr[8].",".$dr[9].",".$dr[10].",".$dr[11].",".$dr[12].",".$dr[13].",".$dr[14].",".$dr[15].",".$dr[16].",".$dr[17]; ?>] }] }); }); function delcom(xx) { var r = confirm("This will permanently delete this record. Are you sure?"); if (r == true) { var formData = { 'action' : 'delallo', 'delid' : xx }; $.ajax({ type: "POST", url: "func.php", data: formData, success: function(data) { $("#sucsubtext").html("Record deleted"); $('#myModal').modal(); $('#myModal').on('hidden.bs.modal', function () {location.href = "../finance/allotments_add.php"; }); location.reload(); } }); } } function allotview(ee) { var formData = { 'editid' : ee }; $.ajax({ type: "POST", url: "allotments_view.php?id="+ee, data: formData, success: function(data) { if (data == "visitpage") { location.href="allotments_view.php?id="+ee; } } }); } </script> <script type="text/javascript" language="javascript" class="init"> var oTable = ""; $(document).ready(function() { function toTitleCase(str) { return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); } function parselimit(strz) { var m = new String(strz); if (m.length > 32) { m = m.substring(0,32); m = m+".."; } return m; } function com(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } function parseStatus(str) { if (str == "0") { status = "<span class='label label-primary'>Open</span>"; } else if (str == "1") { status = "<span class='label label-primary'>Proposed</span>"; } else if (str == "2") { status = "<span class='label label-warning'>In Progress</span>"; } else if (str == "3") { status = "<span class='label label-info'>Completed</span>"; } return status; } $.fn.DataTable.ext.pager.numbers_length = 5; oTable = $('#viewdata').dataTable({ "aProcessing": true, "aServerSide": true, "orderCellsTop": true, "ajax": "dt_allotments.php", "dom": '<"top">rt<"bottom"ip><"clear">', "aaSorting": [9,'desc'], "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { $(nRow).attr('id', aData[0]); // $(nRow).attr('subfeed', aData[1]); return nRow; }, "aoColumnDefs": [ { "aTargets":[7], "mData": null, "mRender": function( data, type, full) { return '<td>&#8369;'+com(data[7])+'</td>'; } }, { "aTargets":[9], "mData": null, "mRender": function( data, type, full) { var id='<?php echo $_SESSION['id']; ?>'; var lvl='<?php echo $_SESSION['permlvl']; ?>'; var d9=data[9]; if(lvl>0 || d9==id) { return '<td><span class=" glyphicon glyphicon-search" onclick="allotview('+data[0]+')"></span>&nbsp;<span class="glyphicon glyphicon-remove" onclick="delcom('+data[0]+')"></span></td>'; } else { return '<td><span class=" glyphicon glyphicon-search" onclick="allotview('+data[0]+')"></span></td>'; } } }, { "bVisible": false, "aTargets":[0] } ] }); $(document).ready(function() { tableshown=false; $("#searchme").keyup(function() { if (tableshown==false) { tableshown=true; } oTable.fnFilter(this.value); }); }); }); </script> <div class="row" style="margin:0;padding:0"> <div class="col-md-2"> <?php require "nav_side.php"; ?> </div> <div class="col-md-10"> <div class="row"> <div class="col-md-12"> <div style="border:solid 1px #c5d6de;background:#fff;text-align:left;padding:2em;margin-bottom:2em"> <div class="row"> <div class="col-md-4"> <h2 style="font-size:36px;margin-bottom:0em;margin-top:0em">Fund Allotments</h2> Encoded by SLP-NPMO <br><br> <a href="allotments_add.php"><button class="btn btn-info btn-sm">Add Fund Allotment</button></a> <button class="btn btn-success btn-sm" onclick="showsearch()"><span class="glyphicon glyphicon-search"></span>&nbsp; Search</button> <br> </div> <div class="col-md-8" id="cont1" style=""> </div> </div> <div class="row" style="margin-top:1em;margin-bottom:1em;display:none;" id="searchfields"> <div class="row" style="padding:2em;padding-bottom:1em"> <input class="col-md-12 form-control" placeholder="Search keywords ..." id="searchme"> </div> <div class="col-md-4"> <select class="form-control"> <option>Filter by Region</option> </select> </div> <div class="col-md-4"> <select class="form-control"> <option>Filter by Type</option> <option>CMF</option> <option>DR</option> </select> </div> <div class="col-md-4"> <select class="form-control"> <option>Filter by Fund Source</option> <option>SLP GAA - MD</option> <option>SLP GAA - EF</option> <option>BUB</option> <option>RRP</option> </select> </div> </div> <table class="table table-bordered table-hover" style="margin-top:2em;line-height:0.9;vertical-align:middle;border-top:2;padding-bottom:0;margin-bottom:0" id="viewdata"> <thead style="background:#f6f8fa"> <th></th> <th>Region</th> <th>Type</th> <th>Sub-Type</th> <th>Sub-Aro</th> <th>UACS</th> <th>Fund Source</th> <th>Amount</th> <th>Date</th> <th></th> </thead> <!-- <tr> <td>Region IV-B</td> <td>CMF</td> <td>Grant</td> <td>2348712398</td> <td>-</td> <td>SLP-EF</td> <td>468,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> <tr> <td>Region IV-B</td> <td>CMF</td> <td>Grant</td> <td>3021000003</td> <td>-</td> <td>SLP-MD</td> <td>268,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> <tr> <td>Region IV-B</td> <td>DR</td> <td>Admin</td> <td>-</td> <td>Travelling Expense</td> <td>PAMANA</td> <td>568,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> <tr data-toggle="tooltip" title="<div style='text-align:left'>Realigned to: <span style='font-weight:normal'>Training Expenses</span><br>Amount: <font color=red>-20,000.00</font><br>Original Amount: 188,232.00<br>Date: 09/27/2016</div>" data-html="true" data-placement="left" data-container="body"> <td>Region IV-B</td> <td>DR</td> <td>Admin</td> <td>-</td> <td>Salary</td> <td>BUB</td> <td>168,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> <tr data-toggle="tooltip" title="<div style='text-align:left'>Realigned from: <span style='font-weight:normal'>Salary</span><br>Amount: <span class='colgreen'>+20,000.00</span><br>Original Amount: 1,444,232.00<br>Date: 09/27/2016</div>" data-html="true" data-placement="left" data-container="body"> <td>NCR</td> <td>CMF</td> <td>Admin</td> <td>-</td> <td>Training Expenses</td> <td>RRP</td> <td>1,468,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> <tr> <td>Region X</td> <td>CMF</td> <td>Admin</td> <td>-</td> <td>Mobile</td> <td>RSF</td> <td>868,232.00</td> <td>06/17/2016</td> <td><span class="glyphicon glyphicon-edit"></span> <span class="glyphicon glyphicon-remove"></span></td> </tr> --> </table> <button class="btn btn-primary btn-xs" style="margin-top:0.5em;margin-left:3px">Export to Excel</button> <div class="clearfix"></div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog" style="margin-top:3em"> <div class="modal-dialog modal-sm"> <div class="modal-content" style="padding:1em;padding-top:0.5em;"> <h3 style="color:#5cb85c;margin-bottom:6px">Success!</h3> <span style="font-size:13px" id="sucsubtext">Fund Allotments saved!</span><br><br> <button type="button" class="btn btn-primary pull-right" style="background:#5cb85c;border:0;margin-top:0;padding:5px 10px 5px 10px" id="okaybtn" data-dismiss="modal">Okay</button> <div class="clearfix"></div> </div> </div> </div> <!-- Modal --> <script> $('[data-toggle="tooltip"]').tooltip(); shown = false; function showsearch() { if (shown == true) { $('#searchfields').fadeOut(399); shown = false; } else { shown = true; $('#searchfields').slideDown(399); } } function getProv() { var formData = { 'action' : 'province', 'regionid' : $('#region option:selected').val() }; $.ajax({ type: "POST", url: "getLocations.php", data: formData, success: function(data) { $("#province").prop('disabled', false); $("#province").html(data); } }); } </script> </body> </html>
jmigdelacruz/SLPonline
finance/allotments.php
PHP
mit
18,757
package iso20022 type RepurchaseType6Code string
fgrid/iso20022
RepurchaseType6Code.go
GO
mit
50
namespace XHTMLClassLibrary.AttributeDataTypes { /// <summary> /// One or more digits. /// </summary> public class Number : IAttributeDataType { private int? _number = null; public string Value { get { if (_number.HasValue) { return _number.ToString(); } return string.Empty; } set { _number = null; int temp; if(int.TryParse(value, out temp)) { _number = temp; } } } } }
LordKiRon/fb2converters
fb2epub/HTML5ClassLibrary/AttributeDataTypes/Number.cs
C#
mit
693
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class ApplicationGatewaySslPredefinedPolicy(SubResource): """An Ssl predefined policy. :param id: Resource ID. :type id: str :param name: Name of Ssl predefined policy. :type name: str :param cipher_suites: Ssl cipher suites to be enabled in the specified order for application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv1_0', 'TLSv1_1', 'TLSv1_2' :type min_protocol_version: str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslProtocol """ _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.cipher_suites = kwargs.get('cipher_suites', None) self.min_protocol_version = kwargs.get('min_protocol_version', None)
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/application_gateway_ssl_predefined_policy.py
Python
mit
1,826
const path = require('path'); const inquirer = require('inquirer'); const yargs = require('yargs'); const { sanitizeArgs, ui, invalidGitRepo, ingredients, addIngredients, promiseTimeout } = require('../common'); const { cloneRepo, deleteGitFolder, establishLocalGitBindings, addGitRemote, pushLocalGitToOrigin, stageChanges } = require('../tasks/git'); const { createEnvFile, checkForExistingFolder, executeCommand } = require('../tasks/filesystem'); const { readAndInitializeProjectRecipe, bakeProject } = require('../tasks/project'); const getDefaultProjectName = repoURL => { let projectName = path.basename(repoURL).toLowerCase(); projectName = projectName.replace(/\.git$/, ''); projectName = projectName.replace(/\.+/g, '-'); projectName = projectName.replace(/-+/g, '-'); return projectName; }; const getValidProjectName = name => { return name .replace(/\W+/g, ' ') // alphanumerics only .trimRight() .replace(/ /g, '-') .toLowerCase(); }; module.exports = { command: 'prepare', desc: 'creates a new scaffold from an ezbake project in a specified Git source', builder: yargs => { return yargs .option('n', { alias: 'projectName', describe: 'Alphanumeric project name' }) .option('r', { alias: 'gitRepoURL', describe: 'The URL of the source Git repo to ezbake' }) .option('b', { alias: 'gitRepoBranch', describe: 'The branch on the source repo which contains the .ezbake folder' }) .option('o', { alias: 'gitOriginURL', describe: 'The URL of the Git destination repo to push to as a remote origin' }) .option('s', { alias: 'simple', describe: 'Flag to indicate Whether to ask for authorName, authorEmail and projectDescription', type: 'boolean', default: false }); }, handler: async argv => { // console.log(argv); let args = sanitizeArgs(argv); // Sanitize Project Name, if passed in as parameter if (args['projectName']) { args['projectName'] = getValidProjectName(args['projectName']); } let baseIngredients = ingredients; const TIMEOUT = 20000; try { // Mise en place baseIngredients = baseIngredients.filter(ingredient => { if (ingredient.name === 'projectName') { // Override default project name if (!args[ingredient.name] && args['gitOriginURL']) { ingredient.default = getDefaultProjectName(args['gitOriginURL']); } } // Exclude fields for which the values have already been provided with the command if (args[ingredient.name]) { console.log(`> ${ingredient.name}: ${args[ingredient.name]}`); return false; } // Exclude some fields in case of simple setup if ( args['simple'] && ['authorName', 'authorEmail', 'projectDescription'].includes( ingredient.name ) ) { return false; } return true; }); let projectIngredients = await inquirer.prompt(baseIngredients); projectIngredients = Object.assign(projectIngredients, args); projectIngredients.projectName = await checkForExistingFolder( ui, projectIngredients.projectName ); // Check if the repo is valid await cloneRepo( ui, projectIngredients.gitRepoURL, projectIngredients.gitRepoBranch, projectIngredients.projectName ).catch(invalidGitRepo); let recipe = readAndInitializeProjectRecipe( ui, projectIngredients.projectName, projectIngredients.gitRepoURL, projectIngredients.gitRepoBranch ); // Remove git bindings await promiseTimeout( TIMEOUT, deleteGitFolder(ui, projectIngredients.projectName) ).catch(err => { throw new Error(`Error: ${err} while deleting cloned Git folder.`); }); // Ask away! let ingredients = await inquirer.prompt(recipe.ingredients); let allIngredients = Object.assign( { ...projectIngredients, ...ingredients }, { projectNameDocker: projectIngredients.projectName.replace(/-/g, '_'), projectAuthor: projectIngredients.authorName + ' <' + projectIngredients.authorEmail + '>' } ); bakeProject(ui, allIngredients, recipe); // .env file setup if (recipe.env) { let envAnswers = await inquirer.prompt(recipe.env); createEnvFile(ui, projectIngredients.projectName, envAnswers); } // Finally, establish a local .git binding // And optionally add the specified remote await promiseTimeout( TIMEOUT, establishLocalGitBindings(ui, projectIngredients.projectName) ).catch(err => { throw new Error(`Error: ${err} while establishing Git bindings.`); }); if (projectIngredients.gitOriginURL) { await addGitRemote( ui, projectIngredients.gitOriginURL, projectIngredients.projectName ); } if (recipe.icing && Array.isArray(recipe.icing)) { ui.log.write(`. Applying icing...`); let projectDir = path.join( process.cwd(), `./${projectIngredients.projectName}` ); process.chdir(projectDir); for (let icing of recipe.icing) { ui.log.write(` . ${icing.description}`); if (Array.isArray(icing.cmd)) { await executeCommand( addIngredients(icing.cmd, allIngredients), icing.cmdOptions ); } } ui.log.write(`. Icing applied!`); } // Finally, stage and commit the changes. // And optionally push to a remote repo await stageChanges( ui, '[ezbake] - initial commit', projectIngredients.projectName ); if (projectIngredients.gitOriginURL) { await pushLocalGitToOrigin( ui, projectIngredients.gitOriginURL, projectIngredients.projectName ); } ui.log.write(`. Your project is ready!`); process.exit(0); } catch (error) { ui.log.write(error.message); process.exit(-1); } } };
appirio-digital/ezbake
commands/prepare.js
JavaScript
mit
6,465
import React from 'react' import { useSelector } from 'react-redux' import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import MoveSelector from '../containers/move-selector' import Footer from '../containers/footer' import Player from '../containers/player' import WelcomeDlg from '../containers/welcome-dlg' import History from '../features/history' import { GlobalState } from '../reducers/consts' const Game = () => { const showWelcome = useSelector(state => state.globalState === GlobalState.New) return ( <> <WelcomeDlg show={showWelcome} /> <Container> <Row> <Col> <Player color='white' /> </Col> <Col> <Player color='black' right /> </Col> </Row> <Row> <Col className='px-0'> <MoveSelector /> </Col> <Col sm='3' className='pr-0 pl-1'> <History /> </Col> </Row> <Row> <Col className='px-0'> <Footer /> </Col> </Row> </Container> </> ) } export default Game
koscelansky/Dama
src/components/game.js
JavaScript
mit
1,182
class LateMigration < ActiveRecord::Migration def up puts "Doing schema LateMigration" end def down puts "Undoing LateMigration" end end
ajvargo/data-migrate
spec/db/migrate/4.2/20131111111111_late_migration.rb
Ruby
mit
154
const fs = require('fs'); const path = require('path'); class Service { constructor() { this.getFileRecursevly = this.getFileRecursevly.bind(this); this.getFiles = this.getFiles.bind(this); } getFileRecursevly(folderPath, shortPath = '') { var files = []; var folder = fs.readdirSync(path.resolve(__dirname, folderPath)); var x = folder.forEach(file => { var filePath = path.resolve(folderPath, file); if (fs.lstatSync(filePath).isDirectory()) { files.push({ folder: file, files: this.getFileRecursevly(filePath, file) }) } else { files.push({ file: file, folder: shortPath }); } }) return files; } getFiles(path) { return new Promise((resolve, reject) => { var files = this.getFileRecursevly(path) resolve(files) }) } } module.exports = Service;
blckt/electron
app/src/TreeView/service.js
JavaScript
mit
1,003
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MemoryStandardStream.Read.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.Domain { using System; using System.Collections.Generic; using System.Linq; using OBeautifulCode.Assertion.Recipes; using OBeautifulCode.Serialization; using static System.FormattableString; public partial class MemoryStandardStream { /// <inheritdoc /> public override IReadOnlyCollection<long> Execute( StandardGetInternalRecordIdsOp operation) { throw new NotImplementedException(); /* operation.MustForArg(nameof(operation)).NotBeNull(); var memoryDatabaseLocator = operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>() ?? this.TryGetSingleLocator(); lock (this.streamLock) { IReadOnlyCollection<long> ProcessDefaultReturn() { switch (operation.RecordNotFoundStrategy) { case RecordNotFoundStrategy.ReturnDefault: return new long[0]; case RecordNotFoundStrategy.Throw: throw new InvalidOperationException(Invariant($"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'.")); default: throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported.")); } } this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition); if (partition == null) { return ProcessDefaultReturn(); } var result = partition .Where( _ => _.Metadata.FuzzyMatchTypes( operation.RecordFilter.IdTypes, operation.RecordFilter.ObjectTypes, operation.RecordFilter.VersionMatchStrategy)) .Select(_ => _.InternalRecordId) .Union( operation.RecordFilter.Ids.Any() partition .Where( _ => _.Metadata.FuzzyMatchTypesAndId( operation.StringSerializedId, operation.IdentifierType, operation.ObjectType, operation.VersionMatchStrategy)) .Select(_ => _.InternalRecordId)) .ToList(); if (result.Any()) { return result; } else { return ProcessDefaultReturn(); } } */ } /// <inheritdoc /> public override IReadOnlyCollection<StringSerializedIdentifier> Execute( StandardGetDistinctStringSerializedIdsOp operation) { operation.MustForArg(nameof(operation)).NotBeNull(); var result = new HashSet<StringSerializedIdentifier>(); lock (this.streamLock) { var locators = new List<MemoryDatabaseLocator>(); if (operation.SpecifiedResourceLocator != null) { locators.Add(operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>()); } else { var allLocators = this.ResourceLocatorProtocols.Execute(new GetAllResourceLocatorsOp()); foreach (var locator in allLocators) { locators.Add(locator.ConfirmAndConvert<MemoryDatabaseLocator>()); } } foreach (var memoryDatabaseLocator in locators) { this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition); if (partition != null) { foreach (var streamRecord in partition) { if (streamRecord.Metadata.FuzzyMatchTypes( operation.RecordFilter.IdTypes, operation.RecordFilter.ObjectTypes, operation.RecordFilter.VersionMatchStrategy) && ((!operation.RecordFilter.Tags?.Any() ?? true) || streamRecord.Metadata.Tags.FuzzyMatchTags(operation.RecordFilter.Tags, operation.RecordFilter.TagMatchStrategy))) { result.Add( new StringSerializedIdentifier( streamRecord.Metadata.StringSerializedId, streamRecord.Metadata.TypeRepresentationOfId.GetTypeRepresentationByStrategy( operation.RecordFilter.VersionMatchStrategy))); } } } } } return result; } /// <inheritdoc /> public override StreamRecord Execute( StandardGetLatestRecordOp operation) { throw new NotImplementedException(); /* operation.MustForArg(nameof(operation)).NotBeNull(); var memoryDatabaseLocator = operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>() ?? this.TryGetSingleLocator(); lock (this.streamLock) { this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition); var result = partition? .OrderByDescending(_ => _.InternalRecordId) .FirstOrDefault( _ => _.Metadata.FuzzyMatchTypes( operation.IdentifierType == null ? null : new[] { operation.IdentifierType, }, operation.ObjectType == null ? null : new[] { operation.ObjectType, }, operation.VersionMatchStrategy)); if (result != null) { return result; } switch (operation.RecordNotFoundStrategy) { case RecordNotFoundStrategy.ReturnDefault: return null; case RecordNotFoundStrategy.Throw: throw new InvalidOperationException(Invariant($"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'.")); default: throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported.")); } } */ } /// <inheritdoc /> public override string Execute( StandardGetLatestStringSerializedObjectOp operation) { operation.MustForArg(nameof(operation)).NotBeNull(); var delegatedOp = new StandardGetLatestRecordOp( operation.RecordFilter, operation.RecordNotFoundStrategy, StreamRecordItemsToInclude.MetadataAndPayload, operation.SpecifiedResourceLocator); var record = this.Execute(delegatedOp); string result; if (record == null) { result = null; } else { if (record.Payload is StringDescribedSerialization stringDescribedSerialization) { result = stringDescribedSerialization.SerializedPayload; } else { switch (operation.RecordNotFoundStrategy) { case RecordNotFoundStrategy.ReturnDefault: result = null; break; case RecordNotFoundStrategy.Throw: throw new NotSupportedException(Invariant($"record {nameof(SerializationFormat)} not {SerializationFormat.String}, it is {record.Payload.GetSerializationFormat()}, but {nameof(RecordNotFoundStrategy)} is not {nameof(RecordNotFoundStrategy.ReturnDefault)}")); default: throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported.")); } } } return result; } } }
NaosProject/Naos.Database
Naos.Database.Domain/Protocols/Classes/Stream/MemoryStandard/MemoryStandardStream.Read.cs
C#
mit
10,172
package com.falcon.cms.web.rest; import com.falcon.cms.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/management") public class LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
dooma/falconcms
src/main/java/com/falcon/cms/web/rest/LogsResource.java
Java
mit
1,166
#include "stdafx.h" #include "record.hpp" namespace tc { namespace log { const char* record::type_acronym( void ) const { switch( type ) { case log::trace: return "T"; case log::debug: return "D"; case log::info: return "I"; case log::warn: return "W"; case log::error: return "E"; case log::fatal: return "F"; case log::all: return "A"; default: return "!"; } return "?"; } record::record( tc::log::type type , const tc::log::tag& tag ) : type(type) , tag(tag) , ts(tc::timestamp::now()) , tid(tc::threading::current_thread_id()) { } record::~record( void ) { } }}
aoziczero/deprecated-libtc
srcs/tc.log/record.cpp
C++
mit
591
exports.LOADING = "LOADING"; exports.ERROR = "ERROR"; exports.SUCCESS = "SUCCESS"; exports.FETCH = "FETCH"; exports.CREATE = "CREATE"; exports.UPDATE = "UPDATE"; exports.DELETE = "DELETE"; exports.SET_EDIT_MODE = "SET_EDIT_MODE"; exports.SET_ADD_MODE = "SET_ADD_MODE"; exports.CLOSE_FORM = "CLOSE_FORM"; exports.SET_PAGE = "SET_PAGE"
Em-Ant/fcc-options-app
client/src/constants/actionTypes/modelActionTypes.js
JavaScript
mit
334
'use strict'; exports.ContainerBuilder = require('./CqrsContainerBuilder'); exports.EventStream = require('./EventStream'); exports.CommandBus = require('./CommandBus'); exports.EventStore = require('./EventStore'); exports.AbstractAggregate = require('./AbstractAggregate'); exports.AggregateCommandHandler = require('./AggregateCommandHandler'); exports.AbstractSaga = require('./AbstractSaga'); exports.SagaEventHandler = require('./SagaEventHandler'); exports.AbstractProjection = require('./AbstractProjection'); exports.InMemoryMessageBus = require('./infrastructure/InMemoryMessageBus'); exports.InMemoryEventStorage = require('./infrastructure/InMemoryEventStorage'); exports.InMemorySnapshotStorage = require('./infrastructure/InMemorySnapshotStorage'); exports.InMemoryView = require('./infrastructure/InMemoryView'); exports.getMessageHandlerNames = require('./utils/getMessageHandlerNames'); exports.subscribe = require('./subscribe');
snatalenko/node-cqrs
src/index.js
JavaScript
mit
953
'use strict'; var _ = require('./underscore-mixins.js'); var fnToNode = new Map(); exports.load = function (nodes, prefix) { let uuid = require('uuid'); if (prefix != null && prefix.length > 0) { prefix = prefix + ':'; } else { prefix = ''; } _(nodes).forEach(function (fn, name) { if (_.isFunction(fn)) { fnToNode.set(fn, { name: prefix + name, id: uuid.v4(), fn: fn, ingoingLinks: new Map(), outgoingLinks: new Map(), counter: 0 }); } else { exports.load(fn, name); } }); }; exports.clone = function (fn, name) { var node = fnToNode.get(fn); var newNodeLoader = {}; newNodeLoader[name] = node.fn.bind({}); exports.load(newNodeLoader); return newNodeLoader[name]; }; exports.debug = function () { fnToNode.forEach(function (node) { console.log( _(Array.from(node.ingoingLinks.keys())).pluck('name'), node.name, _(Array.from(node.outgoingLinks.keys())).pluck('name') ); }); }; var defaultLinkOptions = { primary: true }; exports.link = function (fn) { var node = fnToNode.get(fn); return { to: function (toFn, options) { options = _(options || {}).defaults(defaultLinkOptions); var toNode = fnToNode.get(toFn); toNode.ingoingLinks.set(node, options); node.outgoingLinks.set(toNode, options); } }; }; exports.unlink = function (fn) { var node = fnToNode.get(fn); return { from: function (fromFn) { var fromNode = fnToNode.get(fromFn); fromNode.ingoingLinks.delete(node); node.outgoingLinks.delete(fromNode); } }; }; exports.remove = function (fn) { var node = fnToNode.get(fn), todo = []; node.ingoingLinks.forEach(function (inOptions, inNode) { todo.push(function () { exports.unlink(inNode.fn).from(fn); }); node.outgoingLinks.forEach(function (outOptions, outNode) { todo.push(function () { exports.unlink(fn).from(outNode.fn); exports.link(inNode.fn).to(outNode.fn, outOptions); }); }); }); _(todo).invoke('call'); }; exports.replace = function (fn) { var node = fnToNode.get(fn), todo = []; return { by: function (byFn) { node.ingoingLinks.forEach(function (inOptions, inNode) { todo.push(function () { exports.unlink(inNode.fn).from(node.fn); exports.link(inNode.fn).to(byFn, inOptions); }); }); node.outgoingLinks.forEach(function (outOptions, outNode) { todo.push(function () { exports.unlink(node.fn).from(outNode.fn); exports.link(byFn).to(outNode.fn, outOptions); }); }); _(todo).invoke('call'); } } }; exports.before = function (fn) { var node = fnToNode.get(fn), todo = []; return { insert: function (beforeFn) { node.ingoingLinks.forEach(function (inOptions, inNode) { todo.push(function () { exports.unlink(inNode.fn).from(node.fn); exports.link(inNode.fn).to(beforeFn, inOptions); }); }); todo.push(function () { exports.link(beforeFn).to(node.fn); }); _(todo).invoke('call'); } }; }; exports.after = function (fn) { var node = fnToNode.get(fn), todo = []; return { insert: function (afterFn) { node.outgoingLinks.forEach(function (outOptions, outNode) { todo.push(function () { exports.unlink(node.fn).from(outNode.fn); exports.link(afterFn).to(outNode.fn, outOptions); }); }); todo.push(function () { exports.link(node.fn).to(afterFn); }); _(todo).invoke('call'); } }; }; var runEntryNode; function linksToStream(links) { let plumber = require('gulp-plumber'); return _(links).chain() .pluck('fn') .map(exports.run) .compact() .concatVinylStreams() .value() .pipe(plumber()); } exports.run = function (fn) { var result, node = fnToNode.get(fn); runEntryNode = runEntryNode || node; if (node.lastResult != null) { return node.lastResult; } var primaryStreams = [], secondaryStreams = []; node.ingoingLinks.forEach(function (options, node) { if (options.primary) { primaryStreams.push(node); } else { secondaryStreams.push(node); } }); var primaryStream = linksToStream(primaryStreams), secondaryStream = linksToStream(secondaryStreams); result = fn(primaryStream, secondaryStream); if (runEntryNode === node) { fnToNode.forEach(function (node) { delete node.lastResult; }); } else { node.lastResult = result; } return result; }; function isNotAlone(node) { return (node.ingoingLinks.size + node.outgoingLinks.size) > 0; } function isSource(node) { return node.ingoingLinks.size === 0; } function isOutput(node) { return node.outgoingLinks.size === 0; } exports.renderGraph = function (renderer, filepath, callback) { let graphdot = require('./graphdot.js'); var graph = graphdot.digraph('one_gulp_streams_graph'); graph.set('label', 'one-gulp streams graph\n\n'); graph.set('fontname', 'sans-serif'); graph.set('fontsize', '20'); graph.set('labelloc', 't'); graph.set('pad', '0.5,0.5'); graph.set('nodesep', '0.3'); graph.set('splines', 'spline'); graph.set('ranksep', '1'); graph.set('rankdir', 'LR'); var promises = []; fnToNode.forEach(function (node) { var nodeOptions = { label: node.name, shape: 'rectangle', fontname: 'sans-serif', style: 'bold', margin: '0.2,0.1' }; if (isSource(node)) { nodeOptions.shape = 'ellipse'; nodeOptions.color = 'lavender'; nodeOptions.fontcolor = 'lavender'; nodeOptions.margin = '0.1,0.1'; } if (isOutput(node)) { nodeOptions.color = 'limegreen'; nodeOptions.fontcolor = 'white'; nodeOptions.style = 'filled'; nodeOptions.margin = '0.25,0.25'; } if (isNotAlone(node)) { node.graphNode = graph.addNode(node.id, nodeOptions); if (isSource(node)) { var donePromise = new Promise(function (resolve, reject) { node.fn() .on('data', function () { node.counter += 1; node.graphNode.set('color', 'mediumslateblue'); node.graphNode.set('fontcolor', 'mediumslateblue'); node.graphNode.set('label', node.name + ' (' + node.counter + ')'); }) .on('error', reject) .on('end', resolve); }); promises.push(donePromise); } } }); Promise.all(promises).then(function () { fnToNode.forEach(function (node) { node.ingoingLinks.forEach(function (options, linkedNode) { var edgeOptions = {}; if (options.primary) { edgeOptions.penwidth = '1.5'; } else { edgeOptions.arrowhead = 'empty'; edgeOptions.style = 'dashed'; } if (isSource(linkedNode)) { edgeOptions.color = linkedNode.graphNode.get('color'); } graph.addEdge(linkedNode.graphNode, node.graphNode, edgeOptions); }); }); graphdot.renderToSvgFile(graph, renderer, filepath, callback); }); };
Alex-D/one-gulp
lib/dag.js
JavaScript
mit
8,407
import { connect } from 'react-redux'; import Main from './Main'; import * as userActions from '../../state/user/userActions'; const mapStateToProps = (state, ownProps) => { return { activeTab: ownProps.location.pathname.split('/')[2] }; }; const mapDispatchToProps = (dispatch) => { return { getUserData: () => dispatch(userActions.authRequest()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Main);
GerManson/bodymass
src/dashboard/components/Main/MainContainer.js
JavaScript
mit
440
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { MembersComponent } from './members/members.component'; import { SeatingMapComponent } from './seating-map/seating-map.component'; const routes: Routes = [ { path: 'members', component: MembersComponent }, { path: 'seating-map', component: SeatingMapComponent }, { path: '', redirectTo: '/members', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
pedrorohr/crescer-cwi
src/app/app-routing.module.ts
TypeScript
mit
589
(function(angular) { 'use strict'; angular .module('jstube.chromeExtensionCleaner.popup') .directive('jstubeNavbar', jstubeNavbar); function jstubeNavbar() { return { restrict: 'E', templateUrl: 'nav/_navbar.html', controller: 'NavbarController', controllerAs: 'nav' }; } } (window.angular));
dayanand-saraswati/chrome-extension-cleaner
chromeExtensionCleaner/app/popup/nav/navbarDirective.js
JavaScript
mit
389
// Just re-export everything from the other files export * from './base-table-name'; export * from './compound-constraint'; export * from './constraint'; export * from './constraint-type'; export * from './default-value'; export * from './error-response'; export * from './filter-operation'; export * from './filter'; export * from './master-table-name'; export * from './raw-constraint'; export * from './paginated-response'; export * from './session-ping'; export * from './special-default-value'; export * from './sql-row'; export * from './table-data-type'; export * from './table-header'; export * from './table-insert'; export * from './table-meta'; export * from './table-tier'; export * from './transformed-name';
mattbdean/Helium
common/api/index.ts
TypeScript
mit
723
package com.dranawhite.mybatis.handler; import com.alibaba.fastjson.JSON; import com.dranawhite.mybatis.model.Address; import com.dranawhite.mybatis.model.FullAddress; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import org.apache.ibatis.type.TypeHandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author dranawhite 2018/1/2 * @version 1.0 */ @MappedTypes(FullAddress.class) @MappedJdbcTypes(JdbcType.VARCHAR) public class FullAddressJsonHandler implements TypeHandler<FullAddress> { @Override public void setParameter(PreparedStatement ps, int i, FullAddress parameter, JdbcType jdbcType) throws SQLException { String address = JSON.toJSONString(parameter); ps.setString(i, address); } @Override public FullAddress getResult(ResultSet rs, String columnName) throws SQLException { String address = rs.getString(columnName); return JSON.parseObject(address, FullAddress.class); } @Override public FullAddress getResult(ResultSet rs, int columnIndex) throws SQLException { String address = rs.getString(columnIndex); return JSON.parseObject(address, FullAddress.class); } @Override public FullAddress getResult(CallableStatement cs, int columnIndex) throws SQLException { String address = cs.getString(columnIndex); return JSON.parseObject(address, FullAddress.class); } }
dranawhite/test-java
test-framework/test-mybatis/src/main/java/com/dranawhite/mybatis/handler/FullAddressJsonHandler.java
Java
mit
1,582
from util.tipo import tipo class S_PARTY_MEMBER_INTERVAL_POS_UPDATE(object): def __init__(self, tracker, time, direction, opcode, data): print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
jeff-alves/Tera
game/message/unused/S_PARTY_MEMBER_INTERVAL_POS_UPDATE.py
Python
mit
246
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(1); var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var Hello_1 = __webpack_require__(4); var LabelTextbox_1 = __webpack_require__(5); var WebUser_1 = __webpack_require__(6); $(function () { var id = "target"; var container = document.getElementById(id); var model = new WebUser_1.default("James", null); function validate() { return model.validate(); } var wrapper = React.createElement("div", null, React.createElement(Hello_1.default, {class: "welcome", compiler: "TypeScript", framework: "ReactJS"}), React.createElement(LabelTextbox_1.default, {class: "field-username", type: "text", label: "Username", model: model}), React.createElement("button", {onClick: validate}, "Validate")); ReactDOM.render(wrapper, container); }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * jQuery JavaScript Library v3.0.0 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2016-06-09T18:02Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } var version = "3.0.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this global in .jshintrc would create a danger of using the global // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.0 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-01-04 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement("fieldset"); try { return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Check form elements and option elements for explicit disabling return "label" in elem && elem.disabled === disabled || "form" in elem && elem.disabled === disabled || // Check non-disabled form elements for fieldset[disabled] ancestors "form" in elem && elem.disabled === false && ( // Support: IE6-11+ // Ancestry is covered for us elem.isDisabled === disabled || // Otherwise, assume any non-<option> under fieldset[disabled] is disabled /* jshint -W018 */ elem.isDisabled !== !disabled && ("label" in elem || !disabledAncestor( elem )) !== disabled ); }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( el ) { el.className = "i"; return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( el ) { el.appendChild( document.createComment("") ); return !el.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll(":enabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return (sel + "").replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( el ) { return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context resolve.call( undefined, value ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( /*jshint -W002 */ value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.call( undefined, value ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( jQuery.isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList.then( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnotwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ), display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support: IE <=9 // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // // Support: Firefox <=42 // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push( { elem: cur, handlers: matches } ); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: jQuery.isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event.which; } }, jQuery.event.addProp ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, // Support: IE <=10 - 11, Edge 12 - 13 // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; function manipulationTarget( elem, content ) { if ( jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return elem.getElementsByTagName( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE <=9 only // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val, valueIsBorderBox = true, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. if ( elem.getClientRects().length ) { val = elem.getBoundingClientRect()[ name ]; } // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function raf() { if ( timerId ) { window.requestAnimationFrame( raf ); jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* jshint -W083 */ anim.done( function() { // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnotwhite ); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off or if document is hidden if ( jQuery.fx.off || document.hidden ) { opt.duration = 0; } else { opt.duration = typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = window.requestAnimationFrame ? window.requestAnimationFrame( raf ) : window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { if ( window.cancelAnimationFrame ) { window.cancelAnimationFrame( timerId ); } else { window.clearInterval( timerId ); } timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); var rclass = /[\t\r\n\f]/g; function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnotwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + getClass( elem ) + " " ).replace( rclass, " " ) .indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g, rspaces = /[\x20\t\r\n\f]+/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace( rreturn, "" ) : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 13 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available, append data to url if ( s.data ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in uncached url if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rts, "" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).prop( { charset: s.scriptCharset, src: s.url } ).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.pseudos.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var docElem, win, rect, doc, elem = this[ 0 ]; if ( !elem ) { return; } // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } rect = elem.getBoundingClientRect(); // Make sure element is not hidden (display: none) if ( rect.width || rect.height ) { doc = elem.ownerDocument; win = getWindow( doc ); docElem = doc.documentElement; return { top: rect.top + win.pageYOffset - docElem.clientTop, left: rect.left + win.pageXOffset - docElem.clientLeft }; } // Return zeros for disconnected and hidden elements (gh-2310) return rect; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset = { top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ), left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) }; } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } } ); jQuery.parseJSON = JSON.parse; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( true ) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return jQuery; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; } ) ); /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = React; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = ReactDOM; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = __webpack_require__(2); var HelloComponent = (function (_super) { __extends(HelloComponent, _super); function HelloComponent() { _super.apply(this, arguments); } HelloComponent.prototype.render = function () { return React.createElement("div", {className: this.props.class}, this.props.framework); }; return HelloComponent; }(React.Component)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = HelloComponent; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var React = __webpack_require__(2); var LabelTextbox = (function (_super) { __extends(LabelTextbox, _super); function LabelTextbox() { _super.apply(this, arguments); } LabelTextbox.prototype.update = function (event) { var model = this.props.model; var box = this.refs["box"]; model.UserId = box.value; this.setState({ value: event.target.value }); }; LabelTextbox.prototype.render = function () { var _this = this; var classes = 'lb-txt ' + this.props.class; var model = this.props.model; return React.createElement("div", {className: classes}, React.createElement("div", {className: "label"}, this.props.label), React.createElement("div", {className: "txt-container"}, React.createElement("input", {ref: "box", className: "txt", type: this.props.type, onChange: function (e) { return _this.update(e); }, value: model.UserId}))); }; return LabelTextbox; }(React.Component)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = LabelTextbox; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var validation_1 = __webpack_require__(7); var validation_2 = __webpack_require__(7); var validation_3 = __webpack_require__(7); var WebUser = (function () { function WebUser(userId, pwd) { this.UserId = userId; this.Pwd = pwd; } WebUser.prototype.validate = function () { return validation_3.validate(this)[0]; }; __decorate([ validation_1.required ], WebUser.prototype, "UserId", void 0); __decorate([ validation_1.required ], WebUser.prototype, "Pwd", void 0); WebUser = __decorate([ validation_2.validatable ], WebUser); return WebUser; }()); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = WebUser; /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; function validatable(target) { console.log("Validatable class annotation reached"); } exports.validatable = validatable; function init(target) { if (!target.validators) { target.validators = []; } } function required(target, prop) { console.log("Required property annotation reached"); init(target); target.validators.push(function (modelErrors) { if (!!this[prop]) { modelErrors.push(prop.toString().concat(' validation success!')); return true; } else { modelErrors.push(prop.toString().concat(' cannot be empty!')); return false; } }); } exports.required = required; function validate(target) { var rlt = true; var modelErrors = []; if (target.validators != null && target.validators.length > 0) { for (var _i = 0, _a = target.validators; _i < _a.length; _i++) { var v = _a[_i]; rlt = v.call(target, modelErrors) && rlt; } } console.log(modelErrors); return [rlt, modelErrors]; } exports.validate = validate; /***/ } /******/ ]); //# sourceMappingURL=demo.bundle.js.map
mind0n/hive
Frontend/demo/dist/demo.bundle.js
JavaScript
mit
281,070
/* * Copyright (C) 2013 The Android Open Source Project * * 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 com.example.android.bluetoothlegatt; import android.app.Activity; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CompoundButton; import android.widget.ExpandableListView; import android.widget.SeekBar; import android.widget.SimpleExpandableListAdapter; import android.widget.Switch; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * For a given BLE device, this Activity provides the user interface to connect, display data, * and display GATT services and characteristics supported by the device. The Activity * communicates with {@code BluetoothLeService}, which in turn interacts with the * Bluetooth LE API. */ public class DeviceControlActivity extends Activity implements SeekBar.OnSeekBarChangeListener ,SensorEventListener { private final static String TAG = DeviceControlActivity.class.getSimpleName(); public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME"; public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS"; public static String CLIENT_CHARACTERISTIC_MOTOR = "0000fff1-0000-1000-8000-00805f9b34fb"; private TextView mConnectionState; private TextView mDataField; private String mDeviceName; private String mDeviceAddress; private ExpandableListView mGattServicesList; private BluetoothLeService mBluetoothLeService; private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>(); private boolean mConnected = false; private BluetoothGattCharacteristic mNotifyCharacteristic; private final String LIST_NAME = "NAME"; private final String LIST_UUID = "UUID"; private byte[] value = new byte[8]; private boolean motor_run = false; private TextView mShowSpeed0,mShowSpeed1,mShowSpeed2,mShowSpeed3; private SeekBar mSetSpeed0,mSetSpeed1,mSetSpeed2,mSetSpeed3; private BluetoothGattCharacteristic mMotorChars; private SensorManager mSensorManager; private Switch mDevState = null; private Switch mConState = null; private Switch mCtlState = null; private PowerManager pm = null; PowerManager.WakeLock wl = null; // Code to manage Service lifecycle. private final ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService(); if (!mBluetoothLeService.initialize()) { Log.e(TAG, "Unable to initialize Bluetooth"); finish(); } // Automatically connects to the device upon successful start-up initialization. mBluetoothLeService.connect(mDeviceAddress); } @Override public void onServiceDisconnected(ComponentName componentName) { mBluetoothLeService = null; } }; // Handles various events fired by the Service. // ACTION_GATT_CONNECTED: connected to a GATT server. // ACTION_GATT_DISCONNECTED: disconnected from a GATT server. // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services. // ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read // or notification operations. private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { mConnected = true; updateConnectionState(R.string.connected); invalidateOptionsMenu(); } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { mConnected = false; updateConnectionState(R.string.disconnected); invalidateOptionsMenu(); clearUI(); } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { // Show all the supported services and characteristics on the user interface. displayGattServices(mBluetoothLeService.getSupportedGattServices()); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); } } }; // If a given GATT characteristic is selected, check for supported features. This sample // demonstrates 'Read' and 'Notify' features. See // http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete // list of supported characteristic features. private final ExpandableListView.OnChildClickListener servicesListClickListner = new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (mGattCharacteristics != null) { final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(groupPosition).get(childPosition); // final int charaProp = characteristic.getProperties(); // if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { // // If there is an active notification on a characteristic, clear // // it first so it doesn't update the data field on the user interface. // if (mNotifyCharacteristic != null) { // mBluetoothLeService.setCharacteristicNotification( // mNotifyCharacteristic, false); // mNotifyCharacteristic = null; // } // mBluetoothLeService.readCharacteristic(characteristic); // } // if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // mNotifyCharacteristic = characteristic; // mBluetoothLeService.setCharacteristicNotification( // characteristic, true); // } if(characteristic.getUuid().toString().equals(CLIENT_CHARACTERISTIC_MOTOR)) { mMotorChars = characteristic; value[0] = 0x04; value[5] += 10; value[5] %= 100; value[6] += 10; value[6] %= 100; characteristic.setValue(value); mBluetoothLeService.writeCharacteristic(characteristic); Log.d("BLE_TEST", "Write Begin"); Log.d("BLE_TEST", "value" + value[7]); } return true; } return false; } }; private void clearUI() { mGattServicesList.setAdapter((SimpleExpandableListAdapter) null); mDataField.setText(R.string.no_data); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gatt_services_characteristics); mShowSpeed0 = (TextView) findViewById(R.id.ShowSpeed0); mSetSpeed0 = (SeekBar) findViewById(R.id.SetSpeed0); mShowSpeed1 = (TextView) findViewById(R.id.ShowSpeed1); mSetSpeed1 = (SeekBar) findViewById(R.id.SetSpeed1); mShowSpeed2 = (TextView) findViewById(R.id.ShowSpeed2); mSetSpeed2 = (SeekBar) findViewById(R.id.SetSpeed2); mShowSpeed3 = (TextView) findViewById(R.id.ShowSpeed3); mSetSpeed3 = (SeekBar) findViewById(R.id.SetSpeed3); mDevState = (Switch) findViewById(R.id.DevState); mConState = (Switch) findViewById(R.id.ConState); mCtlState = (Switch) findViewById(R.id.CtlState); // mDevState.setEnabled(false); // 玩家模式 // mConState.setEnabled(true); // 连接状态 // mCtlState.setEnabled(false); // 停止控制 // 开发者模式 or 玩家模式 mDevState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { SetPlayMode(b); } }); // 连接 or 断开 mConState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { // TODO mBluetoothLeService.disconnect(); AppRun(); } }); // 开始控制 or 停止控制 mCtlState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { // TODO } }); mShowSpeed0.setText("Ch0 PWM Duty " + 0); mSetSpeed0.setMax(100); mSetSpeed0.setProgress(0); mSetSpeed0.setOnSeekBarChangeListener(this); mShowSpeed1.setText("Ch1 PWM Duty " + 0); mSetSpeed1.setMax(100); mSetSpeed1.setProgress(0); mSetSpeed1.setOnSeekBarChangeListener(this); mShowSpeed2.setText("Ch2 PWM Duty " + 0); mSetSpeed2.setMax(100); mSetSpeed2.setProgress(0); mSetSpeed2.setOnSeekBarChangeListener(this); mShowSpeed3.setText("Ch3 PWM Duty " + 0); mSetSpeed3.setMax(100); mSetSpeed3.setProgress(0); mSetSpeed3.setOnSeekBarChangeListener(this); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), //SensorManager.SENSOR_DELAY_NORMAL); 50000); final Intent intent = getIntent(); mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME); mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS); // Sets up UI references. ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress); mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list); mGattServicesList.setOnChildClickListener(servicesListClickListner); mConnectionState = (TextView) findViewById(R.id.connection_state); mDataField = (TextView) findViewById(R.id.data_value); getActionBar().setTitle(mDeviceName); getActionBar().setDisplayHomeAsUpEnabled(true); Intent gattServiceIntent = new Intent(this, BluetoothLeService.class); bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); SetPlayMode(false); } private void AppRun() { Intent intent = new Intent(this, DeviceScanActivity.class); startActivity(intent); finish(); } private void SetPlayMode(boolean mode) { // true----developer mode // false---player mode TextView mText = null; if (true == mode) { // Address mText = (TextView) findViewById(R.id.device_address_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.device_address); mText.setVisibility(TextView.VISIBLE); // Connect State mText = (TextView) findViewById(R.id.connection_state_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.connection_state); mText.setVisibility(TextView.VISIBLE); // Data mText = (TextView) findViewById(R.id.data_value_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.data_value); mText.setVisibility(TextView.VISIBLE); ExpandableListView mList = (ExpandableListView) findViewById(R.id.gatt_services_list); mList.setVisibility(ExpandableListView.VISIBLE); } else { // Address mText = (TextView) findViewById(R.id.device_address_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.device_address); mText.setVisibility(TextView.INVISIBLE); // Connect State mText = (TextView) findViewById(R.id.connection_state_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.connection_state); mText.setVisibility(TextView.INVISIBLE); // Data mText = (TextView) findViewById(R.id.data_value_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.data_value); mText.setVisibility(TextView.INVISIBLE); ExpandableListView mList = (ExpandableListView) findViewById(R.id.gatt_services_list); mList.setVisibility(ExpandableListView.INVISIBLE); } } @Override public void onProgressChanged(SeekBar var1, int var2, boolean var3) { /* value[0] = 0x04; if(mSetSpeed0 == var1) { value[4] = (byte) var1.getProgress(); mShowSpeed0.setText("Ch0 PWM Duty " + var1.getProgress()); } if(mSetSpeed1 == var1) { value[5] = (byte) var1.getProgress(); mShowSpeed1.setText("Ch1 PWM Duty " + var1.getProgress()); } if(mSetSpeed2 == var1) { value[6] = (byte) var1.getProgress(); mShowSpeed2.setText("Ch2 PWM Duty " + var1.getProgress()); } if(mSetSpeed3 == var1) { value[7] = (byte) var1.getProgress(); mShowSpeed3.setText("Ch3 PWM Duty " + var1.getProgress()); } */ //mMotorChars.setValue(value); //mBluetoothLeService.writeCharacteristic(mMotorChars); } @Override public void onStartTrackingTouch(SeekBar var1){ } @Override public void onStopTrackingTouch(SeekBar var1){ } @Override public void onSensorChanged(SensorEvent var1){ if (var1.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float[] values = var1.values; // Log.d("BLE_SENSOR", "Length" + values.length); // for(int i = 0; i < values.length; i++) { // Log.d("BLE_SENSOR", "value " + i + values[0]); // } // Control Car int speed_fb = (int)(-20*values[1]); int speed_rl = (int)(20*values[0]); //mShowSpeed0.setText("X Acc value " + speed_fb); //mShowSpeed1.setText("Y Acc value " + speed_rl); if(false == mCtlState.isChecked()){ RemoteCar(0, 0); } else { RemoteCar(speed_fb, speed_rl); } } } // Forward-Back +F-B // Right-Left +L-R void RemoteCar(int speed_fb, int speed_rl){ int speed_l = speed_fb+speed_rl/2; int speed_r = speed_fb-speed_rl/2; for(int i = 0; i < value.length; i++) { value[i] = 0; } if(speed_l > 100) speed_l = 100; if(speed_l < -100) speed_l = -100; if(speed_r > 100) speed_r = 100; if(speed_r < -100) speed_r = -100; value[0] = 0x04; if(speed_l > 0) { value[4] = (byte)speed_l; value[5] = 0; } else if(speed_l < 0){ value[4] = 0; value[5] = (byte)-speed_l; } else { // Do nothing } if(speed_r < 0) { value[6] = (byte)-speed_r; value[7] = 0; } else if(speed_r > 0){ value[6] = 0; value[7] = (byte)speed_r; } else { // Do nothing } /////// mShowSpeed0.setText("Ch0 PWM Duty " + value[4]); mShowSpeed1.setText("Ch1 PWM Duty " + value[5]); mShowSpeed2.setText("Ch2 PWM Duty " + value[6]); mShowSpeed3.setText("Ch3 PWM Duty " + value[7]); mSetSpeed0.setProgress(value[4]); mSetSpeed1.setProgress(value[5]); mSetSpeed2.setProgress(value[6]); mSetSpeed3.setProgress(value[7]); // int progress = (int)value[4]; // mSetSpeed0.setProgress(progress); // progress = (int)value[5]; // mSetSpeed1.setProgress(progress); // progress = (int)value[6]; // mSetSpeed2.setProgress(progress); // progress = (int)value[7]; // mSetSpeed3.setProgress(progress); if(null != mMotorChars) { mMotorChars.setValue(value); if(null != mBluetoothLeService) mBluetoothLeService.writeCharacteristic(mMotorChars); } else { Log.d("BLE_SENSOR", "Error"); } Log.d("BLE_SENSOR", "Update"); /////// } @Override public void onAccuracyChanged(Sensor var1, int var2){ // Do Nothing } @Override protected void onResume() { super.onResume(); if(null == pm) { pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag"); wl.acquire(); } registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); if (mBluetoothLeService != null) { final boolean result = mBluetoothLeService.connect(mDeviceAddress); Log.d(TAG, "Connect request result=" + result); } if(null != mSensorManager) { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), //SensorManager.SENSOR_DELAY_NORMAL); 2000000); } } @Override protected void onPause() { super.onPause(); unregisterReceiver(mGattUpdateReceiver); mSensorManager.unregisterListener(this); if(null != wl) { wl.release(); wl = null; } } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); mBluetoothLeService = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.gatt_services, menu); if (mConnected) { menu.findItem(R.id.menu_connect).setVisible(false); menu.findItem(R.id.menu_disconnect).setVisible(true); } else { menu.findItem(R.id.menu_connect).setVisible(true); menu.findItem(R.id.menu_disconnect).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_connect: mBluetoothLeService.connect(mDeviceAddress); return true; case R.id.menu_disconnect: mBluetoothLeService.disconnect(); return true; case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private void updateConnectionState(final int resourceId) { runOnUiThread(new Runnable() { @Override public void run() { mConnectionState.setText(resourceId); } }); } private void displayData(String data) { if (data != null) { mDataField.setText(data); } } // Demonstrates how to iterate through the supported GATT Services/Characteristics. // In this sample, we populate the data structure that is bound to the ExpandableListView // on the UI. private void displayGattServices(List<BluetoothGattService> gattServices) { if (gattServices == null) return; String uuid = null; String unknownServiceString = getResources().getString(R.string.unknown_service); String unknownCharaString = getResources().getString(R.string.unknown_characteristic); ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>(); ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>(); mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>(); // Loops through available GATT Services. for (BluetoothGattService gattService : gattServices) { HashMap<String, String> currentServiceData = new HashMap<String, String>(); uuid = gattService.getUuid().toString(); currentServiceData.put( LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString)); currentServiceData.put(LIST_UUID, uuid); gattServiceData.add(currentServiceData); ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>(); List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics(); ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>(); // Loops through available Characteristics. for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { charas.add(gattCharacteristic); HashMap<String, String> currentCharaData = new HashMap<String, String>(); uuid = gattCharacteristic.getUuid().toString(); currentCharaData.put( LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString)); currentCharaData.put(LIST_UUID, uuid); gattCharacteristicGroupData.add(currentCharaData); // Set if(gattCharacteristic.getUuid().toString().equals(CLIENT_CHARACTERISTIC_MOTOR)) { mMotorChars = gattCharacteristic; } } mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData); } SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter( this, gattServiceData, android.R.layout.simple_expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { android.R.id.text1, android.R.id.text2 }, gattCharacteristicData, android.R.layout.simple_expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { android.R.id.text1, android.R.id.text2 } ); mGattServicesList.setAdapter(gattServiceAdapter); } private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); return intentFilter; } }
cedar-renjun/RemoteControl-Car
App/BluetoothLeGatt/Application/src/main/java/com/example/android/bluetoothlegatt/DeviceControlActivity.java
Java
mit
25,314
package tasks // This file is generated by methodGenerator. // DO NOT MOTIFY THIS FILE. import ( "net/url" "github.com/kawaken/go-rtm/methods" ) // AddTags returns "rtm.tasks.addTags" method instance. func AddTags(timeline string, listID string, taskseriesID string, taskID string, tags string) *methods.Method { name := "rtm.tasks.addTags" p := url.Values{} p.Add("method", name) p.Add("timeline", timeline) p.Add("list_id", listID) p.Add("taskseries_id", taskseriesID) p.Add("task_id", taskID) p.Add("tags", tags) return &methods.Method{Name: name, Params: p} }
kawaken/go-rtm
methods/tasks/add_tags.go
GO
mit
582
App.SubPhotoInstance = DS.Model.extend({ width: DS.attr('number'), height: DS.attr('number'), url: DS.attr('string'), type: 'sub_photo_instance' });
Mause/tumblr-ember
src/js/app/models/photo_model/sub_photo_instance_model.js
JavaScript
mit
157
require "sendgrid-parse/version" require "sendgrid-parse/encodable_hash"
robforman/sendgrid-parse
lib/sendgrid-parse.rb
Ruby
mit
73
"""Kytos SDN Platform.""" from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
kytos/kytos-utils
kytos/__init__.py
Python
mit
102
finApp.directive('brief', function () { return { restrict: 'E', templateUrl: 'views/directives/brief.html', controller: 'BriefController', controllerAs: 'bfc' }; });
ferpsanta/FinWallet
app/js/directives/brief.js
JavaScript
mit
185
using OpenTK; using OpenTK.Graphics.OpenGL; namespace p_1 { class Spritebatch { public static void DrawSprite(Texture2D texture, RectangleF rectangle) { DrawSprite(texture, new Vector2(rectangle.X, rectangle.Y), new Vector2(rectangle.Width / texture.Width, rectangle.Height / texture.Height), Color.White, Vector2.Zero); } public static void DrawSprite(Texture2D texture, RectangleF rectangle, Color color, RectangleF? sourceRec = null) { DrawSprite(texture, new Vector2(rectangle.X, rectangle.Y), new Vector2(rectangle.Width / texture.Width, rectangle.Height / texture.Height), color, Vector2.Zero, sourceRec); } public static void DrawSprite(Texture2D texture, Vector2 position) { DrawSprite(texture, position, Vector2.One, Color.White, Vector2.Zero); } public static void DrawSprite(Texture2D texture, Vector2 position, Vector2 scale) { DrawSprite(texture, position, scale, Color.White, Vector2.Zero); } public static void DrawSprite(Texture2D texture, Vector2 position, Vector2 scale, Color color) { DrawSprite(texture, position, scale, color, Vector2.Zero); } public static void DrawSprite(Texture2D texture, Vector2 position, Vector2 scale, Color color, Vector2 origin, RectangleF? sourceRec = null) { Vector2[] verts = new Vector2[4] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1), }; GL.BindTexture(TextureTarget.Texture2D, texture.ID); GL.Begin(PrimitiveType.Quads); for (int i = 0; i < 4; i++) { GL.Color3(color); if (sourceRec == null) { GL.TexCoord2(verts[i].X, verts[i].Y); } else { GL.TexCoord2( (sourceRec.Value.X + verts[i].X * sourceRec.Value.Width) / (float)texture.Width, (sourceRec.Value.Y + verts[i].Y * sourceRec.Value.Height) / (float)texture.Height); } verts[i].X *= texture.Width; verts[i].Y *= texture.Height; verts[i] -= origin; verts[i] *= scale; verts[i] += position; GL.Vertex2(verts[i]); } GL.End(); } public static void Begin(GameWindow window) { GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(-window.ClientSize.Width / 2f, window.ClientSize.Width / 2f, window.ClientSize.Height / 2f, -window.ClientSize.Height / 2f, 0, 1); } } }
doshaq/Dosha_Engine
SpriteBatch.cs
C#
mit
2,305
describe("grid-columns", function() { function createSuite(buffered) { describe(buffered ? "with buffered rendering" : "without buffered rendering", function() { var defaultColNum = 4, totalWidth = 1000, grid, view, colRef, store, column; function spyOnEvent(object, eventName, fn) { var obj = { fn: fn || Ext.emptyFn }, spy = spyOn(obj, "fn"); object.addListener(eventName, obj.fn); return spy; } function makeGrid(numCols, gridCfg, hiddenFn, lockedFn){ var cols, col, i; gridCfg = gridCfg || {}; colRef = []; if (!numCols || typeof numCols === 'number') { cols = []; numCols = numCols || defaultColNum; for (i = 0; i < numCols; ++i) { col = { itemId: 'col' + i, text: 'Col' + i, dataIndex: 'field' + i }; if (hiddenFn && hiddenFn(i)) { col.hidden = true; } if (lockedFn && lockedFn(i)) { col.locked = true; } col = new Ext.grid.column.Column(col); cols.push(col); } } else { cols = numCols; } store = new Ext.data.Store({ model: spec.TestModel, data: [{ field0: 'val1', field1: 'val2', field2: 'val3', field3: 'val4', field4: 'val5' }] }); grid = new Ext.grid.Panel(Ext.apply({ renderTo: Ext.getBody(), columns: cols, width: totalWidth, height: 500, border: false, store: store, bufferedRenderer: buffered, viewConfig: { mouseOverOutBuffer: 0 } }, gridCfg)); view = grid.view; colRef = grid.getColumnManager().getColumns(); } function getCell(rowIdx, colIdx) { return grid.getView().getCellInclusive({ row: rowIdx, column: colIdx }); } function getCellText(rowIdx, colIdx) { return getCellInner(rowIdx, colIdx).innerHTML; } function getCellInner(rowIdx, colIdx) { var cell = getCell(rowIdx, colIdx); return Ext.fly(cell).down(grid.getView().innerSelector).dom; } function hasCls(el, cls) { return Ext.fly(el).hasCls(cls); } function clickHeader(col) { // Offset so we're not on the edges to trigger a drag jasmine.fireMouseEvent(col.titleEl, 'click', 10); } function resizeColumn(column, by) { var colBox = column.el.getBox(), fromMx = colBox.x + colBox.width - 2, fromMy = colBox.y + colBox.height / 2, dragThresh = by > 0 ? Ext.dd.DragDropManager.clickPixelThresh + 1 : -Ext.dd.DragDropManager.clickPixelThresh - 1; // Mousedown on the header to drag jasmine.fireMouseEvent(column.el.dom, 'mouseover', fromMx, fromMy); jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx, fromMy); jasmine.fireMouseEvent(column.el.dom, 'mousedown', fromMx, fromMy); // The initial move which tiggers the start of the drag jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx + dragThresh, fromMy); // Move to resize jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx + by + 2, fromMy); jasmine.fireMouseEvent(column.el.dom, 'mouseup', fromMx + by + 2, fromMy); } function setup() { Ext.define('spec.TestModel', { extend: 'Ext.data.Model', fields: ['field0', 'field1', 'field2', 'field3', 'field4'] }); } function tearDown() { Ext.destroy(grid, store, column); grid = view = store = colRef = column = null; Ext.undefine('spec.TestModel'); Ext.data.Model.schema.clear(); } beforeEach(setup); afterEach(tearDown); // https://sencha.jira.com/browse/EXTJS-19950 describe('force fit columns, shrinking width to where flexes tend to zero', function() { it('should work', function() { makeGrid([{ text : 'Col1', dataIndex : 'foo', flex : 1 }, { text : 'Col2', columns : [{ text : 'Col21', dataIndex : 'foo2', width: 140 }, { text : 'Col22', dataIndex : 'foo4', width : 160 }, { text : 'Col23', dataIndex : 'foo4', width : 100 }, { text : 'Col34', dataIndex : 'foo4', width : 85 }] }, { text : 'Col3', dataIndex : 'foo3', width : 110 }, { text : 'Col4', columns : [ { text : 'Col41', dataIndex : 'foo2', flex: 1 }, { text : 'Col42', dataIndex : 'foo4', width : 120 }] }], { autoScroll: true, forceFit: true, width: 1800 }); expect(function() { grid.setWidth(700); }).not.toThrow(); }); }); describe('as containers', function () { var leafCls = 'x-leaf-column-header', col; afterEach(function () { col = null; }); describe('group headers', function () { beforeEach(function () { makeGrid([{ itemId: 'main1', columns: [{ itemId: 'child1' }, { itemId: 'child2' }, { itemId: 'child3' }] }]); col = grid.down('#main1'); }); it('should be stamped as a container', function () { expect(col.isContainer).toBe(true); }); it('should not give the titleEl the leaf column class', function () { expect(col.titleEl.hasCls(leafCls)).toBe(false); }); }); describe('contains child items', function () { beforeEach(function () { makeGrid([{ text: 'Foo', dataIndex: 'field0', items: [{ xtype: 'textfield', itemId: 'foo' }] }]); col = grid.visibleColumnManager.getHeaderByDataIndex('field0'); }); it('should be stamped as a container', function () { expect(col.isContainer).toBe(true); }); it('should not give the titleEl the leaf column class', function () { expect(col.titleEl.hasCls(leafCls)).toBe(false); }); describe('focusing', function () { // See EXTJS-15757. it('should not throw when focusing', function () { expect(function () { grid.down('#foo').onFocus(); }).not.toThrow(); }); it('should return the items collection', function () { var col = grid.visibleColumnManager.getHeaderByDataIndex('field0'); expect(col.getFocusables()).toBe(col.items.items); }); }); }); }); describe("cell sizing", function() { it("should size the cells to match fixed header sizes", function() { makeGrid([{ width: 200 }, { width: 500 }]); expect(getCell(0, 0).getWidth()).toBe(200); expect(getCell(0, 1).getWidth()).toBe(500); }); it("should size the cells to match flex header sizes", function() { makeGrid([{ flex: 8 }, { flex: 2 }]); expect(getCell(0, 0).getWidth()).toBe(800); expect(getCell(0, 1).getWidth()).toBe(200); }); it("should size the cells to match an the text size in the header", function() { makeGrid([{ width: null, text: '<div style="width: 25px;"></div>' }, { width: null, text: '<div style="width: 75px;"></div>' }]); expect(getCell(0, 0).getWidth()).toBe(colRef[0].titleEl.getWidth() + colRef[0].el.getBorderWidth('lr')); expect(getCell(0, 1).getWidth()).toBe(colRef[1].titleEl.getWidth() + colRef[1].el.getBorderWidth('lr')); }); }); describe("initializing", function() { describe("normal", function() { it("should accept a column array", function() { makeGrid([{ text: 'Foo', dataIndex: 'field0' }]); expect(grid.getColumnManager().getHeaderAtIndex(0).text).toBe('Foo'); }); it("should accept a header config", function() { makeGrid({ margin: 5, items: [{ text: 'Foo', dataIndex: 'field0' }] }); expect(grid.getColumnManager().getHeaderAtIndex(0).text).toBe('Foo'); expect(grid.headerCt.margin).toBe(5); }); }); describe("locking", function() { it("should accept a column array, enabling locking if a column is configured with locked: true", function() { makeGrid([{ text: 'Foo', dataIndex: 'field0', locked: true }, { text: 'Bar', dataIndex: 'field1' }]); expect(grid.lockable).toBe(true); }); it("should accept a header config, enabling locking if any column is configured with locked: true", function() { makeGrid({ items: [{ text: 'Foo', dataIndex: 'field0', locked: true }, { text: 'Bar', dataIndex: 'field1' }] }); expect(grid.lockable).toBe(true); // Top level grid should return columns from both sides expect(grid.getVisibleColumns().length).toBe(2); expect(grid.getColumns().length).toBe(2); }); }); }); describe("column manager", function() { // Get all columns from the grid ref function ga() { return grid.getColumnManager().getColumns(); } // Get all manager function gam() { return grid.getColumnManager(); } // Get all visible columns from the grid ref function gv() { return grid.getVisibleColumnManager().getColumns(); } // Get visible manager function gvm() { return grid.getVisibleColumnManager(); } it("should provide a getColumnManager method", function(){ makeGrid(); expect(gam().$className).toBe('Ext.grid.ColumnManager'); }); it("should provide a getVisibleColumnManager method", function(){ makeGrid(); expect(gvm().$className).toBe('Ext.grid.ColumnManager'); }); describe("simple grid", function(){ beforeEach(function(){ makeGrid(); }); it("should return all leaf columns", function() { expect(gv().length).toBe(defaultColNum); }); it("should have the correct column order", function(){ var cols = gv(), i = 0, len = cols.length; for (; i < len; ++i) { expect(cols[i]).toBe(colRef[i]); } }); it("should update the order when moving columns", function(){ grid.headerCt.move(3, 1); var cols = gv(); expect(cols[0]).toBe(colRef[0]); expect(cols[1]).toBe(colRef[3]); expect(cols[2]).toBe(colRef[1]); expect(cols[3]).toBe(colRef[2]); }); it("should update the columns when removing a column", function(){ grid.headerCt.remove(1); var cols = gv(); expect(cols[0]).toBe(colRef[0]); expect(cols[1]).toBe(colRef[2]); expect(cols[2]).toBe(colRef[3]); }); it("should update the columns when adding a column", function(){ grid.headerCt.add({ text: 'Col4' }); expect(gv()[4].text).toBe('Col4'); }); describe("functions", function() { describe("getHeaderIndex", function() { it("should return the correct index for the header", function() { expect(gam().getHeaderIndex(colRef[3])).toBe(3); }); it("should return -1 if the column doesn't exist", function(){ column = new Ext.grid.column.Column(); expect(gam().getHeaderIndex(column)).toBe(-1); }); }); describe("getHeaderAtIndex", function(){ it("should return the column reference", function(){ expect(gam().getHeaderAtIndex(2)).toBe(colRef[2]); }); it("should return null if the index is out of bounds", function(){ expect(gam().getHeaderAtIndex(10)).toBeNull(); }); }); describe("getHeaderById", function(){ it("should return the column reference by id", function(){ expect(gam().getHeaderById('col1')).toBe(colRef[1]); }); it("should return null if the id doesn't exist", function() { expect(gam().getHeaderById('foo')).toBeNull(); }); }); it("should return the first item", function(){ expect(gam().getFirst()).toBe(colRef[0]); }); it("should return the last item", function(){ expect(gam().getLast()).toBe(colRef[3]); }); describe("getNextSibling", function(){ it("should return the next sibling", function(){ expect(gam().getNextSibling(colRef[1])).toBe(colRef[2]); }); it("should return the null if the next sibling doesn't exist", function(){ expect(gam().getNextSibling(colRef[3])).toBeNull(); }); }); describe("getPreviousSibling", function(){ it("should return the previous sibling", function(){ expect(gam().getPreviousSibling(colRef[2])).toBe(colRef[1]); }); it("should return the null if the previous sibling doesn't exist", function(){ expect(gam().getPreviousSibling(colRef[0])).toBeNull(); }); }); }); }); describe('getHeaderIndex', function () { var index, headerCtItems; beforeEach(function () { makeGrid([{ text: 'Name', width: 100, dataIndex: 'name', hidden: true },{ text: 'Email', width: 100, dataIndex: 'email' }, { text: 'Stock Price', columns: [{ text: 'Price', width: 75, dataIndex: 'price' }, { text: 'Phone', width: 80, dataIndex: 'phone', hidden: true }, { text: '% Change', width: 40, dataIndex: 'pctChange' }] }, { text: 'Foo', columns: [{ text: 'Foo Price', width: 75, dataIndex: 'price', hidden: true }, { text: 'Foo Phone', width: 80, dataIndex: 'phone' }, { text: 'Foo % Change', width: 40, dataIndex: 'pctChange' }] }]); headerCtItems = grid.headerCt.items; }); afterEach(function () { index = headerCtItems = null; }); describe('all columns', function () { describe('when argument is a column', function () { it('should return a valid index', function () { index = gam().getHeaderIndex(headerCtItems.items[0]); expect(index).not.toBe(-1); expect(index).toBe(0); }); it('should return the header regardless of visibility', function () { var header; header = headerCtItems.items[0]; index = gam().getHeaderIndex(header); expect(header.hidden).toBe(true); expect(index).toBe(0); }); it('should return the index of the header in its owner stack - rootHeader', function () { index = gam().getHeaderIndex(headerCtItems.items[3].items.items[0]); expect(index).toBe(5); }); it('should return the index of the header in its owner stack - groupHeader', function () { // Note that this spec is using the same header as the previous spec to demonstrate the difference. var groupHeader = headerCtItems.items[3]; index = groupHeader.columnManager.getHeaderIndex(groupHeader.items.items[0]); expect(index).toBe(0); }); }); describe('when argument is a group header', function () { it('should return a valid index', function () { index = gam().getHeaderIndex(headerCtItems.items[2]); expect(index).not.toBe(-1); expect(index).toBe(2); }); it('should return an index of the first leaf of group header', function () { var colMgrHeader; // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gam().getHeaderIndex(headerCtItems.items[2]); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gam().getHeaderAtIndex(index); // Remember, this is the index of the root header's visible col mgr. expect(index).toBe(2); expect(colMgrHeader.hidden).toBe(false); expect(colMgrHeader.dataIndex).toBe('price'); }); it("should be a reference to the first leaf header in the grouped header's columnn manager", function () { var groupedHeader, colMgrHeader, groupHeaderFirstHeader; groupedHeader = headerCtItems.items[2]; groupHeaderFirstHeader = groupedHeader.columnManager.getHeaderAtIndex(0); // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gam().getHeaderIndex(groupedHeader); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gam().getHeaderAtIndex(index); expect(colMgrHeader).toBe(groupHeaderFirstHeader); expect(colMgrHeader.hidden).toBe(groupHeaderFirstHeader.hidden); expect(colMgrHeader.dataIndex).toBe(groupHeaderFirstHeader.dataIndex); }); it('should return first sub-header regardless of visibility', function () { var groupedHeader, colMgrHeader, groupHeaderFirstHeader; groupedHeader = headerCtItems.items[3]; groupHeaderFirstHeader = groupedHeader.columnManager.getHeaderAtIndex(0); // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gam().getHeaderIndex(groupedHeader); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gam().getHeaderAtIndex(index); expect(colMgrHeader).toBe(groupHeaderFirstHeader); expect(colMgrHeader.hidden).toBe(true); expect(colMgrHeader.text).toBe('Foo Price'); }); }); }); describe('visible only', function () { describe('when argument is a column', function () { it('should return the correct index for the header', function() { expect(gvm().getHeaderIndex(headerCtItems.items[1])).toBe(0); }); it("should return -1 if the column doesn't exist", function() { column = new Ext.grid.column.Column(); expect(gvm().getHeaderIndex(column)).toBe(-1); }); it('should not return a hidden sub-header', function () { var header; header = headerCtItems.items[0]; index = gvm().getHeaderIndex(header); expect(header.hidden).toBe(true); expect(index).toBe(-1); }); it('should return a valid index', function () { index = gvm().getHeaderIndex(headerCtItems.items[1]); expect(index).not.toBe(-1); // Will filter out the first hidden column in the stack. expect(index).toBe(0); }); it('should return the index of the header in its owner stack - rootHeader', function () { index = gvm().getHeaderIndex(headerCtItems.items[3].items.items[2]); expect(index).toBe(4); }); it('should return the index of the header in its owner stack - groupHeader', function () { // Note that this spec is using the same header as the previous spec to demonstrate the difference. var groupHeader = headerCtItems.items[3]; index = groupHeader.visibleColumnManager.getHeaderIndex(groupHeader.items.items[2]); expect(index).toBe(1); }); }); describe('when argument is a group header', function () { it('should return a valid index', function () { index = gvm().getHeaderIndex(headerCtItems.items[2]); expect(index).not.toBe(-1); // Will filter out the second hidden column in the stack. expect(index).toBe(1); }); it('should return an index of the first leaf of group header', function () { var colMgrHeader; // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gvm().getHeaderIndex(headerCtItems.items[2]); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gvm().getHeaderAtIndex(index); // Remember, this is the index of the root header's visible col mgr. expect(index).toBe(1); expect(colMgrHeader.hidden).toBe(false); expect(colMgrHeader.dataIndex).toBe('price'); }); it("should be a reference to the first leaf header in the grouped header's columnn manager", function () { var groupedHeader, colMgrHeader, groupHeaderFirstHeader; groupedHeader = headerCtItems.items[2]; groupHeaderFirstHeader = headerCtItems.items[2].visibleColumnManager.getHeaderAtIndex(0); // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gvm().getHeaderIndex(groupedHeader); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gvm().getHeaderAtIndex(index); expect(colMgrHeader).toBe(groupHeaderFirstHeader); expect(colMgrHeader.hidden).toBe(groupHeaderFirstHeader.hidden); expect(colMgrHeader.dataIndex).toBe(groupHeaderFirstHeader.dataIndex); }); it('should not return a hidden sub-header', function () { var groupedHeader, colMgrHeader, groupHeaderFirstHeader; groupedHeader = headerCtItems.items[3]; groupHeaderFirstHeader = groupedHeader.visibleColumnManager.getHeaderAtIndex(0); // First, get the index from the column mgr. It will retrieve it from the group header's column mgr. index = gvm().getHeaderIndex(groupedHeader); // Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers). colMgrHeader = gvm().getHeaderAtIndex(index); expect(colMgrHeader).toBe(groupHeaderFirstHeader); expect(colMgrHeader.hidden).toBe(false); expect(colMgrHeader.text).toBe('Foo Phone'); }); }); }); }); describe('getHeaderAtIndex', function () { var header, headerCtItems; beforeEach(function () { makeGrid([{ text: 'Name', width: 100, dataIndex: 'name', hidden: true },{ text: 'Email', width: 100, dataIndex: 'email' }, { text: 'Stock Price', columns: [{ text: 'Price', width: 75, dataIndex: 'price' }, { text: 'Phone', width: 80, dataIndex: 'phone', hidden: true }, { text: '% Change', width: 40, dataIndex: 'pctChange' }] }, { text: 'Foo', columns: [{ text: 'Foo Price', width: 75, dataIndex: 'price', hidden: true }, { text: 'Foo Phone', width: 80, dataIndex: 'phone' }, { text: 'Foo % Change', width: 40, dataIndex: 'pctChange' }] }]); headerCtItems = grid.headerCt.items; }); afterEach(function () { header = headerCtItems = null; }); describe('all columns', function () { it('should return a valid header', function () { header = gam().getHeaderAtIndex(0); expect(header).not.toBe(null); expect(header.dataIndex).toBe('name'); }); it('should return the correct header from the index', function() { expect(gam().getHeaderAtIndex(0).dataIndex).toBe('name'); }); it("should return null if the column doesn't exist", function() { expect(gam().getHeaderAtIndex(50)).toBe(null); }); it('should return the header regardless of visibility', function () { var header2; header = gam().getHeaderAtIndex(0); header2 = gam().getHeaderAtIndex(1); expect(header).not.toBe(null); expect(header.hidden).toBe(true); expect(header2).not.toBe(null); expect(header2.hidden).toBe(false); }); it('should return the header in its owner stack - rootHeader', function () { header = gam().getHeaderAtIndex(0); expect(header.text).toBe('Name'); }); it('should return the index of the header in its owner stack - groupHeader', function () { // Note that this spec is using the index as the previous spec to demonstrate the difference. header = headerCtItems.items[3].columnManager.getHeaderAtIndex(0); expect(header.text).toBe('Foo Price'); }); }); describe('visible only', function () { it('should return the correct header from the index', function() { expect(gvm().getHeaderAtIndex(0).dataIndex).toBe('email'); }); it("should return null if the column doesn't exist", function() { expect(gvm().getHeaderAtIndex(50)).toBe(null); }); it('should not return a hidden sub-header', function () { header = gvm().getHeaderAtIndex(2); expect(header.hidden).toBe(false); expect(header.dataIndex).toBe('pctChange'); }); it('should return a valid header', function () { header = gvm().getHeaderAtIndex(0); expect(header).not.toBe(null); expect(header.dataIndex).toBe('email'); }); it('should return the header in its owner stack - rootHeader', function () { header = gvm().getHeaderAtIndex(0); expect(header.text).toBe('Email'); }); it('should return the index of the header in its owner stack - groupHeader', function () { // Note that this spec is using the same header as the previous spec to demonstrate the difference. var groupHeader = headerCtItems.items[3]; header = headerCtItems.items[3].visibleColumnManager.getHeaderAtIndex(0); expect(header.text).toBe('Foo Phone'); }); }); }); describe('hidden columns', function() { // Hidden at index 3/6 beforeEach(function(){ makeGrid(8, null, function(i){ return i > 0 && i % 3 === 0; }); }); it("should return all columns when using getColumnManager", function(){ expect(ga().length).toBe(8); }); it("should return only visible columns when using getVisibleColumnManager", function(){ expect(gv().length).toBe(6); }); it("should update the collection when hiding a column", function(){ colRef[0].hide(); expect(gv().length).toBe(5); }); it("should update the collection when showing a column", function(){ colRef[3].show(); expect(gv().length).toBe(7); }); describe("getHeaderAtIndex", function(){ it("should return the column reference", function(){ expect(gvm().getHeaderAtIndex(3)).toBe(colRef[4]); }); it("should return null if the index is out of bounds", function(){ expect(gvm().getHeaderAtIndex(7)).toBeNull(); }); }); describe("getHeaderById", function(){ it("should return the column reference by id", function(){ expect(gvm().getHeaderById('col1')).toBe(colRef[1]); }); it("should return null if the id doesn't exist", function() { expect(gvm().getHeaderById('col3')).toBeNull(); }); }); it("should return the first item", function(){ expect(gvm().getFirst()).toBe(colRef[0]); }); it("should return the last item", function(){ expect(gvm().getLast()).toBe(colRef[7]); }); describe("getNextSibling", function(){ it("should return the next sibling", function(){ expect(gvm().getNextSibling(colRef[2])).toBe(colRef[4]); }); it("should return the null if the next sibling doesn't exist", function(){ expect(gvm().getNextSibling(colRef[3])).toBeNull(); }); }); describe("getPreviousSibling", function(){ it("should return the previous sibling", function(){ expect(gvm().getPreviousSibling(colRef[7])).toBe(colRef[5]); }); it("should return the null if the previous sibling doesn't exist", function(){ expect(gvm().getPreviousSibling(colRef[6])).toBeNull(); }); }); }); describe("locking", function(){ // first 4 locked beforeEach(function(){ makeGrid(10, null, null, function(i){ return i <= 3; }); }); describe("global manager", function() { it("should return both sets of columns", function(){ expect(ga().length).toBe(10); }); it("should update the collection when adding to the locked side", function(){ grid.lockedGrid.headerCt.add({ text: 'Foo' }); expect(ga().length).toBe(11); }); it("should update the collection when adding to the unlocked side", function(){ grid.normalGrid.headerCt.add({ text: 'Foo' }); expect(ga().length).toBe(11); }); it("should update the collection when removing from the locked side", function(){ grid.lockedGrid.headerCt.remove(0); expect(ga().length).toBe(9); }); it("should update the collection when removing from the unlocked side", function(){ grid.normalGrid.headerCt.remove(0); expect(ga().length).toBe(9); }); it("should maintain the same size when locking an item", function(){ grid.lock(colRef[4]); expect(ga().length).toBe(10); }); it("should maintain the same size when unlocking an item", function(){ grid.unlock(colRef[0]); expect(ga().length).toBe(10); }); }); describe("locked side", function(){ var glm = function(){ return grid.lockedGrid.getColumnManager(); }; it("should only return the columns for this side", function(){ expect(glm().getColumns().length).toBe(4); }); it("should update the collection when adding an item to this side", function(){ grid.lock(colRef[9]); expect(glm().getColumns().length).toBe(5); }); it("should update the collection when removing an item from this side", function(){ grid.unlock(colRef[0]); expect(glm().getColumns().length).toBe(3); }); describe("function", function(){ describe("getHeaderIndex", function() { it("should return the correct index for the header", function() { expect(glm().getHeaderIndex(colRef[2])).toBe(2); }); it("should return -1 if the column doesn't exist", function(){ expect(glm().getHeaderIndex(colRef[5])).toBe(-1); }); }); describe("getHeaderAtIndex", function(){ it("should return the column reference", function(){ expect(glm().getHeaderAtIndex(3)).toBe(colRef[3]); }); it("should return null if the index is out of bounds", function(){ expect(glm().getHeaderAtIndex(6)).toBeNull(); }); }); describe("getHeaderById", function(){ it("should return the column reference by id", function(){ expect(glm().getHeaderById('col1')).toBe(colRef[1]); }); it("should return null if the id doesn't exist", function() { expect(glm().getHeaderById('col5')).toBeNull(); }); }); }); }); describe("unlocked side", function(){ var gum = function(){ return grid.normalGrid.getColumnManager(); }; it("should only return the columns for this side", function(){ expect(gum().getColumns().length).toBe(6); }); it("should update the collection when adding an item to this side", function(){ grid.unlock(colRef[1]); expect(gum().getColumns().length).toBe(7); }); it("should update the collection when removing an item from this side", function(){ grid.lock(colRef[7]); expect(gum().getColumns().length).toBe(5); }); describe("function", function(){ var offset = 4; describe("getHeaderIndex", function() { it("should return the correct index for the header", function() { expect(gum().getHeaderIndex(colRef[offset + 2])).toBe(2); }); it("should return -1 if the column doesn't exist", function(){ expect(gum().getHeaderIndex(colRef[0])).toBe(-1); }); }); describe("getHeaderAtIndex", function(){ it("should return the column reference", function(){ expect(gum().getHeaderAtIndex(3)).toBe(colRef[3 + offset]); }); it("should return null if the index is out of bounds", function(){ expect(gum().getHeaderAtIndex(6)).toBeNull(); }); }); describe("getHeaderById", function(){ it("should return the column reference by id", function(){ expect(gum().getHeaderById('col6')).toBe(colRef[6]); }); it("should return null if the id doesn't exist", function() { expect(gum().getHeaderById('col2')).toBeNull(); }); }); }); }); }); }); describe("menu", function() { it("should not allow menu to be shown when menuDisabled: true", function() { makeGrid([{ dataIndex: 'field0', width: 200, filter: 'string', menuDisabled: true }], { plugins: 'gridfilters' }); // menuDisabled=true, shouldn't have a trigger expect(colRef[0].triggerEl).toBeNull(); }); it("should not allow menu to be shown when grid is configured with enableColumnHide: false and sortableColumns: false", function() { makeGrid([{ dataIndex: 'field0', width: 200 }], { enableColumnHide: false, sortableColumns: false }); expect(colRef[0].triggerEl).toBeNull(); }); it("should allow menu to be shown when requiresMenu: true (from plugin) and grid is configured with enableColumnHide: false and sortableColumns: false", function() { makeGrid([{ dataIndex: 'field0', width: 200, filter: 'string' }], { enableColumnHide: false, sortableColumns: false, plugins: 'gridfilters' }); var col = colRef[0], menu; col.triggerEl.show(); jasmine.fireMouseEvent(col.triggerEl.dom, 'click'); menu = col.activeMenu; expect(menu.isVisible()).toBe(true); expect(col.requiresMenu).toBe(true); }); }); describe("sorting", function() { it("should sort by dataIndex when clicking on the header with sortable: true", function() { makeGrid([{ dataIndex: 'field0', sortable: true }]); clickHeader(colRef[0]); var sorters = store.getSorters(); expect(sorters.getCount()).toBe(1); expect(sorters.first().getProperty()).toBe('field0'); expect(sorters.first().getDirection()).toBe('ASC'); }); it("should invert the sort order when clicking on a sorted column", function() { makeGrid([{ dataIndex: 'field0', sortable: true }]); clickHeader(colRef[0]); var sorters = store.getSorters(); clickHeader(colRef[0]); expect(sorters.getCount()).toBe(1); expect(sorters.first().getProperty()).toBe('field0'); expect(sorters.first().getDirection()).toBe('DESC'); clickHeader(colRef[0]); expect(sorters.getCount()).toBe(1); expect(sorters.first().getProperty()).toBe('field0'); expect(sorters.first().getDirection()).toBe('ASC'); }); it("should not sort when configured with sortable false", function() { makeGrid([{ dataIndex: 'field0', sortable: false }]); clickHeader(colRef[0]); expect(store.getSorters().getCount()).toBe(0); }); it("should not sort when the grid is configured with sortableColumns: false", function() { makeGrid([{ dataIndex: 'field0' }], { sortableColumns: false }); clickHeader(colRef[0]); expect(store.getSorters().getCount()).toBe(0); }); }); describe("grouped columns", function() { var baseCols; function createGrid(cols, stateful) { if (grid) { grid.destroy(); grid = null; } makeGrid(cols, { renderTo: null, stateful: stateful, stateId: 'foo' }); } function getCol(id) { return grid.down('#' + id); } describe('when stateful', function () { var col; beforeEach(function () { new Ext.state.Provider(); makeGrid([{ itemId: 'main1', columns: [{ itemId: 'child1' }, { itemId: 'child2' }, { itemId: 'child3' }] }, { itemId: 'main2', columns: [{ itemId: 'child4' }, { itemId: 'child5' }, { itemId: 'child6' }] }], { stateful: true, stateId: 'foo' }); }); afterEach(function () { Ext.state.Manager.getProvider().clear(); col = null; }); it('should work when toggling visibility on the groups', function () { // See EXTJS-11661. col = grid.down('#main2'); col.hide(); // Trigger the bug. grid.saveState(); col.show(); // Now, select one of the col's children and query its hidden state. // Really, we can check anything here, b/c if the bug wasn't fixed then // a TypeError would be thrown in Ext.view.TableLayout#setColumnWidths. expect(grid.down('#child6').hidden).toBe(false); }); it('should not show a previously hidden subheader when the visibility of its group header is toggled', function () { var subheader = grid.down('#child4'); subheader.hide(); col = grid.down('#main2'); col.hide(); col.show(); expect(subheader.hidden).toBe(true); }); }); describe("column visibility", function() { var cells; afterEach(function () { cells = null; }); describe("hiding/show during construction", function() { it("should be able to show a column during construction", function() { expect(function() { makeGrid([{ dataIndex: 'field1', hidden: true, listeners: { added: function(c) { c.show(); } } }]); }).not.toThrow(); expect(grid.getVisibleColumnManager().getColumns()[0]).toBe(colRef[0]); }); it("should be able to hide a column during construction", function() { expect(function() { makeGrid([{ dataIndex: 'field1', listeners: { added: function(c) { c.hide(); } } }]); }).not.toThrow(); expect(grid.getVisibleColumnManager().getColumns().length).toBe(0); }); }); describe('when groupheader parent is hidden', function () { describe('hidden at config time', function () { beforeEach(function () { makeGrid([{ itemId: 'main1' }, { itemId: 'main2', hidden: true, columns: [{ itemId: 'child1' }, { itemId: 'child2' }] }]); cells = grid.view.body.query('.x-grid-row td'); }); it('should hide child columns at config time if the parent is hidden', function () { expect(grid.down('#child1').getInherited().hidden).toBe(true); expect(grid.down('#child2').getInherited().hidden).toBe(true); // Check the view. expect(cells.length).toBe(1); }); it('should not explicitly hide any child columns (they will be hierarchically hidden)', function () { expect(grid.down('#child1').hidden).toBe(false); expect(grid.down('#child2').hidden).toBe(false); // Check the view. expect(cells.length).toBe(1); }); }); describe('hidden at run time', function () { beforeEach(function () { makeGrid([{ itemId: 'main1' }, { itemId: 'main2', columns: [{ itemId: 'child1' }, { itemId: 'child2' }] }]); grid.down('#main2').hide(); cells = grid.view.body.query('.x-grid-row td'); }); it('should hide child columns at runtime if the parent is hidden', function () { expect(grid.down('#child1').getInherited().hidden).toBe(true); expect(grid.down('#child2').getInherited().hidden).toBe(true); // Check the view. expect(cells.length).toBe(1); }); it('should not explicitly hide any child columns (they will be hierarchically hidden)', function () { expect(grid.down('#child1').hidden).toBe(false); expect(grid.down('#child2').hidden).toBe(false); // Check the view. expect(cells.length).toBe(1); }); }); }); describe('when groupheader parent is shown', function () { describe('shown at config time', function () { beforeEach(function () { makeGrid([{ itemId: 'main1' }, { itemId: 'main2', columns: [{ itemId: 'child1' }, { itemId: 'child2' }] }]); cells = grid.view.body.query('.x-grid-row td'); }); it('should not hide child columns at config time if the parent is shown', function () { expect(grid.down('#child1').getInherited().hidden).not.toBeDefined(); expect(grid.down('#child2').getInherited().hidden).not.toBeDefined(); // Check the view. expect(cells.length).toBe(3); }); it('should not explicitly hide any child columns (they will be hierarchically shown)', function () { expect(grid.down('#child1').hidden).toBe(false); expect(grid.down('#child2').hidden).toBe(false); // Check the view. expect(cells.length).toBe(3); }); }); describe('shown at run time', function () { beforeEach(function () { makeGrid([{ itemId: 'main1' }, { itemId: 'main2', hidden: true, columns: [{ itemId: 'child1' }, { itemId: 'child2' }] }]); grid.down('#main2').show(); cells = grid.view.body.query('.x-grid-row td'); }); it('should show child columns at runtime if the parent is shown', function () { expect(grid.down('#child1').getInherited().hidden).not.toBeDefined(); expect(grid.down('#child2').getInherited().hidden).not.toBeDefined(); // Check the view. expect(cells.length).toBe(3); }); it('should not explicitly hide any child columns (they will be hierarchically shown)', function () { expect(grid.down('#child1').hidden).toBe(false); expect(grid.down('#child2').hidden).toBe(false); // Check the view. expect(cells.length).toBe(3); }); }); }); describe("hiding/showing children", function() { beforeEach(function() { baseCols = [{ itemId: 'col1', columns: [{ itemId: 'col11' }, { itemId: 'col12' }, { itemId: 'col13' }] }, { itemId: 'col2', columns: [{ itemId: 'col21' }, { itemId: 'col22' }, { itemId: 'col23' }] }]; }); it('should not show a previously hidden subheader when the visibility of its group header is toggled', function () { var subheader, col; makeGrid([{ itemId: 'main1' }, { itemId: 'main2', columns: [{ itemId: 'child1' }, { itemId: 'child2' }] }]); subheader = grid.down('#child1'); subheader.hide(); col = grid.down('#main2'); col.hide(); col.show(); expect(subheader.hidden).toBe(true); }); it('should allow any subheader to be reshown when all subheaders are currently hidden', function () { // There was a bug where a subheader could not be reshown when itself and all of its fellows were curently hidden. // See EXTJS-18515. var subheader; makeGrid([{ itemId: 'main1' }, { itemId: 'main2', columns: [{ itemId: 'child1' }, { itemId: 'child2' }, { itemId: 'child3' }] }]); grid.down('#child1').hide(); grid.down('#child2').hide(); subheader = grid.down('#child3'); // Toggling would reveal the bug. subheader.hide(); expect(subheader.hidden).toBe(true); subheader.show(); expect(subheader.hidden).toBe(false); }); it('should show the last hidden subheader if all subheaders are currently hidden when the group is reshown', function () { var groupheader, subheader1, subheader2, subheader3; makeGrid([{ itemId: 'main1' }, { itemId: 'main2', columns: [{ itemId: 'child1' }, { itemId: 'child2' }, { itemId: 'child3' }] }]); groupheader = grid.down('#main2'); subheader1 = grid.down('#child1').hide(); subheader3 = grid.down('#child3').hide(); subheader2 = grid.down('#child2') subheader2.hide(); expect(subheader2.hidden).toBe(true); groupheader.show(); // The last hidden subheader should now be shown. expect(subheader2.hidden).toBe(false); // Let's also demonstrate that the others are still hidden. expect(subheader1.hidden).toBe(true); expect(subheader3.hidden).toBe(true); }); describe("initial configuration", function() { it("should not hide the parent by default", function() { createGrid(baseCols); expect(getCol('col1').hidden).toBe(false); }); it("should not hide the parent if not all children are hidden", function() { baseCols[1].columns[2].hidden = baseCols[1].columns[0].hidden = true; createGrid(baseCols); expect(getCol('col2').hidden).toBe(false); }); it("should hide the parent if all children are hidden", function() { baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true; createGrid(baseCols); expect(getCol('col2').hidden).toBe(true); }); }); describe("before render", function() { it("should hide the parent when hiding all children", function() { createGrid(baseCols); getCol('col21').hide(); getCol('col22').hide(); getCol('col23').hide(); grid.render(Ext.getBody()); expect(getCol('col2').hidden).toBe(true); }); it("should show the parent when showing a hidden child", function() { baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true; createGrid(baseCols); getCol('col22').show(); grid.render(Ext.getBody()); expect(getCol('col2').hidden).toBe(false); }); }); describe("after render", function() { it("should hide the parent when hiding all children", function() { createGrid(baseCols); grid.render(Ext.getBody()); getCol('col21').hide(); getCol('col22').hide(); getCol('col23').hide(); expect(getCol('col2').hidden).toBe(true); }); it("should show the parent when showing a hidden child", function() { baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true; createGrid(baseCols); grid.render(Ext.getBody()); getCol('col22').show(); expect(getCol('col2').hidden).toBe(false); }); it("should only trigger a single layout when hiding the last leaf in a group", function() { baseCols[0].columns.splice(1, 2); createGrid(baseCols); grid.render(Ext.getBody()); var count = grid.componentLayoutCounter; getCol('col11').hide(); expect(grid.componentLayoutCounter).toBe(count + 1); }); it("should only trigger a single refresh when hiding the last leaf in a group", function() { baseCols[0].columns.splice(1, 2); createGrid(baseCols); grid.render(Ext.getBody()); var view = grid.getView(), count = view.refreshCounter; getCol('col11').hide(); expect(view.refreshCounter).toBe(count + 1); }); }); describe('nested stacked columns', function () { // Test stacked group headers where the only child is the next group header in the hierarchy. // The last (lowest in the stack) group header will contain multiple child items. // For example: // // +-----------------------------------+ // | col1 | // |-----------------------------------| // | col2 | // other |-----------------------------------| other // headers | col3 | headers // |-----------------------------------| // | col4 | // |-----------------------------------| // | Field1 | Field2 | Field3 | Field4 | // |===================================| // | view | // +-----------------------------------+ // function assertHiddenState(n, hiddenState) { while (n) { expect(getCol('col' + n).hidden).toBe(hiddenState); --n; } } describe('on hide', function () { beforeEach(function() { baseCols = [{ itemId: 'col1', columns: [{ itemId: 'col2', columns: [{ itemId: 'col3', columns: [{ itemId: 'col4', columns: [{ itemId: 'col41' }, { itemId: 'col42' }, { itemId: 'col43' }, { itemId: 'col44' }] }] }] }] }, { itemId: 'col5' }] }); it('should hide every group header above the target group header', function () { createGrid(baseCols); getCol('col4').hide(); assertHiddenState(4, true); tearDown(); setup(); createGrid(baseCols); getCol('col3').hide(); assertHiddenState(3, true); tearDown(); setup(); createGrid(baseCols); getCol('col2').hide(); assertHiddenState(2, true); }); it('should reshow every group header above the target group header when toggled', function () { createGrid(baseCols); getCol('col4').hide(); assertHiddenState(4, true); getCol('col4').show(); assertHiddenState(4, false); tearDown(); setup(); createGrid(baseCols); getCol('col3').hide(); assertHiddenState(3, true); getCol('col3').show(); assertHiddenState(3, false); tearDown(); setup(); createGrid(baseCols); getCol('col2').hide(); assertHiddenState(2, true); getCol('col2').show(); assertHiddenState(2, false); }); describe('subheaders', function () { it('should hide all ancestor group headers when hiding all subheaders in lowest group header', function () { createGrid(baseCols); getCol('col41').hide(); getCol('col42').hide(); getCol('col43').hide(); getCol('col44').hide(); assertHiddenState(4, true); }); }); }); describe('on show', function () { beforeEach(function() { baseCols = [{ itemId: 'col1', hidden: true, columns: [{ itemId: 'col2', hidden: true, columns: [{ itemId: 'col3', hidden: true, columns: [{ itemId: 'col4', hidden: true, columns: [{ itemId: 'col41' }, { itemId: 'col42' }, { itemId: 'col43' }, { itemId: 'col44' }] }] }] }] }, { itemId: 'col5' }] }); it('should show every group header above the target group header', function () { // Here we're showing that a header that is explicitly shown will have every header // above it shown as well. createGrid(baseCols); getCol('col4').show(); assertHiddenState(4, false); tearDown(); setup(); createGrid(baseCols); getCol('col3').show(); assertHiddenState(3, false); tearDown(); setup(); createGrid(baseCols); getCol('col2').show(); assertHiddenState(2, false); }); it('should show every group header in the chain no matter which group header is checked', function () { // Here we're showing that a header that is explicitly shown will have every header // in the chain shown, no matter which group header was clicked. // // Group headers are special in that they are auto-hidden when their subheaders are all // hidden and auto-shown when the first subheader is reshown. They are the only headers // that should now be auto-shown or -hidden. // // It follows that since group headers are dictated by some automation depending upon the // state of their child items that all group headers should be shown if anyone in the // hierarchy is shown since these special group headers only contain one child, which is // the next group header in the stack. createGrid(baseCols); getCol('col4').show(); assertHiddenState(4, false); tearDown(); setup(); createGrid(baseCols); getCol('col3').show(); assertHiddenState(4, false); tearDown(); setup(); createGrid(baseCols); getCol('col2').show(); assertHiddenState(4, false); tearDown(); setup(); createGrid(baseCols); getCol('col1').show(); assertHiddenState(4, false); }); it('should rehide every group header above the target group header when toggled', function () { createGrid(baseCols); getCol('col4').show(); assertHiddenState(4, false); getCol('col4').hide(); assertHiddenState(4, true); tearDown(); setup(); createGrid(baseCols); getCol('col3').show(); assertHiddenState(3, false); getCol('col3').hide(); assertHiddenState(3, true); tearDown(); setup(); createGrid(baseCols); getCol('col2').show(); assertHiddenState(2, false); getCol('col2').hide(); assertHiddenState(2, true); }); describe('subheaders', function () { it('should not show any ancestor group headers when hiding all subheaders in lowest group header', function () { createGrid(baseCols); getCol('col41').hide(); getCol('col42').hide(); getCol('col43').hide(); getCol('col44').hide(); assertHiddenState(4, true); }); it('should show all ancestor group headers when hiding all subheaders in lowest group header and then showing one', function () { createGrid(baseCols); getCol('col41').hide(); getCol('col42').hide(); getCol('col43').hide(); getCol('col44').hide(); assertHiddenState(4, true); getCol('col42').show(); assertHiddenState(4, false); }); it('should remember which subheader was last checked and restore its state when its group header is rechecked', function () { var col, subheader, headerCt; // Let's hide the 3rd menu item. makeGrid(baseCols); col = getCol('col4'); subheader = getCol('col43'); headerCt = grid.headerCt; getCol('col41').hide(); getCol('col42').hide(); getCol('col44').hide(); subheader.hide(); expect(col.hidden).toBe(true); // Get the menu item. headerCt.getMenuItemForHeader(headerCt.menu, col).setChecked(true); expect(subheader.hidden).toBe(false); // Now let's hide the 2nd menu item. tearDown(); setup(); makeGrid(baseCols); col = getCol('col4'); subheader = getCol('col42'); headerCt = grid.headerCt; getCol('col41').hide(); getCol('col43').hide(); getCol('col44').hide(); subheader.hide(); expect(col.hidden).toBe(true); // Get the menu item. headerCt.getMenuItemForHeader(headerCt.menu, col).setChecked(true); expect(subheader.hidden).toBe(false); }); it('should only show visible subheaders when all group headers are shown', function () { var col; createGrid(baseCols); col = getCol('col4'); // All subheaders are visible. col.show(); expect(col.visibleColumnManager.getColumns().length).toBe(4); // Hide the group header and hide two subheaders. col.hide(); getCol('col42').hide(); getCol('col43').hide(); // Only two subheaders should now be visible. col.show(); expect(col.visibleColumnManager.getColumns().length).toBe(2); }); }); }); }); }); describe("adding/removing children", function() { beforeEach(function() { baseCols = [{ itemId: 'col1', columns: [{ itemId: 'col11' }, { itemId: 'col12' }, { itemId: 'col13' }] }, { itemId: 'col2', columns: [{ itemId: 'col21' }, { itemId: 'col22' }, { itemId: 'col23' }] }]; }); describe("before render", function() { it("should hide the parent if removing the last hidden item", function() { baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = true; createGrid(baseCols); getCol('col13').destroy(); grid.render(Ext.getBody()); expect(getCol('col1').hidden).toBe(true); }); it("should show the parent if adding a visible item and all items are hidden", function() { baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = baseCols[0].columns[2].hidden = true; createGrid(baseCols); getCol('col1').add({ itemId: 'col14' }); grid.render(Ext.getBody()); expect(getCol('col1').hidden).toBe(false); }); }); describe("after render", function() { it("should hide the parent if removing the last hidden item", function() { baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = true; createGrid(baseCols); grid.render(Ext.getBody()); getCol('col13').destroy(); expect(getCol('col1').hidden).toBe(true); }); it("should show the parent if adding a visible item and all items are hidden", function() { baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = baseCols[0].columns[2].hidden = true; createGrid(baseCols); grid.render(Ext.getBody()); getCol('col1').add({ itemId: 'col14' }); expect(getCol('col1').hidden).toBe(false); }); }); }); }); describe("removing columns from group", function() { beforeEach(function() { baseCols = [{ itemId: 'col1', columns: [{ itemId: 'col11' }, { itemId: 'col12' }, { itemId: 'col13' }] }, { itemId: 'col2', columns: [{ itemId: 'col21' }, { itemId: 'col22' }, { itemId: 'col23' }] }]; createGrid(baseCols); }); describe("before render", function() { it("should destroy the group header when removing all columns", function() { var headerCt = grid.headerCt, col2 = getCol('col2'); expect(headerCt.items.indexOf(col2)).toBe(1); getCol('col21').destroy(); getCol('col22').destroy(); getCol('col23').destroy(); expect(col2.destroyed).toBe(true); expect(headerCt.items.indexOf(col2)).toBe(-1); }); }); describe("after render", function() { it("should destroy the group header when removing all columns", function() { createGrid(baseCols); grid.render(Ext.getBody()); var headerCt = grid.headerCt, col2 = getCol('col2'); expect(headerCt.items.indexOf(col2)).toBe(1); getCol('col21').destroy(); getCol('col22').destroy(); getCol('col23').destroy(); expect(col2.destroyed).toBe(true); expect(headerCt.items.indexOf(col2)).toBe(-1); }); }); }); }); describe("column operations & the view", function() { describe('', function () { beforeEach(function() { makeGrid(); }); it("should update the view when adding a new header", function() { grid.headerCt.insert(0, { dataIndex: 'field4' }); expect(getCellText(0, 0)).toBe('val5'); }); it("should update the view when moving an existing header", function() { grid.headerCt.insert(0, colRef[1]); expect(getCellText(0, 0)).toBe('val2'); }); it("should update the view when removing a header", function() { grid.headerCt.remove(1); expect(getCellText(0, 1)).toBe('val3'); }); it("should not refresh the view when doing a drag/drop move", function() { var called = false, header; grid.getView().on('refresh', function() { called = true; }); // Simulate a DD here header = colRef[0]; grid.headerCt.move(0, 3); expect(getCellText(0, 3)).toBe('val1'); expect(called).toBe(false); }); }); describe('toggling column visibility', function () { var refreshCounter; beforeEach(function () { makeGrid(); refreshCounter = view.refreshCounter; }); afterEach(function () { refreshCounter = null; }); describe('hiding', function () { it('should update the view', function () { colRef[0].hide(); expect(view.refreshCounter).toBe(refreshCounter + 1); }); }); describe('showing', function () { it('should update the view', function () { colRef[0].hide(); refreshCounter = view.refreshCounter; colRef[0].show(); expect(view.refreshCounter).toBe(refreshCounter + 1); }); }); }); }); describe("locked/normal grid visibility", function() { function expectVisible(locked, normal) { expect(grid.lockedGrid.isVisible()).toBe(locked); expect(grid.normalGrid.isVisible()).toBe(normal); } var failCount; beforeEach(function() { failCount = Ext.failedLayouts; }); afterEach(function() { expect(failCount).toBe(Ext.failedLayouts); failCount = null; }); describe("initial", function() { it("should have both sides visible", function() { makeGrid([{locked: true}, {}], { syncTaskDelay: 0 }); expectVisible(true, true); }); it("should have only the normal side visible if there are no locked columns", function() { makeGrid([{}, {}], { enableLocking: true, syncTaskDelay: 0 }); expectVisible(false, true); }); it("should have only the locked side visible if there are no normal columns", function() { makeGrid([{locked: true}, {locked: true}], { syncTaskDelay: 0 }); expectVisible(true, false); }); }); describe("dynamic", function() { beforeEach(function() { makeGrid([{ locked: true, itemId: 'col0' }, { locked: true, itemId: 'col1' }, { itemId: 'col2' }, { itemId: 'col3' }], { syncTaskDelay: 0 }); }); describe("normal side", function() { it("should not hide when removing a column but there are other normal columns", function() { grid.normalGrid.headerCt.remove('col2'); expectVisible(true, true); }); it("should hide when removing the last normal column", function() { grid.normalGrid.headerCt.remove('col2'); grid.normalGrid.headerCt.remove('col3'); expectVisible(true, false); }); it("should not hide when hiding a column but there are other visible normal columns", function() { colRef[2].hide(); expectVisible(true, true); }); it("should hide when hiding the last normal column", function() { colRef[2].hide(); colRef[3].hide(); expectVisible(true, false); }); }); describe("locked side", function() { it("should not hide when removing a column but there are other locked columns", function() { grid.lockedGrid.headerCt.remove('col0'); expectVisible(true, true); }); it("should hide when removing the last locked column", function() { grid.lockedGrid.headerCt.remove('col0'); grid.lockedGrid.headerCt.remove('col1'); expectVisible(false, true); }); it("should not hide when hiding a column but there are other visible locked columns", function() { colRef[0].hide(); expectVisible(true, true); }); it("should hide when hiding the last locked column", function() { colRef[0].hide(); colRef[1].hide(); expectVisible(false, true); }); }); }); }); describe("rendering", function() { beforeEach(function() { makeGrid(); }); describe("first/last", function() { it("should stamp x-grid-cell-first on the first column cell", function() { var cls = grid.getView().firstCls; expect(hasCls(getCell(0, 0), cls)).toBe(true); expect(hasCls(getCell(0, 1), cls)).toBe(false); expect(hasCls(getCell(0, 2), cls)).toBe(false); expect(hasCls(getCell(0, 3), cls)).toBe(false); }); it("should stamp x-grid-cell-last on the last column cell", function() { var cls = grid.getView().lastCls; expect(hasCls(getCell(0, 0), cls)).toBe(false); expect(hasCls(getCell(0, 1), cls)).toBe(false); expect(hasCls(getCell(0, 2), cls)).toBe(false); expect(hasCls(getCell(0, 3), cls)).toBe(true); }); it("should update the first class when moving the first column", function() { grid.headerCt.insert(0, colRef[1]); var cell = getCell(0, 0), view = grid.getView(), cls = view.firstCls; expect(getCellText(0, 0)).toBe('val2'); expect(hasCls(cell, cls)).toBe(true); expect(hasCls(getCell(0, 1), cls)).toBe(false); }); it("should update the last class when moving the last column", function() { // Suppress console warning about reusing existing id spyOn(Ext.log, 'warn'); grid.headerCt.add(colRef[1]); var cell = getCell(0, 3), view = grid.getView(), cls = view.lastCls; expect(getCellText(0, 3)).toBe('val2'); expect(hasCls(cell, cls)).toBe(true); expect(hasCls(getCell(0, 2), cls)).toBe(false); }); }); describe("id", function() { it("should stamp the id of the column in the cell", function() { expect(hasCls(getCell(0, 0), 'x-grid-cell-col0')).toBe(true); expect(hasCls(getCell(0, 1), 'x-grid-cell-col1')).toBe(true); expect(hasCls(getCell(0, 2), 'x-grid-cell-col2')).toBe(true); expect(hasCls(getCell(0, 3), 'x-grid-cell-col3')).toBe(true); }); }); }); describe("hiddenHeaders", function() { it("should lay out the hidden items so cells obtain correct width", function() { makeGrid([{ width: 100 }, { flex: 1 }, { width: 200 }], { hiddenHeaders: true }); expect(getCell(0, 0).getWidth()).toBe(100); expect(getCell(0, 1).getWidth()).toBe(totalWidth - 200 - 100); expect(getCell(0, 2).getWidth()).toBe(200); }); it("should lay out grouped column headers", function() { makeGrid([{ width: 100 }, { columns: [{ width: 200 }, { width: 400 }, { width: 100 }] }, { width: 200 }], { hiddenHeaders: true }); expect(getCell(0, 0).getWidth()).toBe(100); expect(getCell(0, 1).getWidth()).toBe(200); expect(getCell(0, 2).getWidth()).toBe(400); expect(getCell(0, 3).getWidth()).toBe(100); expect(getCell(0, 4).getWidth()).toBe(200); }); }); describe("emptyCellText config", function () { function expectEmptyText(column, rowIdx, colIdx) { var cell = getCellInner(rowIdx, colIdx), el = document.createElement('div'); // We're doing this because ' ' !== '&#160;'. By letting the browser decode the entity, we // can then do a comparison. el.innerHTML = column.emptyCellText; expect(cell.textContent || cell.innerText).toBe(el.textContent || el.innerText); } describe("rendering", function() { beforeEach(function () { makeGrid([{ width: 100 }, { emptyCellText: 'derp', width: 200 }]); }); it("should use the default html entity for when there is no emptyCellText given", function () { expectEmptyText(colRef[0], 0, 0); }); it("should use the value of emptyCellText when configured", function () { expectEmptyText(colRef[1], 0, 1); }); }); describe("column update", function() { describe("full row update", function() { it("should use the empty text on update", function() { makeGrid([{ width: 100, dataIndex: 'field0', renderer: function(v, meta, rec) { return v; } }]); // Renderer with >1 arg requires a full row redraw store.getAt(0).set('field0', ''); expectEmptyText(colRef[0], 0, 0); }); }); describe("cell update only", function() { describe("producesHTML: true", function() { it("should use the empty text on update", function() { makeGrid([{ width: 100, producesHTML: true, dataIndex: 'field0' }]); store.getAt(0).set('field0', ''); expectEmptyText(colRef[0], 0, 0); }); it("should use the empty text on update with a simple renderer", function() { makeGrid([{ width: 100, producesHTML: true, dataIndex: 'field0', renderer: Ext.identityFn }]); store.getAt(0).set('field0', ''); expectEmptyText(colRef[0], 0, 0); }); }); describe("producesHTML: false", function() { it("should use the empty text on update", function() { makeGrid([{ width: 100, producesHTML: false, dataIndex: 'field0' }]); store.getAt(0).set('field0', ''); expectEmptyText(colRef[0], 0, 0); }); it("should use the empty text on update with a simple renderer", function() { makeGrid([{ width: 100, producesHTML: false, dataIndex: 'field0', renderer: Ext.identityFn }]); store.getAt(0).set('field0', ''); expectEmptyText(colRef[0], 0, 0); }); }); }); }); }); describe("non-column items in the header", function() { it("should show non-columns as children", function() { makeGrid([{ width: 100, items: { xtype: 'textfield', itemId: 'foo' } }]); expect(grid.down('#foo').isVisible(true)).toBe(true); }); it("should have the hidden item as visible after showing an initially hidden column", function() { makeGrid([{ width: 100, items: { xtype: 'textfield' } }, { width: 100, hidden: true, items: { xtype: 'textfield', itemId: 'foo' } }]); var field = grid.down('#foo'); expect(field.isVisible(true)).toBe(false); field.ownerCt.show(); expect(field.isVisible(true)).toBe(true); }); }); describe("reconfiguring", function() { it("should destroy any old columns", function() { var o = {}; makeGrid(4); Ext.Array.forEach(colRef, function(col) { col.on('destroy', function(c) { o[col.getItemId()] = true; }); }); grid.reconfigure(null, []); expect(o).toEqual({ col0: true, col1: true, col2: true, col3: true }); }); describe("with locking", function() { it("should resize the locked part to match the grid size", function() { makeGrid(4, null, null, function(i) { return i === 0; }); var borderWidth = grid.lockedGrid.el.getBorderWidth('lr'); // Default column width expect(grid.lockedGrid.getWidth()).toBe(100 + borderWidth); grid.reconfigure(null, [{ locked: true, width: 120 }, { locked: true, width: 170 }, {}, {}]) expect(grid.lockedGrid.getWidth()).toBe(120 + 170 + borderWidth); }); }); }); describe('column header borders', function() { it('should show header borders by default, and turn them off dynamically', function() { makeGrid(); expect(colRef[0].el.getBorderWidth('r')).toBe(1); expect(colRef[1].el.getBorderWidth('r')).toBe(1); expect(colRef[2].el.getBorderWidth('r')).toBe(1); grid.setHeaderBorders(false); expect(colRef[0].el.getBorderWidth('r')).toBe(0); expect(colRef[1].el.getBorderWidth('r')).toBe(0); expect(colRef[2].el.getBorderWidth('r')).toBe(0); }); it('should have no borders if configured false, and should show them dynamically', function() { makeGrid(null, { headerBorders: false }); expect(colRef[0].el.getBorderWidth('r')).toBe(0); expect(colRef[1].el.getBorderWidth('r')).toBe(0); expect(colRef[2].el.getBorderWidth('r')).toBe(0); grid.setHeaderBorders(true); expect(colRef[0].el.getBorderWidth('r')).toBe(1); expect(colRef[1].el.getBorderWidth('r')).toBe(1); expect(colRef[2].el.getBorderWidth('r')).toBe(1); }); }); describe('column resize', function() { it('should not fire drag events on headercontainer during resize', function() { makeGrid(); var colWidth = colRef[0].getWidth(), dragSpy = spyOnEvent(grid.headerCt.el, 'drag'); resizeColumn(colRef[0], 10); expect(colRef[0].getWidth()).toBe(colWidth + 10); expect(dragSpy).not.toHaveBeenCalled(); }); }); }); } createSuite(false); createSuite(true); });
san4osq/bindformext
ext/classic/classic/test/specs/grid/grid-columns.js
JavaScript
mit
120,088
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pigame.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
MoonCheesez/stack
PiGame/pigame/manage.py
Python
mit
804
/* * Copyright 2011 Matt Crinklaw-Vogt * * 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 com.tantaman.commons.examples; import java.util.Collection; import java.util.LinkedList; import org.debian.alioth.shootout.u32.nbody.NBodySystem; import com.tantaman.commons.concurrent.Parallel; public class ParallelForDemo { public static void main(String[] args) { Collection<Integer> elems = new LinkedList<Integer>(); for (int i = 0; i < 40; ++i) { elems.add(i*55000 + 100); } Parallel.For(elems, new Parallel.Operation<Integer>() { public void perform(Integer pParameter) { // do something with the parameter }; }); Parallel.Operation<Integer> bodiesOp = new Parallel.Operation<Integer>() { @Override public void perform(Integer pParameter) { NBodySystem bodies = new NBodySystem(); for (int i = 0; i < pParameter; ++i) bodies.advance(0.01); } }; System.out.println("RUNNING THE Parallel.For vs Parallel.ForFJ performance comparison"); System.out.println("This could take a while."); // warm up.. it really does have a large impact. Parallel.ForFJ(elems, bodiesOp); long start = System.currentTimeMillis(); Parallel.For(elems, bodiesOp); long stop = System.currentTimeMillis(); System.out.println("DELTA TIME VIA NORMAL PARALLEL FOR: " + (stop - start)); start = System.currentTimeMillis(); Parallel.ForFJ(elems, bodiesOp); stop = System.currentTimeMillis(); System.out.println("DELTA TIME VIA FOR FORK JOIN: " + (stop - start)); System.out.println("Finished"); } }
tantaman/commons
src/examples/java/com/tantaman/commons/examples/ParallelForDemo.java
Java
mit
2,605
<?php namespace Akamon\OAuth2\Server\Domain\Service\Token\TokenGranter; use Akamon\OAuth2\Server\Domain\Exception\OAuthError\GrantTypeNotFoundOAuthErrorException; use Akamon\OAuth2\Server\Domain\Exception\OAuthError\UnauthorizedClientForGrantTypeOAuthErrorException; use Akamon\OAuth2\Server\Domain\Exception\OAuthError\UnsupportedGrantTypeOAuthErrorException; use Akamon\OAuth2\Server\Domain\Service\Client\ClientObtainer\ClientObtainerInterface; use Akamon\OAuth2\Server\Domain\Service\Token\TokenGrantTypeProcessor\TokenGrantTypeProcessorInterface; use Symfony\Component\HttpFoundation\Request; use felpado as f; class TokenGranterByGrantType implements TokenGranterInterface { private $clientObtainer; private $processors = []; public function __construct(ClientObtainerInterface $clientObtainer, array $processors) { $this->clientObtainer = $clientObtainer; foreach ($processors as $name => $processor) { $this->addProcessor($name, $processor); } } private function addProcessor($name, TokenGrantTypeProcessorInterface $processor) { $this->processors[$name] = $processor; } public function grant(Request $request) { $client = $this->clientObtainer->getClient($request); $grantType = $this->getGrantTypeFromRequest($request); if (!$client->hasAllowedGrantType($grantType)) { throw new UnauthorizedClientForGrantTypeOAuthErrorException(); } $inputData = $this->getInputDataFromRequest($request); return $this->findProcessor($grantType)->process($client, $inputData); } private function getGrantTypeFromRequest(Request $request) { if (!$request->request->has('grant_type')) { throw new GrantTypeNotFoundOAuthErrorException(); } return $request->request->get('grant_type'); } /** * @return TokenGrantTypeProcessorInterface */ private function findProcessor($grantType) { if (f\contains($this->processors, $grantType)) { return f\get($this->processors, $grantType); } throw new UnsupportedGrantTypeOAuthErrorException(); } private function getInputDataFromRequest(Request $request) { return f\dissoc($request->request->all(), 'grant_type'); } }
Akamon/oauth2-server
src/Akamon/OAuth2/Server/Domain/Service/Token/TokenGranter/TokenGranterByGrantType.php
PHP
mit
2,338
package com.flockinger.spongeblogSP.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { ApiInfo apiInfo() { return new ApiInfoBuilder().title("SpongeblogSP API").description("Spongeblog blogging API") .license("").licenseUrl("http://unlicense.org").termsOfServiceUrl("").version("1.0.0") .build(); } @Bean public Docket customImplementation() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.flockinger.spongeblogSP.api.impl")).build() .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } }
daflockinger/spongeblogSP
src/main/java/com/flockinger/spongeblogSP/config/SwaggerConfig.java
Java
mit
1,216
import {keccak256, bufferToHex} from "ethereumjs-util" export default class MerkleTree { constructor(elements) { // Filter empty strings and hash elements this.elements = elements.filter(el => el).map(el => keccak256(el)) // Deduplicate elements this.elements = this.bufDedup(this.elements) // Sort elements this.elements.sort(Buffer.compare) // Create layers this.layers = this.getLayers(this.elements) } getLayers(elements) { if (elements.length === 0) { return [[""]] } const layers = [] layers.push(elements) // Get next layer until we reach the root while (layers[layers.length - 1].length > 1) { layers.push(this.getNextLayer(layers[layers.length - 1])) } return layers } getNextLayer(elements) { return elements.reduce((layer, el, idx, arr) => { if (idx % 2 === 0) { // Hash the current element with its pair element layer.push(this.combinedHash(el, arr[idx + 1])) } return layer }, []) } combinedHash(first, second) { if (!first) { return second } if (!second) { return first } return keccak256(this.sortAndConcat(first, second)) } getRoot() { return this.layers[this.layers.length - 1][0] } getHexRoot() { return bufferToHex(this.getRoot()) } getProof(el) { let idx = this.bufIndexOf(el, this.elements) if (idx === -1) { throw new Error("Element does not exist in Merkle tree") } return this.layers.reduce((proof, layer) => { const pairElement = this.getPairElement(idx, layer) if (pairElement) { proof.push(pairElement) } idx = Math.floor(idx / 2) return proof }, []) } getHexProof(el) { const proof = this.getProof(el) return this.bufArrToHexArr(proof) } getPairElement(idx, layer) { const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1 if (pairIdx < layer.length) { return layer[pairIdx] } else { return null } } bufIndexOf(el, arr) { let hash // Convert element to 32 byte hash if it is not one already if (el.length !== 32 || !Buffer.isBuffer(el)) { hash = keccak256(el) } else { hash = el } for (let i = 0; i < arr.length; i++) { if (hash.equals(arr[i])) { return i } } return -1 } bufDedup(elements) { return elements.filter((el, idx) => { return this.bufIndexOf(el, elements) === idx }) } bufArrToHexArr(arr) { if (arr.some(el => !Buffer.isBuffer(el))) { throw new Error("Array is not an array of buffers") } return arr.map(el => "0x" + el.toString("hex")) } sortAndConcat(...args) { return Buffer.concat([...args].sort(Buffer.compare)) } }
livepeer/protocol
utils/merkleTree.js
JavaScript
mit
3,202
// // peas.js // // tree data structure in javascript // ////////////////////////// var peas = function() { // "sub" here is used as an object container for // operations related to sub nodes. // Each pea node will have a "sub" property // with an instance of "sub" var sub = function() {} // the current node is accesable as "this.pea", from // methods in the "sub" object sub.prototype.pea = null // first and last sub sub.prototype.first = null sub.prototype.last = null // number of sub nodes sub.prototype.n = 0 // get subnode at index position (0 index) sub.prototype.at = function( index ) { var pik,i if( index > this.pea.sub.n - 1 ) return null pik = this.pea.sub.first for( i=0; i<index; i++ ) pik = pik.next return pik } // add spare node at last position // returns the added node sub.prototype.add = function( spare ) { if( this.pea.sub.last ) { spare.prev = this.pea.sub.last this.pea.sub.last.next = spare this.pea.sub.last = spare } else { spare.prev = null this.pea.sub.first = spare this.pea.sub.last = spare } spare.top = this.pea spare.next = null this.pea.sub.n++ return spare } // insert sub node at index position // returns the inserted node sub.prototype.insertAt = function( spare, index ) { var pik // validate index given if( index < 0 ) throw "node insert failed, invalid index" if( index > this.pea.sub.n ) throw "node insert failed, given index exceeds valid places" // if insert at last+1, then just add if( index == this.pea.sub.n ) { this.pea.add( spare ) return } pik = this.pea.sub.at( index ) spare.prev = pik.prev spare.next = pik // if not inserting at first if( pik.prev ) { pik.prev.next = spare } else { // inserting as first pik.top.sub.first = spare } pik.prev = spare spare.top = this.pea this.pea.sub.n++ return spare } // executes function "action" on each direct // sub node (not recursive) sub.prototype.each = function( action ) { var node = this.pea.sub.first while( node ) { action( node ) node = node.next } } /////////////////////////// // constructor function for pea nodes peas = function( item ) { this.sub = new sub() this.sub.pea = this this.item = item } peas.prototype.item = null // top node peas.prototype.top = null // prev peas.prototype.prev = null // next peas.prototype.next = null // namespace for sub nodes peas.prototype.sub = {} // find the root node, of the tree // of this node peas.prototype.root = function() { var node = this while ( node.top ) node = node.top } // executes function func on all the tree // nodes below (recursively) peas.prototype.onAllBelow = function( action ) { var node = this.sub.first while( node ) { action( node ) if( node.sub.n > 0 ) nodeMethods.each( action ) node = node.next } } // removes this node from tree, leaving // other tree nodes in consistent state peas.prototype.rip = function() { if( ! this.top ) return this if( this.next ) this.next.prev = this.prev if( this.prev ) this.prev.next = this.next if( this.top.sub.last == this ) this.top.sub.last = this.prev if( this.top.sub.first == this ) this.top.sub.first = this.next this.top.sub.n-- this.top = null this.next = null this.prev = null return this } // returns an array containing all nodes below this, in the tree peas.prototype.flat = function() { var flat = [] var grab = function( node ) { flat.push( node ) } root.onAllBelow( grab ) return flat } // puts spare node in the tree, // before of this node. // returns the inserted node peas.prototype.putBefore = function( spare ) { if( ! this.top ) throw "not in a tree" if ( this.prev ) this.prev.next = spare if( this.top.sub.first == this ) this.top.sub.first = spare spare.next = this spare.prev = this.prev this.prev = spare spare.top = this.top this.top.sub.n++ return spare } return peas }()
nzonbi/peas.js
peas.js
JavaScript
mit
4,109
using System; using System.Linq; using System.Reflection; using System.Text; namespace Stealer { public class Spy { public string StealFieldInfo(string className, params string[] fieldsNames) { var sb = new StringBuilder(); sb.AppendLine($"Class under investigation: {className}"); var type = typeof(Hacker); var classInstance = Activator.CreateInstance(type, new object[] { }); var fieldsInfo = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fieldsInfo.Where(fld => fieldsNames.Contains(fld.Name))) { sb.AppendLine($"{field.Name} = {field.GetValue(classInstance)}"); } return sb.ToString(); } } }
BlueDress/School
C# OOP Advanced/Reflection/Stealer/Spy.cs
C#
mit
857
from .. import Provider as CompanyProvider class Provider(CompanyProvider): formats = ( "{{last_name}} {{company_suffix}}", "{{last_name}} {{last_name}} {{company_suffix}}", "{{large_company}}", ) large_companies = ( "AZAL", "Azergold", "SOCAR", "Socar Polymer", "Global Export Fruits", "Baku Steel Company", "Azersun", "Sun Food", "Azərbaycan Şəkər İstehsalat Birliyi", "Azərsu", "Xəzər Dəniz Gəmiçiliyi", "Azərenerji", "Bakıelektrikşəbəkə", "Azəralüminium", "Bravo", "Azərpambıq Aqrar Sənaye Kompleksi", "CTS-Agro", "Azərtütün Aqrar Sənaye Kompleksi", "Azəripək", "Azfruittrade", "AF Holding", "Azinko Holding", "Gilan Holding", "Azpetrol", "Azərtexnolayn", "Bakı Gəmiqayırma Zavodu", "Gəncə Tekstil Fabriki", "Mətanət A", "İrşad Electronics", ) company_suffixes = ( "ASC", "QSC", "MMC", ) def large_company(self): """ :example: 'SOCAR' """ return self.random_element(self.large_companies)
joke2k/faker
faker/providers/company/az_AZ/__init__.py
Python
mit
1,274
import formatPhoneNumber, { formatPhoneNumberIntl } from './formatPhoneNumberDefaultMetadata' describe('formatPhoneNumberDefaultMetadata', () => { it('should format phone numbers', () => { formatPhoneNumber('+12133734253', 'NATIONAL').should.equal('(213) 373-4253') formatPhoneNumber('+12133734253', 'INTERNATIONAL').should.equal('+1 213 373 4253') formatPhoneNumberIntl('+12133734253').should.equal('+1 213 373 4253') }) })
halt-hammerzeit/react-phone-number-input
source/formatPhoneNumberDefaultMetadata.test.js
JavaScript
mit
433
import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import { green } from '@material-ui/core/colors'; import Radio, { RadioProps } from '@material-ui/core/Radio'; import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked'; import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonChecked'; const GreenRadio = withStyles({ root: { color: green[400], '&$checked': { color: green[600], }, }, checked: {}, })((props: RadioProps) => <Radio color="default" {...props} />); export default function RadioButtons() { const [selectedValue, setSelectedValue] = React.useState('a'); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setSelectedValue(event.target.value); }; return ( <div> <Radio checked={selectedValue === 'a'} onChange={handleChange} value="a" name="radio-button-demo" inputProps={{ 'aria-label': 'A' }} /> <Radio checked={selectedValue === 'b'} onChange={handleChange} value="b" name="radio-button-demo" inputProps={{ 'aria-label': 'B' }} /> <GreenRadio checked={selectedValue === 'c'} onChange={handleChange} value="c" name="radio-button-demo" inputProps={{ 'aria-label': 'C' }} /> <Radio checked={selectedValue === 'd'} onChange={handleChange} value="d" color="default" name="radio-button-demo" inputProps={{ 'aria-label': 'D' }} /> <Radio checked={selectedValue === 'e'} onChange={handleChange} value="e" color="default" name="radio-button-demo" inputProps={{ 'aria-label': 'E' }} icon={<RadioButtonUncheckedIcon fontSize="small" />} checkedIcon={<RadioButtonCheckedIcon fontSize="small" />} /> </div> ); }
kybarg/material-ui
docs/src/pages/components/radio-buttons/RadioButtons.tsx
TypeScript
mit
1,939
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 doriancoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "crypter.h" #include "ui_interface.h" #include "base58.h" using namespace std; ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey key; key.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); if (!AddKey(key)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return key.GetPubKey(); } bool CWallet::AddKey(const CKey& key) { if (!CCryptoKeyStore::AddKey(key)) return false; if (!fFileBacked) return true; if (!IsCrypted()) return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey()); return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); } return false; } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { if (!IsLocked()) return false; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a private-key-encrypted wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) wtx.nTimeReceived = GetAdjustedTime(); bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; #ifndef QT_GUI // If default receiving address gets used, replace it with a new one CScript scriptDefaultKey; scriptDefaultKey.SetDestination(vchDefaultKey.GetID()); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { CPubKey newDefaultKey; if (GetKeyFromPool(newDefaultKey, false)) { SetDefaultKey(newDefaultKey); SetAddressBookName(vchDefaultKey.GetID(), ""); } } } #endif // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } bool CWallet::EraseFromWallet(uint256 hash) { if (!fFileBacked) return false; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return true; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64 CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64 CWalletTx::GetTxTime() const { return nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived, list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const { nGeneratedImmature = nGeneratedMature = nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; if (IsCoinBase()) { if (GetBlocksToMaturity() > 0) nGeneratedImmature = pwallet->GetCredit(*this); else nGeneratedMature = GetCredit(); return; } // Compute fee: int64 nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64 nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { CTxDestination address; vector<unsigned char> vchPubKey; if (!ExtractDestination(txout.scriptPubKey, address)) { printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); } // Don't report 'change' txouts if (nDebit > 0 && pwallet->IsChange(txout)) continue; if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); if (pwallet->IsMine(txout)) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, int64& nSent, int64& nFee) const { nGenerated = nReceived = nSent = nFee = 0; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (strAccount == "") nGenerated = allGeneratedMature; if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (!fClient && txdb.ReadDiskTx(hash, tx)) { ; } else { printf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } int CWallet::ScanForWalletTransaction(const uint256& hashTx) { CTransaction tx; tx.ReadFromDisk(COutPoint(hashTx, 0)); if (AddToWalletIfInvolvingMe(tx, NULL, true, true)) return 1; return 0; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if (wtx.IsCoinBase() && wtx.IsSpent(0)) continue; CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Reaccept any txes of ours that aren't already in a block if (!wtx.IsCoinBase()) wtx.AcceptWalletTransaction(txdb, false); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do Reaccept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx); } } if (!IsCoinBase()) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str()); RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); } } } void CWalletTx::RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64 nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64 nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); // Rebroadcast any of our txes that aren't in a block yet printf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(txdb); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64 CWallet::GetBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsFinal() && pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetUnconfirmedBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetImmatureBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& pcoin = (*it).second; if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.GetDepthInMainChain() >= 2) nTotal += GetCredit(pcoin); } } return nTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const { vCoins.clear(); { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal()) continue; if (fOnlyConfirmed && !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; // If output is less than minimum value, then don't include transaction. // This is to help deal with dust spam clogging up create transactions. for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue) vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain())); } } } static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue, vector<char>& vfBest, int64& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64 nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { if (nPass == 0 ? rand() % 2 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; int64 nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; int64 n = pcoin->vout[i].nValue; pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; int64 nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } //// debug print printf("SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) printf("%s ", FormatMoney(vValue[i].first).c_str()); printf("total %s\n", FormatMoney(nBest).c_str()); } return true; } bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { vector<COutput> vCoins; AvailableCoins(vCoins); return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)); } bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = nTransactionFee; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn)) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } if (nChange > 0) { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address CScript scriptChange; scriptChange.SetDestination(vchPubKey.GetID()); // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000); bool fAllowFree = CTransaction::AllowFree(dPriority); int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { vector< pair<CScript, int64> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet); } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool()) { // This must not fail. The transaction has already been signed and recorded. printf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64 nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = _("Error: Transaction creation failed "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); } int CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return false; fFirstRunRet = false; int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } nLoadWalletRet = DB_NEED_REWRITE; } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); CreateThread(ThreadFlushWalletDB, &strWalletFile); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName) { std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address); mapAddressBook[address] = strName; NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBookName(const CTxDestination& address) { mapAddressBook.erase(address); NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } void CWallet::PrintWallet(const CBlock& block) { { LOCK(cs_wallet); if (mapWallet.count(block.vtx[0].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit()); } } printf("\n"); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) { if (!pwallet->fFileBacked) return false; strWalletFileOut = pwallet->strWalletFile; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64 nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64 nKeys = max(GetArg("-keypool", 100), (int64)0); for (int i = 0; i < nKeys; i++) { int64 nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool() { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL); while (setKeyPool.size() < (nTargetSize + 1)) { int64 nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); printf("keypool reserve %"PRI64d"\n", nIndex); } } int64 CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64 nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64 nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } printf("keypool keep %"PRI64d"\n", nIndex); } void CWallet::ReturnKey(int64 nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } printf("keypool return %"PRI64d"\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse) { int64 nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (fAllowReuse && vchDefaultKey.IsValid()) { result = vchDefaultKey; return true; } if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64 CWallet::GetOldestKeyPoolTime() { int64 nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } CPubKey CReserveKey::GetReservedKey() { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool."); vchPubKey = pwallet->vchDefaultKey; } } assert(vchPubKey.IsValid()); return vchPubKey; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } }
doriancoin/doriancoin-v3
src/wallet.cpp
C++
mit
52,573
<?php /* Safe sample input : get the field UserData from the variable $_POST sanitize : settype (float) construction : use of sprintf via a %u with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_POST['UserData']; if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; $query = sprintf("SELECT * FROM student where id='%u'", $tainted); $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_89/safe/CWE_89__POST__CAST-func_settype_float__select_from_where-sprintf_%u_simple_quote.php
PHP
mit
1,590
var final_transcript = ''; var recognizing = false; //var socket = io.connect('http://collab.di.uniba.it:48922');//"http://collab.di.uniba.it/~iaffaldano:48922" //socket.emit('client_type', {text: "Speaker"}); if ('webkitSpeechRecognition' in window) { var recognition = new webkitSpeechRecognition(); recognition.continuous = true; recognition.interimResults = true; console.log("MAX ALTERNATIVES = "+ recognition.maxAlternatives); recognition.onstart = function () { recognizing = true; console.log("RECOGNITION STARTED"); }; recognition.onerror = function (event) { console.log("RECOGNITION ERROR: " + event.error); recognition.start(); }; recognition.onend = function () { console.log("RECOGNITION STOPPED"); if(recognizing){ recognition.start(); console.log("RECOGNITION RESTARTED"); } }; recognition.onresult = function (event) { var interim_transcript = ''; for (var i = event.resultIndex; i < event.results.length; ++i) { if (event.results[i].isFinal) { final_transcript += event.results[i][0].transcript; console.log("CONFIDENCE (" + event.results[i][0].transcript + ") = " + event.results[i][0].confidence); //recognition.stop(); //recognition.start(); socket.emit('client_message', {text: event.results[i][0].transcript}); } else { interim_transcript += event.results[i][0].transcript; } } final_transcript = capitalize(final_transcript); final_span.innerHTML = linebreak(final_transcript); interim_span.innerHTML = linebreak(interim_transcript); }; recognition.onaudiostart= function (event) { console.log("AUDIO START"); }; recognition.onsoundstart= function (event) { console.log("SOUND START"); }; recognition.onspeechstart= function (event) { console.log("SPEECH START"); }; recognition.onspeechend= function (event) { console.log("SPEECH END"); }; recognition.onsoundend= function (event) { console.log("SOUND END"); }; recognition.onnomatch= function (event) { console.log("NO MATCH"); }; } var two_line = /\n\n/g; var one_line = /\n/g; function linebreak(s) { return s.replace(two_line, '<p></p>').replace(one_line, '<br>'); } function capitalize(s) { return s.replace(s.substr(0, 1), function (m) { return m.toUpperCase(); }); } function startDictation(event) { if (recognizing) { recognition.stop(); recognizing=false; start_button.innerHTML = "START" return; } final_transcript = ''; recognition.lang = 'it-IT'; recognition.start(); start_button.innerHTML = "STOP" final_span.innerHTML = ''; interim_span.innerHTML = ''; }
collab-uniba/scriba
client/src/js/transcriptor.js
JavaScript
mit
2,613
/* eslint-disable promise/always-return */ import { runAuthenticatedQuery, runQuery } from "schema/v1/test/utils" describe("UpdateCollectorProfile", () => { it("updates and returns a collector profile", () => { /* eslint-disable max-len */ const mutation = ` mutation { updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art", intents: [BUY_ART_AND_DESIGN] }) { id name email self_reported_purchases intents } } ` /* eslint-enable max-len */ const context = { updateCollectorProfileLoader: () => Promise.resolve({ id: "3", name: "Percy", email: "percy@cat.com", self_reported_purchases: "treats", intents: ["buy art & design"], }), } const expectedProfileData = { id: "3", name: "Percy", email: "percy@cat.com", self_reported_purchases: "treats", intents: ["buy art & design"], } expect.assertions(1) return runAuthenticatedQuery(mutation, context).then( ({ updateCollectorProfile }) => { expect(updateCollectorProfile).toEqual(expectedProfileData) } ) }) it("throws error when data loader is missing", () => { /* eslint-disable max-len */ const mutation = ` mutation { updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art" }) { id name email self_reported_purchases intents } } ` /* eslint-enable max-len */ const errorResponse = "Missing Update Collector Profile Loader. Check your access token." expect.assertions(1) return runQuery(mutation) .then(() => { throw new Error("An error was not thrown but was expected.") }) .catch(error => { expect(error.message).toEqual(errorResponse) }) }) })
mzikherman/metaphysics-1
src/schema/v1/me/__tests__/update_collector_profile.test.js
JavaScript
mit
2,055
module.exports = require('./src/tracking');
JoshuaTang/jstracking
index.js
JavaScript
mit
44
/** * Created by Administrator on 2017/3/11. */ public class ReverseWordsInSequence { public void reverseSequence(String str) { if (str == null) return; String[] strArray = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i = strArray.length-1; i >= 0; --i) sb.append(strArray[i] + " "); System.out.println(sb); } public static void main(String[] args) { ReverseWordsInSequence r = new ReverseWordsInSequence(); String str = "I am a Students."; r.reverseSequence(str); } } /** * Created by Administrator on 2017/3/11. */ public class ReverseWordsInSequence { public String reverseSequence(String str) { if (str == null || str.length() <= 1) return str; StringBuilder sb = new StringBuilder(str); reverse(sb, 0, str.length() - 1); int begin = 0, end = 0; while (end < str.length()) { while (end < str.length() && sb.charAt(end) != ' ') end++; reverse(sb, begin, end - 1); begin = end + 1; end = begin; } return sb.toString(); } public void reverse(StringBuilder sb, int start, int end) { if (sb == null || end <= start) return; while (start < end) { char temp = sb.charAt(start); sb.setCharAt(start, sb.charAt(end)); sb.setCharAt(end, temp); start++; end--; } } public static void main(String[] args) { ReverseWordsInSequence r = new ReverseWordsInSequence(); String str = "i am a students."; System.out.print(r.reverseSequence(str)); } }
RudyZH/Aim2Offer
042_ReverseWordsInSequence.java
Java
mit
1,796
<?php class Autoreportemail_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_milist($where = array()) { $this->db->select('*'); $this->db->where($where); $query = $this->db->get('autoreport_email'); return $query->result_array(); } public function add_milist($data = array()) { $empty = $this->get_milist(array('email' => $data['email'], 'client' => $data['client'])); if(empty($empty)){ $data['user_c'] = $this->session->userdata('logged_in_data')['id']; $this->db->insert('autoreport_email',$data); if( $this->db->affected_rows() > 0) { return $this->db->insert_id(); } }else{ return false; } } public function edit_milist($data = array()) { $empty = $this->get_milist(array('email' => $data['email'], 'id !=' => $data['id'], 'client' => $data['client'])); if(empty($empty)){ $id = $data['id']; unset($data['id']); $this->db->where('id', $id); $this->db->update('autoreport_email', $data); return $this->db->affected_rows(); }else{ return false; } } public function update_milist($id,$data = array()) { $nempty = $this->get_milist(array('id' => $id)); if(!empty($nempty)){ $this->db->where('id', $id); $this->db->update('autoreport_email', $data); return TRUE; }else{ return false; } } public function remove_milist($id) { $data['status'] = 'inactive'; $this->db->where('id',$id); $this->db->update('phases',$data); if( $this->db->affected_rows() > 0) { return $this->db->affected_rows(); } return ; } public function reactivate_milist($id) { $data['status'] = 'active'; $this->db->where('id',$id); $this->db->update('phases',$data); if( $this->db->affected_rows() > 0) { return $this->db->affected_rows(); } return ; } }
garpepi/Mini-HRM
application/models/Autoreportemail_model.php
PHP
mit
2,189
/* Configures webpack to build only assets required for integration environments. */ const webpack = require('webpack'); const merge = require('webpack-merge'); const { source, sourceAll } = require('../lib/path-helpers'); const ciBuildWorkflow = require('./workflow/build.ci'); const { entries } = require(source('fc-config')); // eslint-disable-line // remove the styleguide dll references const modify = (config) => { config.plugins = config.plugins.slice(1); return config; }; module.exports = modify(merge(ciBuildWorkflow, { entry: sourceAll(entries.ci), plugins: [ new webpack.DefinePlugin({ 'process.env.CI_MODE': true }) ] }));
connectivedx/fuzzy-chainsaw
build/webpack/webpack.config.build.ci.js
JavaScript
mit
671
/** * A null-safe function to repeat the source string the desired amount of times. * @private * @param {String} source * @param {Number} times * @returns {String} */ function _repeat (source, times) { var result = ""; for (var i = 0; i < times; i++) { result += source; } return result; } export default _repeat;
ascartabelli/lamb
src/privates/_repeat.js
JavaScript
mit
347
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Handles backports of the standard library's `fractions.py`. The fractions module in 2.6 does not handle being instantiated using a float and then calculating an approximate fraction based on that. This functionality is required by the FITS unit format generator, since the FITS unit format handles only rational, not decimal point, powers. """ from __future__ import absolute_import import sys if sys.version_info[:2] == (2, 6): from ._fractions_py2 import * else: from fractions import *
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/utils/compat/fractions.py
Python
mit
568
/* eslint-disable func-names */ const { sampleUrls, shortSampleUrls, E2E_WAIT_TIME: WAIT_TIME, E2E_PRESENT_WAIT_TIME: PRESENT_WAIT_TIME } = require('../e2e_helper'); module.exports = { after(browser) { browser.end(); }, 'Go to top page': browser => { browser.page.index().navigate().waitForElementVisible('body', PRESENT_WAIT_TIME); }, 'Add musics': browser => { browser.page .index() .log('add musics') .setValue('@trackUrlField', sampleUrls.join(',')) .submitForm('@trackSubmitButton') .waitForElementPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME) .assert.elementPresent('@playButton') .assert.hasPlaylistLength(5) .api.pause(WAIT_TIME); }, 'Play music': browser => { browser.page .index() .moveToElement('@playerBlock', 10, 10) .click('@playButton') .waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME) .assert.elementPresent('@pauseButton') .assert.hasPlaylistLength(5) .assert.currentTrackNumEquals(1) .assert.currentTitleEquals(1) .api.pause(WAIT_TIME); }, 'Play next music': browser => { browser.page .index() .click('@nextButton') .waitForElementNotPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME) // dequeue .assert.elementPresent('@pauseButton') .assert.hasPlaylistLength(4) .assert.currentTrackNumEquals(1) .assert.currentTitleEquals(1) .api.pause(WAIT_TIME); }, 'Has play prev music button?': browser => { browser.page.index().assert.cssClassPresent('@prevButton', 'deactivate'); }, 'Stop music': browser => { browser.page .index() .click('@pauseButton') .waitForElementPresent('@playButton', PRESENT_WAIT_TIME) .assert.elementPresent('@playButton') .assert.hasPlaylistLength(4) .assert.currentTrackNumEquals(1) .assert.title('jukebox') .api.pause(WAIT_TIME); }, 'Play specified music': browser => { browser.page .index() .click('a.playlist-content:nth-child(3)') .waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME) .assert.elementPresent('@pauseButton') .assert.hasPlaylistLength(4) .assert.currentTrackNumEquals(3) .assert.currentTitleEquals(3) .api.pause(WAIT_TIME); }, 'Delete current music': browser => { browser.page .index() .click('a.playlist-content:nth-child(3) i[title=Delete]') .waitForElementPresent('@playButton', PRESENT_WAIT_TIME) .assert.elementPresent('@playButton') .assert.hasPlaylistLength(3) .assert.currentTrackNumEquals(3) .assert.title('jukebox') .api.pause(WAIT_TIME); }, 'Add short music': browser => { browser.page .index() .setValue('@trackUrlField', shortSampleUrls[0]) .submitForm('@trackSubmitButton') .waitForElementPresent('a.playlist-content:nth-child(4)', PRESENT_WAIT_TIME) .assert.hasPlaylistLength(4); }, 'Play short music': browser => { browser.page .index() .click('a.playlist-content:nth-child(4)') .waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME); }, 'Wait till end': browser => { browser.page .index() .waitForElementNotPresent( '.playlist-content:nth-child(4) .thumbnail-wrapper i', PRESENT_WAIT_TIME ) .assert.elementPresent('@playButton') .assert.hasPlaylistLength(3); }, 'Clear playlist': browser => { browser.page .index() .click('@openClearModalButton') .waitForElementPresent('@clearModal', PRESENT_WAIT_TIME) .click('@clearButton') .waitForElementNotPresent('a.playlist-content', PRESENT_WAIT_TIME) .assert.hasPlaylistLength(0) .api.pause(WAIT_TIME); } };
unblee/jukebox
e2e/tests/index_test.js
JavaScript
mit
3,824
/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.7 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.7 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.7' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector === '#' ? [] : selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.7 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.7' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d).prop(d, true) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d).prop(d, false) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault() // The target component still receive the focus if ($btn.is('input,button')) $btn.trigger('focus') else $btn.find('input:visible,button:visible').first().trigger('focus') } }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.7 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.7' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.7 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ /* jshint latedef: false */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.7' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.7 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.7' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.7 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.7' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function () { that.$element.one('mouseup.dismiss.bs.modal', function (e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (document !== e.target && this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { this.adjustDialog() } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.7 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.7' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = { click: false, hover: false, focus: false } if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function () { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary. that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) } callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var isSvg = window.SVGElement && el instanceof window.SVGElement // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3. // See https://github.com/twbs/bootstrap/issues/20280 var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset()) var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null that.$element = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.7 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.7' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.7 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.7' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.7 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.7' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.7 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.7' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); $(function () { $('.button-checkbox').each(function () { // Settings var $widget = $(this), $button = $widget.find('button'), $checkbox = $widget.find('input:checkbox'), color = $button.data('color'), settings = { on: { icon: 'glyphicon glyphicon-check' }, off: { icon: 'fa fa-square-o' } }; // Event Handlers $button.on('click', function () { $checkbox.prop('checked', !$checkbox.is(':checked')); $checkbox.triggerHandler('change'); updateDisplay(); }); $checkbox.on('change', function () { updateDisplay(); }); // Actions function updateDisplay() { var isChecked = $checkbox.is(':checked'); // Set the button's state $button.data('state', (isChecked) ? "on" : "off"); // Set the button's icon $button.find('.state-icon') .removeClass() .addClass('state-icon ' + settings[$button.data('state')].icon); // Update the button's color if (isChecked) { $button .removeClass('btn-default') .addClass('btn-' + color + ' active'); } else { $button .removeClass('btn-' + color + ' active') .addClass('btn-default'); } } // Initialization function init() { updateDisplay(); // Inject the icon if applicable if ($button.find('.state-icon').length == 0) { $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> '); } } init(); }); });
austinxiao-ucsd/cogs120-webapp
js/bootstrap.js
JavaScript
mit
71,641
<?php /** * @package AcyMailing for Joomla! * @version 5.6.5 * @author acyba.com * @copyright (C) 2009-2017 ACYBA S.A.R.L. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php $name = 'Technology'; $thumb = 'media/com_acymailing/templates/technology_resp/thumb.jpg'; $body = JFile::read(dirname(__FILE__).DS.'index.html'); $styles['tag_h1'] = 'font-size:20px; margin:0px; margin-bottom:15px; padding:0px; font-weight:bold; color:#01bbe5 !important;'; $styles['tag_h2'] = 'font-size:12px; font-weight:bold; color:#565656 !important; text-transform:uppercase; margin:10px 0px; padding:0px; padding-bottom:5px; border-bottom:1px solid #ddd;'; $styles['tag_h3'] = 'color:#565656 !important; font-weight:bold; font-size:12px; margin:0px; margin-bottom:10px; padding:0px;'; $styles['tag_h4'] = ''; $styles['color_bg'] = '#575757'; $styles['tag_a'] = 'cursor:pointer;color:#01bbe5;text-decoration:none;border:none;'; $styles['acymailing_online'] = 'color:#d2d1d1; cursor:pointer;'; $styles['acymailing_unsub'] = 'color:#d2d1d1; cursor:pointer;'; $styles['acymailing_readmore'] = 'cursor:pointer; font-weight:bold; color:#fff; background-color:#01bbe5; padding:2px 5px;'; $stylesheet = 'table, div, p, td { font-family:Arial, Helvetica, sans-serif; font-size:12px; } p{margin:0px; padding:0px} .special h2{font-size:18px; margin:0px; margin-bottom:15px; padding:0px; font-weight:bold; color:#01bbe5 !important; text-transform:none; border:none} .links a{color:#ababab} @media (min-width:10px){ .w600 { width:320px !important;} .w540 { width:260px !important;} .w30 { width:30px !important;} .w600 img {max-width:320px; height:auto !important} .w540 img {max-width:260px; height:auto !important} } @media (min-width: 480px){ .w600 { width:480px !important;} .w540 { width:420px !important;} .w30 { width:30px !important;} .w600 img {max-width:480px; height:auto !important} .w540 img {max-width:420px; height:auto !important} } @media (min-width:600px){ .w600 { width:600px !important;} .w540 { width:540px !important;} .w30 { width:30px !important;} .w600 img {max-width:600px; height:auto !important} .w540 img {max-width:540px; height:auto !important} } ';
yaelduckwen/libriastore
joomla/media/com_acymailing/templates/technology_resp/install.php
PHP
mit
2,281
<?php namespace EntityManager5178714d05176_546a8d27f194334ee012bfe64f629947b07e4919\__CG__\Doctrine\ORM; /** * CG library enhanced proxy class. * * This code was generated automatically by the CG library, manual changes to it * will be lost upon next generation. */ class EntityManager extends \Doctrine\ORM\EntityManager { private $delegate; private $container; /** * Executes a function in a transaction. * * The function gets passed this EntityManager instance as an (optional) parameter. * * {@link flush} is invoked prior to transaction commit. * * If an exception occurs during execution of the function or flushing or transaction commit, * the transaction is rolled back, the EntityManager closed and the exception re-thrown. * * @param callable $func The function to execute transactionally. * @return mixed Returns the non-empty value returned from the closure or true instead */ public function transactional($func) { return $this->delegate->transactional($func); } /** * Performs a rollback on the underlying database connection. */ public function rollback() { return $this->delegate->rollback(); } /** * Removes an entity instance. * * A removed entity will be removed from the database at or before transaction commit * or as a result of the flush operation. * * @param object $entity The entity instance to remove. */ public function remove($entity) { return $this->delegate->remove($entity); } /** * Refreshes the persistent state of an entity from the database, * overriding any local changes that have not yet been persisted. * * @param object $entity The entity to refresh. */ public function refresh($entity) { return $this->delegate->refresh($entity); } /** * Tells the EntityManager to make an instance managed and persistent. * * The entity will be entered into the database at or before transaction * commit or as a result of the flush operation. * * NOTE: The persist operation always considers entities that are not yet known to * this EntityManager as NEW. Do not pass detached entities to the persist operation. * * @param object $object The instance to make managed and persistent. */ public function persist($entity) { return $this->delegate->persist($entity); } /** * Create a new instance for the given hydration mode. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function newHydrator($hydrationMode) { return $this->delegate->newHydrator($hydrationMode); } /** * Merges the state of a detached entity into the persistence context * of this EntityManager and returns the managed copy of the entity. * The entity passed to merge will not become associated/managed with this EntityManager. * * @param object $entity The detached entity to merge into the persistence context. * @return object The managed copy of the entity. */ public function merge($entity) { return $this->delegate->merge($entity); } /** * Acquire a lock on the given entity. * * @param object $entity * @param int $lockMode * @param int $lockVersion * @throws OptimisticLockException * @throws PessimisticLockException */ public function lock($entity, $lockMode, $lockVersion = NULL) { return $this->delegate->lock($entity, $lockMode, $lockVersion); } /** * Check if the Entity manager is open or closed. * * @return bool */ public function isOpen() { return $this->delegate->isOpen(); } /** * Checks whether the state of the filter collection is clean. * * @return boolean True, if the filter collection is clean. */ public function isFiltersStateClean() { return $this->delegate->isFiltersStateClean(); } /** * Helper method to initialize a lazy loading proxy or persistent collection. * * This method is a no-op for other objects * * @param object $obj */ public function initializeObject($obj) { return $this->delegate->initializeObject($obj); } /** * Checks whether the Entity Manager has filters. * * @return True, if the EM has a filter collection. */ public function hasFilters() { return $this->delegate->hasFilters(); } /** * Gets the UnitOfWork used by the EntityManager to coordinate operations. * * @return \Doctrine\ORM\UnitOfWork */ public function getUnitOfWork() { return $this->delegate->getUnitOfWork(); } /** * Gets the repository for an entity class. * * @param string $entityName The name of the entity. * @return EntityRepository The repository class. */ public function getRepository($className) { $repository = $this->delegate->getRepository($className); if ($repository instanceof \Symfony\Component\DependencyInjection\ContainerAwareInterface) { $repository->setContainer($this->container); return $repository; } if (null !== $metadata = $this->container->get("jms_di_extra.metadata.metadata_factory")->getMetadataForClass(get_class($repository))) { foreach ($metadata->classMetadata as $classMetadata) { foreach ($classMetadata->methodCalls as $call) { list($method, $arguments) = $call; call_user_func_array(array($repository, $method), $this->prepareArguments($arguments)); } } } return $repository; } /** * Gets a reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * @param string $entityName The name of the entity type. * @param mixed $id The entity identifier. * @return object The entity reference. */ public function getReference($entityName, $id) { return $this->delegate->getReference($entityName, $id); } /** * Gets the proxy factory used by the EntityManager to create entity proxies. * * @return ProxyFactory */ public function getProxyFactory() { return $this->delegate->getProxyFactory(); } /** * Gets a partial reference to the entity identified by the given type and identifier * without actually loading it, if the entity is not yet loaded. * * The returned reference may be a partial object if the entity is not yet loaded/managed. * If it is a partial object it will not initialize the rest of the entity state on access. * Thus you can only ever safely access the identifier of an entity obtained through * this method. * * The use-cases for partial references involve maintaining bidirectional associations * without loading one side of the association or to update an entity without loading it. * Note, however, that in the latter case the original (persistent) entity data will * never be visible to the application (especially not event listeners) as it will * never be loaded in the first place. * * @param string $entityName The name of the entity type. * @param mixed $identifier The entity identifier. * @return object The (partial) entity reference. */ public function getPartialReference($entityName, $identifier) { return $this->delegate->getPartialReference($entityName, $identifier); } /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\ORM\Mapping\ClassMetadataFactory */ public function getMetadataFactory() { return $this->delegate->getMetadataFactory(); } /** * Gets a hydrator for the given hydration mode. * * This method caches the hydrator instances which is used for all queries that don't * selectively iterate over the result. * * @param int $hydrationMode * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ public function getHydrator($hydrationMode) { return $this->delegate->getHydrator($hydrationMode); } /** * Gets the enabled filters. * * @return FilterCollection The active filter collection. */ public function getFilters() { return $this->delegate->getFilters(); } /** * Gets an ExpressionBuilder used for object-oriented construction of query expressions. * * Example: * * <code> * $qb = $em->createQueryBuilder(); * $expr = $em->getExpressionBuilder(); * $qb->select('u')->from('User', 'u') * ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2))); * </code> * * @return \Doctrine\ORM\Query\Expr */ public function getExpressionBuilder() { return $this->delegate->getExpressionBuilder(); } /** * Gets the EventManager used by the EntityManager. * * @return \Doctrine\Common\EventManager */ public function getEventManager() { return $this->delegate->getEventManager(); } /** * Gets the database connection object used by the EntityManager. * * @return \Doctrine\DBAL\Connection */ public function getConnection() { return $this->delegate->getConnection(); } /** * Gets the Configuration used by the EntityManager. * * @return \Doctrine\ORM\Configuration */ public function getConfiguration() { return $this->delegate->getConfiguration(); } /** * Returns the ORM metadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)) or an aliased class name. * * Examples: * MyProject\Domain\User * sales:PriceRequest * * @return \Doctrine\ORM\Mapping\ClassMetadata * @internal Performance-sensitive method. */ public function getClassMetadata($className) { return $this->delegate->getClassMetadata($className); } /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the * database. * * If an entity is explicitly passed to this method only this entity and * the cascade-persist semantics + scheduled inserts/removals are synchronized. * * @param object $entity * @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. */ public function flush($entity = NULL) { return $this->delegate->flush($entity); } /** * Finds an Entity by its identifier. * * @param string $entityName * @param mixed $id * @param integer $lockMode * @param integer $lockVersion * * @return object */ public function find($entityName, $id, $lockMode = 0, $lockVersion = NULL) { return $this->delegate->find($entityName, $id, $lockMode, $lockVersion); } /** * Detaches an entity from the EntityManager, causing a managed entity to * become detached. Unflushed changes made to the entity if any * (including removal of the entity), will not be synchronized to the database. * Entities which previously referenced the detached entity will continue to * reference it. * * @param object $entity The entity to detach. */ public function detach($entity) { return $this->delegate->detach($entity); } /** * Create a QueryBuilder instance * * @return QueryBuilder $qb */ public function createQueryBuilder() { return $this->delegate->createQueryBuilder(); } /** * Creates a new Query object. * * @param string $dql The DQL string. * @return \Doctrine\ORM\Query */ public function createQuery($dql = '') { return $this->delegate->createQuery($dql); } /** * Creates a native SQL query. * * @param string $sql * @param ResultSetMapping $rsm The ResultSetMapping to use. * @return NativeQuery */ public function createNativeQuery($sql, \Doctrine\ORM\Query\ResultSetMapping $rsm) { return $this->delegate->createNativeQuery($sql, $rsm); } /** * Creates a Query from a named query. * * @param string $name * @return \Doctrine\ORM\Query */ public function createNamedQuery($name) { return $this->delegate->createNamedQuery($name); } /** * Creates a NativeQuery from a named native query. * * @param string $name * @return \Doctrine\ORM\NativeQuery */ public function createNamedNativeQuery($name) { return $this->delegate->createNamedNativeQuery($name); } /** * Creates a copy of the given entity. Can create a shallow or a deep copy. * * @param object $entity The entity to copy. * @return object The new entity. * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e: * Fatal error: Maximum function nesting level of '100' reached, aborting! */ public function copy($entity, $deep = false) { return $this->delegate->copy($entity, $deep); } /** * Determines whether an entity instance is managed in this EntityManager. * * @param object $entity * @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise. */ public function contains($entity) { return $this->delegate->contains($entity); } /** * Commits a transaction on the underlying database connection. */ public function commit() { return $this->delegate->commit(); } /** * Closes the EntityManager. All entities that are currently managed * by this EntityManager become detached. The EntityManager may no longer * be used after it is closed. */ public function close() { return $this->delegate->close(); } /** * Clears the EntityManager. All entities that are currently managed * by this EntityManager become detached. * * @param string $entityName if given, only entities of this type will get detached */ public function clear($entityName = NULL) { return $this->delegate->clear($entityName); } /** * Starts a transaction on the underlying database connection. */ public function beginTransaction() { return $this->delegate->beginTransaction(); } public function __construct($objectManager, \Symfony\Component\DependencyInjection\ContainerInterface $container) { $this->delegate = $objectManager; $this->container = $container; } private function prepareArguments(array $arguments) { $processed = array(); foreach ($arguments as $arg) { if ($arg instanceof \Symfony\Component\DependencyInjection\Reference) { $processed[] = $this->container->get((string) $arg, $arg->getInvalidBehavior()); } else if ($arg instanceof \Symfony\Component\DependencyInjection\Parameter) { $processed[] = $this->container->getParameter((string) $arg); } else { $processed[] = $arg; } } return $processed; } }
deivy90/Detoditoonline
app/cache/dev/jms_diextra/doctrine/EntityManager_5178714d05176.php
PHP
mit
16,022
# -*- coding: utf-8 -*- import os.path from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return "%s: %s" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension("No file extension found in filename. That's not okay!") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension("The following filename is illegal: %s. Extension has to be one of %s" % (filename, ", ".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(".")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension("File extension has to be '%s', not '%s'." % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return "%s: %s (r%d)" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision)
indexofire/gork
src/gork/application/know/plugins/attachments/models.py
Python
mit
6,582
package h1z1.screens; import h1z1.MainFrame; import h1z1.game.GameState; import h1z1.input.ButtonHandler; import h1z1.input.InputButton; import h1z1.input.InputProvider; import h1z1.io.ResourceManager; import javax.imageio.ImageIO; import java.awt.*; import java.util.List; import h1z1.game.Maze; public class PlayGameScreenManager extends ScreenManager { private Maze maze = new Maze(); public PlayGameScreenManager(MainFrame mainFrame) throws Exception { super(mainFrame); } @Override public void update(List<InputProvider> inputs) { } @Override public void paint(Frame frame, Graphics2D graphics) { for(int x = 0; x < Maze.WIDTH; x++){ for(int y = 0; y < Maze.HEIGHT; y++) { boolean value = maze.getValue(x, y); if (value) {graphics.setColor(Color.RED);} else{ graphics.setColor(Color.WHITE); } graphics.fillRect(Maze.OFFSET + Maze.SIZE * x, Maze.OFFSET + Maze.SIZE * y, Maze.SIZE, Maze.SIZE); } } } }
johnathandavis/H1Z1
src/main/java/h1z1/screens/PlayGameScreenManager.java
Java
mit
1,193
import express from 'express' import cors from 'cors' import bodyParser from 'body-parser' import helmet from 'helmet' import httpStatus from 'http-status' import path from 'path' import routes from './routes' import logger from './helpers/logger.js' const app = express() // Pug app.set('view engine', 'pug') app.set('views', path.join(__dirname, 'views')) // Helmet helps you secure your Express apps by setting various HTTP headers. app.use(helmet()) // Enable CORS app.use(cors()) // To use with Nginx // app.enable('trust proxy') // Parse incoming request bodies in a middleware before your handlers, available under the req.body property. app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) // API Routes app.use('/', routes) // Catch 404 app.get('*', (req, res) => { res.status(404).send({ message: 'Not found' }) }) // Error log app.use((err, req, res, next) => { logger.log(err.level || 'error', err.message) next(err) }) // Error handler app.use((err, req, res, next) => { res.status(err.status || 500).send({ status: err.status || 500, message: err.status ? err.message : httpStatus[500], }) }) export default app
AitorDB/API-NodeJS
app/app.js
JavaScript
mit
1,199
<?php namespace PandaGroup\StoreLocator\Controller\Adminhtml\Index; use Magento\Framework\Exception\LocalizedException; class Save extends \Magento\Backend\App\Action { /** @var \Magento\Framework\App\Request\DataPersistorInterface */ protected $dataPersistor; /** @var \PandaGroup\StoreLocator\Model\RegionsData */ protected $regionsData; /** @var \PandaGroup\StoreLocator\Model\States */ protected $states; /** @var \PandaGroup\StoreLocator\Model\StatesFactory */ protected $statesFactory; /** @var \PandaGroup\StoreLocator\Logger\Logger */ protected $logger; public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor, \PandaGroup\StoreLocator\Model\RegionsData $regionsData, \PandaGroup\StoreLocator\Model\States $states, \PandaGroup\StoreLocator\Model\StatesFactory $statesFactory, \PandaGroup\StoreLocator\Logger\Logger $logger ) { $this->dataPersistor = $dataPersistor; $this->regionsData = $regionsData; $this->states = $states; $this->statesFactory = $statesFactory; $this->logger = $logger; parent::__construct($context); } public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $data = $this->getRequest()->getPostValue(); if ($data) { $this->logger->info('Start saving new store/edit exist store.'); $id = (int) $this->getRequest()->getParam('id'); $stateIdFromStatesDataSource = $this->getRequest()->getPostValue('state_source_id'); $nameFromStatesDataSource = $this->regionsData->load($stateIdFromStatesDataSource)->getData('name'); if (true === empty($nameFromStatesDataSource)) { // Empty names of countries states which aren't any states $nameFromStatesDataSource = $data['country']; } $newStateIdFromStoreLocatorStates = $this->states->addNewRegion( $stateIdFromStatesDataSource, $nameFromStatesDataSource, '', $data['country'] ); $data['state_id'] = $newStateIdFromStoreLocatorStates; /** @var \PandaGroup\StoreLocator\Model\StoreLocator $model */ $model = $this->_objectManager->create('PandaGroup\StoreLocator\Model\StoreLocator')->load($id); if (!$model->getId() && $id) { $this->messageManager->addErrorMessage(__('This store no longer exists.')); return $resultRedirect->setPath('*/*/'); } if ($data['storelocator_id'] === '') { $data['storelocator_id'] = null; // Bug with saving new store } $data['rewrite_request_path'] = $this->toSafeUrl($data['name']); $data['state'] = null; $data['link'] = null; if (true === empty($data['fax'])) { $data['fax'] = null; } if (true === empty($data['image_icon'])) { $data['image_icon'] = null; } $data['monday_open_break'] = $data['monday_open']; $data['monday_close_break'] = $data['monday_open']; $data['tuesday_open_break'] = $data['tuesday_open']; $data['tuesday_close_break'] = $data['tuesday_open']; $data['wednesday_open_break'] = $data['wednesday_open']; $data['wednesday_close_break'] = $data['wednesday_open']; $data['thursday_open_break'] = $data['thursday_open']; $data['thursday_close_break'] = $data['thursday_open']; $data['friday_open_break'] = $data['friday_open']; $data['friday_close_break'] = $data['friday_open']; $data['saturday_open_break'] = $data['saturday_open']; $data['saturday_close_break'] = $data['saturday_open']; $data['sunday_open_break'] = $data['sunday_open']; $data['sunday_close_break'] = $data['sunday_open']; $model->setData($data); try { $model->getResource()->save($model); $this->messageManager->addSuccessMessage(__('You saved the store.')); $this->logger->info(' Saving new store/edit exist store was successful.'); $this->dataPersistor->clear('storelocator'); if ($this->getRequest()->getParam('back')) { $this->logger->info('Finish saving new store/edit exist store.'); return $resultRedirect->setPath('*/*/edit', ['id' => $model->getId()]); } $this->logger->info('Finish saving new store/edit exist store.'); return $resultRedirect->setPath('*/*/'); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); $this->logger->error(' Error while saving new store/edit exist store.', $e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the store.')); $this->logger->error(' Error while saving new store/edit exist store.', $e->getMessage()); } $this->dataPersistor->set('storelocator', $data); $this->logger->info('Finish saving new store/edit exist store.'); return $resultRedirect->setPath('*/*/edit', ['storelocator_id' => $this->getRequest()->getParam('storelocator_id')]); } return $resultRedirect->setPath('*/*/'); } /** * @param $str * @param array $replace * @param string $delimiter * @return mixed|string */ protected function toSafeUrl($str, $replace=array(), $delimiter='-') { $baseStr = $str; if( !empty($replace) ) { $str = str_replace((array)$replace, ' ', $str); } $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str); $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean); $clean = strtolower(trim($clean, '-')); $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean); $this->logger->info(' Store Name was replaced by safe url link: '.$baseStr.'->'.$clean); return $clean; } }
pandagrouppl/StoreLocator
Controller/Adminhtml/Index/Save.php
PHP
mit
6,561
using TwinTechs.Controls; using TekConf.Core.Data.Dtos; namespace TekConf.Forms.Cells { public partial class ConferenceListSessionsListCell : FastCell { protected override void InitializeCell () { InitializeComponent (); } protected override void SetupCell (bool isRecycled) { var session = BindingContext as SessionDto; if (session != null) { // logoImage.ImageUrl = conference.ImageUrl ?? ""; title.Text = session.Title; date.Text = session.Date; } } } }
tekconf/TekConf.Forms
TekConf/TekConf.Forms/Cells/ConferenceListSessionsListCell.xaml.cs
C#
mit
499
<?php namespace SilexMarkdown\Parser; use SilexMarkdown\Filter\FilterInterface; interface ParserInterface { public function transform($source); public function registerFilter($method, FilterInterface $filter); public function getFilters(); public function hasFilter($method); public function useFilter($method, $content, $params); }
MadCatme/SilexMarkdown
src/SilexMarkdown/Parser/ParserInterface.php
PHP
mit
356
import Lab from 'lab'; import server from '../../server'; import data from '../data'; const expect = Lab.assertions.expect; export const lab = Lab.script(); lab.experiment('ProfileCtrl', function() { lab.before(done => { data.sync().then(done, done); }); lab.test('[getAuthenticated] returns the current profile', function(done) { const options = { method: 'GET', url: '/profile', headers: { 'Authorization': `Bearer ${data.fp.token.value}` } }; server.inject(options, function(response) { const result = response.result; expect(response.statusCode).to.equal(200); expect(result.email).to.equal(data.fp.account.profile.email); done(); }); }); lab.test('[getAuthenticated] returns 401 without a token', function(done) { const options = { method: 'GET', url: '/profile' }; server.inject(options, function(response) { expect(response.statusCode).to.equal(401); done(); }); }); lab.test('[get] returns the correct profile by id', function(done) { const options = { method: 'GET', url: `/profile/${data.tp.account.profile.id}`, headers: { 'Authorization': `Bearer ${data.fp.token.value}` } }; server.inject(options, function(response) { const result = response.result; expect(response.statusCode).to.equal(200); expect(result.id).to.equal(data.tp.account.profile.id); done(); }); }); lab.test('[get] returns the correct profile by email', function(done) { const options = { method: 'GET', url: `/profile/${encodeURIComponent(data.tp.account.profile.email)}`, headers: { 'Authorization': `Bearer ${data.fp.token.value}` } }; server.inject(options, function(response) { const result = response.result; expect(response.statusCode).to.equal(200); expect(result.email).to.equal(data.tp.account.profile.email); done(); }); }); lab.test('[get] returns 404 if not found by id', function(done) { const options = { method: 'GET', url: `/profile/123-456`, headers: { 'Authorization': `Bearer ${data.fp.token.value}` } }; server.inject(options, function(response) { expect(response.statusCode).to.equal(404); done(); }); }); lab.test('[get] returns 404 if not found by email', function(done) { const options = { method: 'GET', url: `/profile/${encodeURIComponent('not@found.com')}`, headers: { 'Authorization': `Bearer ${data.fp.token.value}` } }; server.inject(options, function(response) { expect(response.statusCode).to.equal(404); done(); }); }); lab.test('[update] returns the profile with a new first name (by id)', function(done) { const options = { method: 'PUT', url: `/profile/${data.tp.account.profile.id}`, headers: { 'Authorization': `Bearer ${data.tp.token.value}` }, payload: { firstName: 'Gargantua' } }; server.inject(options, function(response) { const result = response.result; expect(response.statusCode).to.equal(200); expect(result.name.first).to.equal('Gargantua'); done(); }); }); lab.test('[update] returns the profile with a new last name (by email)', function(done) { const options = { method: 'PUT', url: `/profile/${data.tp.account.profile.email}`, headers: { 'Authorization': `Bearer ${data.tp.token.value}` }, payload: { lastName: 'Batman' } }; server.inject(options, function(response) { const result = response.result; expect(response.statusCode).to.equal(200); expect(result.name.last).to.equal('Batman'); done(); }); }); lab.test('[update] returns 401 if trying to update someone else\'s profile', function(done) { const options = { method: 'PUT', url: `/profile/${data.tp.account.profile.email}`, headers: { 'Authorization': `Bearer ${data.fp.token.value}` }, payload: { lastName: 'Batman' } }; server.inject(options, function(response) { expect(response.statusCode).to.equal(401); done(); }); }); });
FOUfashion/api
src/tests/controllers/profile.js
JavaScript
mit
4,337
package net.glowstone.net.message.play.entity; import com.flowpowered.network.Message; import java.util.List; import lombok.Data; @Data public final class DestroyEntitiesMessage implements Message { private final List<Integer> ids; }
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/net/message/play/entity/DestroyEntitiesMessage.java
Java
mit
242
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2022, Benoit BLANCHON // MIT License #include <ArduinoJson.h> #include <catch.hpp> #define SHOULD_WORK(expression) REQUIRE(DeserializationError::Ok == expression); #define SHOULD_FAIL(expression) \ REQUIRE(DeserializationError::TooDeep == expression); TEST_CASE("JsonDeserializer nesting") { DynamicJsonDocument doc(4096); SECTION("Input = const char*") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeJson(doc, "\"toto\"", nesting)); SHOULD_WORK(deserializeJson(doc, "123", nesting)); SHOULD_WORK(deserializeJson(doc, "true", nesting)); SHOULD_FAIL(deserializeJson(doc, "[]", nesting)); SHOULD_FAIL(deserializeJson(doc, "{}", nesting)); SHOULD_FAIL(deserializeJson(doc, "[\"toto\"]", nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":1}", nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeJson(doc, "[\"toto\"]", nesting)); SHOULD_WORK(deserializeJson(doc, "{\"toto\":1}", nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":{}}", nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":[]}", nesting)); SHOULD_FAIL(deserializeJson(doc, "[[\"toto\"]]", nesting)); SHOULD_FAIL(deserializeJson(doc, "[{\"toto\":1}]", nesting)); } } SECTION("char* and size_t") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeJson(doc, "\"toto\"", 6, nesting)); SHOULD_WORK(deserializeJson(doc, "123", 3, nesting)); SHOULD_WORK(deserializeJson(doc, "true", 4, nesting)); SHOULD_FAIL(deserializeJson(doc, "[]", 2, nesting)); SHOULD_FAIL(deserializeJson(doc, "{}", 2, nesting)); SHOULD_FAIL(deserializeJson(doc, "[\"toto\"]", 8, nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":1}", 10, nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeJson(doc, "[\"toto\"]", 8, nesting)); SHOULD_WORK(deserializeJson(doc, "{\"toto\":1}", 10, nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":{}}", 11, nesting)); SHOULD_FAIL(deserializeJson(doc, "{\"toto\":[]}", 11, nesting)); SHOULD_FAIL(deserializeJson(doc, "[[\"toto\"]]", 10, nesting)); SHOULD_FAIL(deserializeJson(doc, "[{\"toto\":1}]", 12, nesting)); } } SECTION("Input = std::string") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); SHOULD_WORK(deserializeJson(doc, std::string("\"toto\""), nesting)); SHOULD_WORK(deserializeJson(doc, std::string("123"), nesting)); SHOULD_WORK(deserializeJson(doc, std::string("true"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("[]"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("{}"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("[\"toto\"]"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":1}"), nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); SHOULD_WORK(deserializeJson(doc, std::string("[\"toto\"]"), nesting)); SHOULD_WORK(deserializeJson(doc, std::string("{\"toto\":1}"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":{}}"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("{\"toto\":[]}"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("[[\"toto\"]]"), nesting)); SHOULD_FAIL(deserializeJson(doc, std::string("[{\"toto\":1}]"), nesting)); } } SECTION("Input = std::istream") { SECTION("limit = 0") { DeserializationOption::NestingLimit nesting(0); std::istringstream good("true"); std::istringstream bad("[]"); SHOULD_WORK(deserializeJson(doc, good, nesting)); SHOULD_FAIL(deserializeJson(doc, bad, nesting)); } SECTION("limit = 1") { DeserializationOption::NestingLimit nesting(1); std::istringstream good("[\"toto\"]"); std::istringstream bad("{\"toto\":{}}"); SHOULD_WORK(deserializeJson(doc, good, nesting)); SHOULD_FAIL(deserializeJson(doc, bad, nesting)); } } }
bblanchon/ArduinoJson
extras/tests/JsonDeserializer/nestingLimit.cpp
C++
mit
4,306
const fs = require('fs') const path = require('path') const LRU = require('lru-cache') const express = require('express') const favicon = require('serve-favicon') const compression = require('compression') const resolve = file => path.resolve(__dirname, file) const { createBundleRenderer } = require('vue-server-renderer') const isProd = process.env.NODE_ENV === 'production' const useMicroCache = process.env.MICRO_CACHE !== 'false' const serverInfo = `express/${require('express/package.json').version} ` + `vue-server-renderer/${require('vue-server-renderer/package.json').version}` const app = express() const template = fs.readFileSync(resolve('./src/index.html'), 'utf-8'); function createRenderer (bundle, options) { // https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer return createBundleRenderer(bundle, Object.assign(options, { template, // for component caching cache: LRU({ max: 1000, maxAge: 1000 * 60 * 15 }), // this is only needed when vue-server-renderer is npm-linked basedir: resolve('./dist'), // recommended for performance runInNewContext: false })) } let renderer let readyPromise if (isProd) { // In production: create server renderer using built server bundle. // The server bundle is generated by vue-ssr-webpack-plugin. const bundle = require('./dist/vue-ssr-server-bundle.json') // The client manifests are optional, but it allows the renderer // to automatically infer preload/prefetch links and directly add <script> // tags for any async chunks used during render, avoiding waterfall requests. const clientManifest = require('./dist/vue-ssr-client-manifest.json') renderer = createRenderer(bundle, { clientManifest }) } else { // In development: setup the dev server with watch and hot-reload, // and create a new renderer on bundle / index template update. readyPromise = require('./build/setup-dev-server')(app, (bundle, options) => { renderer = createRenderer(bundle, options) }) } const serve = (path, cache) => express.static(resolve(path), { maxAge: cache && isProd ? 1000 * 60 * 60 * 24 * 30 : 0 }) app.use(compression({ threshold: 0 })) //app.use(favicon('./public/logo-48.png')) app.use('/dist', serve('./dist', true)) app.use('/public', serve('./public', true)) app.use('/manifest.json', serve('./manifest.json', true)) app.use('/service-worker.js', serve('./dist/service-worker.js')) // 1-second microcache. // https://www.nginx.com/blog/benefits-of-microcaching-nginx/ const microCache = LRU({ max: 100, maxAge: 1000 }) // since this app has no user-specific content, every page is micro-cacheable. // if your app involves user-specific content, you need to implement custom // logic to determine whether a request is cacheable based on its url and // headers. const isCacheable = req => useMicroCache function render (req, res) { const s = Date.now() res.setHeader("Content-Type", "text/html") res.setHeader("Server", serverInfo) const handleError = err => { if (err.url) { res.redirect(err.url) } else if(err.code === 404) { res.status(404).end('404 | Page Not Found') } else { // Render Error Page or Redirect res.status(500).end('500 | Internal Server Error') console.error(`error during render : ${req.url}`) console.error(err.stack) } } const cacheable = isCacheable(req) if (cacheable) { const hit = microCache.get(req.url) if (hit) { if (!isProd) { console.log(`cache hit!`) } return res.end(hit) } } const context = { title: '交易虎_手机游戏交易平台_手游交易_帐号交易_游戏币交易_装备交易_道具交易_jiaoyihu', // default title url: req.url } renderer.renderToString(context, (err, html) => { debugger; if (err) { return handleError(err) } res.end(html) if (cacheable) { microCache.set(req.url, html) } if (!isProd) { console.log(`whole request: ${Date.now() - s}ms`) } }) } app.get('*', isProd ? render : (req, res) => { readyPromise.then(() => render(req, res)) }) const port = process.env.PORT || 80; app.listen(port, () => { console.log(`server started at localhost:${port}`) })
wenyejie/trading-tiger
server.js
JavaScript
mit
4,301
module FinancialStatementHelper include HyaccConst def colspan( node_level ) @max_node_level - node_level + 1 end def is_visible_on_report( account, branch_id ) # 削除された科目は表示しない return false if account.deleted? # 決算書科目以外は表示しない return false unless account.is_settlement_report_account # 検索条件に部門指定がない場合は全社での出力なので内部取引は表示しない if branch_id.to_i == 0 return false if account.internal_trade? end true end end
hybitz/hyacc
app/helpers/financial_statement_helper.rb
Ruby
mit
611
<?php class kml_TimeSpan extends kml_TimePrimitive { protected $tagName = 'TimeSpan'; var $begin; var $end; /* Constructor */ function kml_TimeSpan($begin = null, $end = null) { parent::kml_TimePrimitive(); if ($begin !== null) $this->set_begin($begin); if ($end !== null) $this->set_end($end); } /* Assignments */ function set_begin($begin) { $this->begin = $begin; } function set_end($end) { $this->end = $end; } /* Render */ function render($doc) { $X = parent::render($doc); if (isset($this->begin)) $X->appendChild(XML_create_text_element($doc, 'begin', $this->begin)); if (isset($this->end)) $X->appendChild(XML_create_text_element($doc, 'end', $this->end)); return $X; } } /* $a = new kml_TimeSpan(); $a->dump(false); */
lifelink1987/old.life-link.org
libs/php-kml/kml_TimeSpan.php
PHP
mit
845