repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
seuffert/rclone | vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go | 74066 | package devices
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 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"
"net/http"
)
// IotHubResourceClient is the use this API to manage the IoT hubs in your Azure subscription.
type IotHubResourceClient struct {
BaseClient
}
// NewIotHubResourceClient creates an instance of the IotHubResourceClient client.
func NewIotHubResourceClient(subscriptionID string) IotHubResourceClient {
return NewIotHubResourceClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewIotHubResourceClientWithBaseURI creates an instance of the IotHubResourceClient client.
func NewIotHubResourceClientWithBaseURI(baseURI string, subscriptionID string) IotHubResourceClient {
return IotHubResourceClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CheckNameAvailability check if an IoT hub name is available.
// Parameters:
// operationInputs - set the name parameter in the OperationInputs structure to the name of the IoT hub to
// check.
func (client IotHubResourceClient) CheckNameAvailability(ctx context.Context, operationInputs OperationInputs) (result IotHubNameAvailabilityInfo, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: operationInputs,
Constraints: []validation.Constraint{{Target: "operationInputs.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("devices.IotHubResourceClient", "CheckNameAvailability", err.Error())
}
req, err := client.CheckNameAvailabilityPreparer(ctx, operationInputs)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CheckNameAvailability", nil, "Failure preparing request")
return
}
resp, err := client.CheckNameAvailabilitySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CheckNameAvailability", resp, "Failure sending request")
return
}
result, err = client.CheckNameAvailabilityResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CheckNameAvailability", resp, "Failure responding to request")
}
return
}
// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request.
func (client IotHubResourceClient) CheckNameAvailabilityPreparer(ctx context.Context, operationInputs OperationInputs) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
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}/providers/Microsoft.Devices/checkNameAvailability", pathParameters),
autorest.WithJSON(operationInputs),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) CheckNameAvailabilityResponder(resp *http.Response) (result IotHubNameAvailabilityInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible endpoint in an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// eventHubEndpointName - the name of the Event Hub-compatible endpoint in the IoT hub.
// name - the name of the consumer group to add.
func (client IotHubResourceClient) CreateEventHubConsumerGroup(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) {
req, err := client.CreateEventHubConsumerGroupPreparer(ctx, resourceGroupName, resourceName, eventHubEndpointName, name)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CreateEventHubConsumerGroup", nil, "Failure preparing request")
return
}
resp, err := client.CreateEventHubConsumerGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CreateEventHubConsumerGroup", resp, "Failure sending request")
return
}
result, err = client.CreateEventHubConsumerGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CreateEventHubConsumerGroup", resp, "Failure responding to request")
}
return
}
// CreateEventHubConsumerGroupPreparer prepares the CreateEventHubConsumerGroup request.
func (client IotHubResourceClient) CreateEventHubConsumerGroupPreparer(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"eventHubEndpointName": autorest.Encode("path", eventHubEndpointName),
"name": autorest.Encode("path", name),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateEventHubConsumerGroupSender sends the CreateEventHubConsumerGroup request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) CreateEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateEventHubConsumerGroupResponder handles the response to the CreateEventHubConsumerGroup request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) CreateEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// CreateOrUpdate create or update the metadata of an Iot hub. The usual pattern to modify a property is to retrieve
// the IoT hub metadata and security metadata, and then combine them with the modified values in a new body to update
// the IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// iotHubDescription - the IoT hub metadata and security metadata.
// ifMatch - eTag of the IoT Hub. Do not specify for creating a brand new IoT Hub. Required to update an
// existing IoT Hub.
func (client IotHubResourceClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, iotHubDescription IotHubDescription, ifMatch string) (result IotHubResourceCreateOrUpdateFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: iotHubDescription,
Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil},
{Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil},
{Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.Source", Name: validation.Null, Rule: true, Chain: nil},
{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil},
{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil},
}},
{Target: "iotHubDescription.Properties.Routing.FallbackRoute.IsEnabled", Name: validation.Null, Rule: true, Chain: nil},
}},
}},
{Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil},
{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}},
{Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil},
{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil},
}},
}},
}},
}},
{Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("devices.IotHubResourceClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, resourceName, iotHubDescription, ifMatch)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client IotHubResourceClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, resourceName string, iotHubDescription IotHubDescription, ifMatch string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters),
autorest.WithJSON(iotHubDescription),
autorest.WithQueryParameters(queryParameters))
if len(ifMatch) > 0 {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithHeader("If-Match", autorest.String(ifMatch)))
}
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 IotHubResourceClient) CreateOrUpdateSender(req *http.Request) (future IotHubResourceCreateOrUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) CreateOrUpdateResponder(resp *http.Response) (result IotHubDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete delete an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) Delete(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubResourceDeleteFuture, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", 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 IotHubResourceClient) DeleteSender(req *http.Request) (future IotHubResourceDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) DeleteResponder(resp *http.Response) (result SetObject, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// DeleteEventHubConsumerGroup delete a consumer group from an Event Hub-compatible endpoint in an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// eventHubEndpointName - the name of the Event Hub-compatible endpoint in the IoT hub.
// name - the name of the consumer group to delete.
func (client IotHubResourceClient) DeleteEventHubConsumerGroup(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result autorest.Response, err error) {
req, err := client.DeleteEventHubConsumerGroupPreparer(ctx, resourceGroupName, resourceName, eventHubEndpointName, name)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "DeleteEventHubConsumerGroup", nil, "Failure preparing request")
return
}
resp, err := client.DeleteEventHubConsumerGroupSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure sending request")
return
}
result, err = client.DeleteEventHubConsumerGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure responding to request")
}
return
}
// DeleteEventHubConsumerGroupPreparer prepares the DeleteEventHubConsumerGroup request.
func (client IotHubResourceClient) DeleteEventHubConsumerGroupPreparer(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"eventHubEndpointName": autorest.Encode("path", eventHubEndpointName),
"name": autorest.Encode("path", name),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteEventHubConsumerGroupSender sends the DeleteEventHubConsumerGroup request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) DeleteEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteEventHubConsumerGroupResponder handles the response to the DeleteEventHubConsumerGroup request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) DeleteEventHubConsumerGroupResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// ExportDevices exports all the device identities in the IoT hub identity registry to an Azure Storage blob container.
// For more information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// exportDevicesParameters - the parameters that specify the export devices operation.
func (client IotHubResourceClient) ExportDevices(ctx context.Context, resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (result JobResponse, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: exportDevicesParameters,
Constraints: []validation.Constraint{{Target: "exportDevicesParameters.ExportBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil},
{Target: "exportDevicesParameters.ExcludeKeys", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("devices.IotHubResourceClient", "ExportDevices", err.Error())
}
req, err := client.ExportDevicesPreparer(ctx, resourceGroupName, resourceName, exportDevicesParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ExportDevices", nil, "Failure preparing request")
return
}
resp, err := client.ExportDevicesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ExportDevices", resp, "Failure sending request")
return
}
result, err = client.ExportDevicesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ExportDevices", resp, "Failure responding to request")
}
return
}
// ExportDevicesPreparer prepares the ExportDevices request.
func (client IotHubResourceClient) ExportDevicesPreparer(ctx context.Context, resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
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.Devices/IotHubs/{resourceName}/exportDevices", pathParameters),
autorest.WithJSON(exportDevicesParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ExportDevicesSender sends the ExportDevices request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ExportDevicesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ExportDevicesResponder handles the response to the ExportDevices request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ExportDevicesResponder(resp *http.Response) (result JobResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Get get the non-security related metadata of an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) Get(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client IotHubResourceClient) GetPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}", 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 IotHubResourceClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetResponder(resp *http.Response) (result IotHubDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// eventHubEndpointName - the name of the Event Hub-compatible endpoint in the IoT hub.
// name - the name of the consumer group to retrieve.
func (client IotHubResourceClient) GetEventHubConsumerGroup(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) {
req, err := client.GetEventHubConsumerGroupPreparer(ctx, resourceGroupName, resourceName, eventHubEndpointName, name)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEventHubConsumerGroup", nil, "Failure preparing request")
return
}
resp, err := client.GetEventHubConsumerGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEventHubConsumerGroup", resp, "Failure sending request")
return
}
result, err = client.GetEventHubConsumerGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEventHubConsumerGroup", resp, "Failure responding to request")
}
return
}
// GetEventHubConsumerGroupPreparer prepares the GetEventHubConsumerGroup request.
func (client IotHubResourceClient) GetEventHubConsumerGroupPreparer(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"eventHubEndpointName": autorest.Encode("path", eventHubEndpointName),
"name": autorest.Encode("path", name),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetEventHubConsumerGroupSender sends the GetEventHubConsumerGroup request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetEventHubConsumerGroupResponder handles the response to the GetEventHubConsumerGroup request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetJob get the details of a job from an IoT hub. For more information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// jobID - the job identifier.
func (client IotHubResourceClient) GetJob(ctx context.Context, resourceGroupName string, resourceName string, jobID string) (result JobResponse, err error) {
req, err := client.GetJobPreparer(ctx, resourceGroupName, resourceName, jobID)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetJob", nil, "Failure preparing request")
return
}
resp, err := client.GetJobSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetJob", resp, "Failure sending request")
return
}
result, err = client.GetJobResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetJob", resp, "Failure responding to request")
}
return
}
// GetJobPreparer prepares the GetJob request.
func (client IotHubResourceClient) GetJobPreparer(ctx context.Context, resourceGroupName string, resourceName string, jobID string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"jobId": autorest.Encode("path", jobID),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/jobs/{jobId}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetJobSender sends the GetJob request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetJobSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetJobResponder handles the response to the GetJob request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetJobResponder(resp *http.Response) (result JobResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetKeysForKeyName get a shared access policy by name from an IoT hub. For more information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// keyName - the name of the shared access policy.
func (client IotHubResourceClient) GetKeysForKeyName(ctx context.Context, resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) {
req, err := client.GetKeysForKeyNamePreparer(ctx, resourceGroupName, resourceName, keyName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetKeysForKeyName", nil, "Failure preparing request")
return
}
resp, err := client.GetKeysForKeyNameSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetKeysForKeyName", resp, "Failure sending request")
return
}
result, err = client.GetKeysForKeyNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetKeysForKeyName", resp, "Failure responding to request")
}
return
}
// GetKeysForKeyNamePreparer prepares the GetKeysForKeyName request.
func (client IotHubResourceClient) GetKeysForKeyNamePreparer(ctx context.Context, resourceGroupName string, resourceName string, keyName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"keyName": autorest.Encode("path", keyName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetKeysForKeyNameSender sends the GetKeysForKeyName request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetKeysForKeyNameSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetKeysForKeyNameResponder handles the response to the GetKeysForKeyName request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRule, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetQuotaMetrics get the quota metrics for an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) GetQuotaMetrics(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubQuotaMetricInfoListResultPage, err error) {
result.fn = client.getQuotaMetricsNextResults
req, err := client.GetQuotaMetricsPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetQuotaMetrics", nil, "Failure preparing request")
return
}
resp, err := client.GetQuotaMetricsSender(req)
if err != nil {
result.ihqmilr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetQuotaMetrics", resp, "Failure sending request")
return
}
result.ihqmilr, err = client.GetQuotaMetricsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetQuotaMetrics", resp, "Failure responding to request")
}
return
}
// GetQuotaMetricsPreparer prepares the GetQuotaMetrics request.
func (client IotHubResourceClient) GetQuotaMetricsPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/quotaMetrics", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetQuotaMetricsSender sends the GetQuotaMetrics request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetQuotaMetricsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetQuotaMetricsResponder handles the response to the GetQuotaMetrics request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetQuotaMetricsResponder(resp *http.Response) (result IotHubQuotaMetricInfoListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// getQuotaMetricsNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) getQuotaMetricsNextResults(lastResults IotHubQuotaMetricInfoListResult) (result IotHubQuotaMetricInfoListResult, err error) {
req, err := lastResults.iotHubQuotaMetricInfoListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getQuotaMetricsNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.GetQuotaMetricsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getQuotaMetricsNextResults", resp, "Failure sending next results request")
}
result, err = client.GetQuotaMetricsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getQuotaMetricsNextResults", resp, "Failure responding to next results request")
}
return
}
// GetQuotaMetricsComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) GetQuotaMetricsComplete(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubQuotaMetricInfoListResultIterator, err error) {
result.page, err = client.GetQuotaMetrics(ctx, resourceGroupName, resourceName)
return
}
// GetStats get the statistics from an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) GetStats(ctx context.Context, resourceGroupName string, resourceName string) (result RegistryStatistics, err error) {
req, err := client.GetStatsPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetStats", nil, "Failure preparing request")
return
}
resp, err := client.GetStatsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetStats", resp, "Failure sending request")
return
}
result, err = client.GetStatsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetStats", resp, "Failure responding to request")
}
return
}
// GetStatsPreparer prepares the GetStats request.
func (client IotHubResourceClient) GetStatsPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/IotHubStats", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetStatsSender sends the GetStats request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetStatsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetStatsResponder handles the response to the GetStats request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetStatsResponder(resp *http.Response) (result RegistryStatistics, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetValidSkus get the list of valid SKUs for an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) GetValidSkus(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubSkuDescriptionListResultPage, err error) {
result.fn = client.getValidSkusNextResults
req, err := client.GetValidSkusPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetValidSkus", nil, "Failure preparing request")
return
}
resp, err := client.GetValidSkusSender(req)
if err != nil {
result.ihsdlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetValidSkus", resp, "Failure sending request")
return
}
result.ihsdlr, err = client.GetValidSkusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetValidSkus", resp, "Failure responding to request")
}
return
}
// GetValidSkusPreparer prepares the GetValidSkus request.
func (client IotHubResourceClient) GetValidSkusPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/skus", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetValidSkusSender sends the GetValidSkus request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) GetValidSkusSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetValidSkusResponder handles the response to the GetValidSkus request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) GetValidSkusResponder(resp *http.Response) (result IotHubSkuDescriptionListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// getValidSkusNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) getValidSkusNextResults(lastResults IotHubSkuDescriptionListResult) (result IotHubSkuDescriptionListResult, err error) {
req, err := lastResults.iotHubSkuDescriptionListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getValidSkusNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.GetValidSkusSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getValidSkusNextResults", resp, "Failure sending next results request")
}
result, err = client.GetValidSkusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getValidSkusNextResults", resp, "Failure responding to next results request")
}
return
}
// GetValidSkusComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) GetValidSkusComplete(ctx context.Context, resourceGroupName string, resourceName string) (result IotHubSkuDescriptionListResultIterator, err error) {
result.page, err = client.GetValidSkus(ctx, resourceGroupName, resourceName)
return
}
// ImportDevices import, update, or delete device identities in the IoT hub identity registry from a blob. For more
// information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// importDevicesParameters - the parameters that specify the import devices operation.
func (client IotHubResourceClient) ImportDevices(ctx context.Context, resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (result JobResponse, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: importDevicesParameters,
Constraints: []validation.Constraint{{Target: "importDevicesParameters.InputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil},
{Target: "importDevicesParameters.OutputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("devices.IotHubResourceClient", "ImportDevices", err.Error())
}
req, err := client.ImportDevicesPreparer(ctx, resourceGroupName, resourceName, importDevicesParameters)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ImportDevices", nil, "Failure preparing request")
return
}
resp, err := client.ImportDevicesSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ImportDevices", resp, "Failure sending request")
return
}
result, err = client.ImportDevicesResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ImportDevices", resp, "Failure responding to request")
}
return
}
// ImportDevicesPreparer prepares the ImportDevices request.
func (client IotHubResourceClient) ImportDevicesPreparer(ctx context.Context, resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
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.Devices/IotHubs/{resourceName}/importDevices", pathParameters),
autorest.WithJSON(importDevicesParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ImportDevicesSender sends the ImportDevices request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ImportDevicesSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ImportDevicesResponder handles the response to the ImportDevices request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ImportDevicesResponder(resp *http.Response) (result JobResponse, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup get all the IoT hubs in a resource group.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
func (client IotHubResourceClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result IotHubDescriptionListResultPage, err error) {
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.ihdlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.ihdlr, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client IotHubResourceClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ListByResourceGroupResponder(resp *http.Response) (result IotHubDescriptionListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) listByResourceGroupNextResults(lastResults IotHubDescriptionListResult) (result IotHubDescriptionListResult, err error) {
req, err := lastResults.iotHubDescriptionListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result IotHubDescriptionListResultIterator, err error) {
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListBySubscription get all the IoT hubs in a subscription.
func (client IotHubResourceClient) ListBySubscription(ctx context.Context) (result IotHubDescriptionListResultPage, err error) {
result.fn = client.listBySubscriptionNextResults
req, err := client.ListBySubscriptionPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListBySubscription", nil, "Failure preparing request")
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.ihdlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListBySubscription", resp, "Failure sending request")
return
}
result.ihdlr, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListBySubscription", resp, "Failure responding to request")
}
return
}
// ListBySubscriptionPreparer prepares the ListBySubscription request.
func (client IotHubResourceClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/IotHubs", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListBySubscriptionSender sends the ListBySubscription request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ListBySubscriptionResponder(resp *http.Response) (result IotHubDescriptionListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listBySubscriptionNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) listBySubscriptionNextResults(lastResults IotHubDescriptionListResult) (result IotHubDescriptionListResult, err error) {
req, err := lastResults.iotHubDescriptionListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listBySubscriptionNextResults", resp, "Failure sending next results request")
}
result, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request")
}
return
}
// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) ListBySubscriptionComplete(ctx context.Context) (result IotHubDescriptionListResultIterator, err error) {
result.page, err = client.ListBySubscription(ctx)
return
}
// ListEventHubConsumerGroups get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in
// an IoT hub.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
// eventHubEndpointName - the name of the Event Hub-compatible endpoint.
func (client IotHubResourceClient) ListEventHubConsumerGroups(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResultPage, err error) {
result.fn = client.listEventHubConsumerGroupsNextResults
req, err := client.ListEventHubConsumerGroupsPreparer(ctx, resourceGroupName, resourceName, eventHubEndpointName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListEventHubConsumerGroups", nil, "Failure preparing request")
return
}
resp, err := client.ListEventHubConsumerGroupsSender(req)
if err != nil {
result.ehcglr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListEventHubConsumerGroups", resp, "Failure sending request")
return
}
result.ehcglr, err = client.ListEventHubConsumerGroupsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListEventHubConsumerGroups", resp, "Failure responding to request")
}
return
}
// ListEventHubConsumerGroupsPreparer prepares the ListEventHubConsumerGroups request.
func (client IotHubResourceClient) ListEventHubConsumerGroupsPreparer(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"eventHubEndpointName": autorest.Encode("path", eventHubEndpointName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListEventHubConsumerGroupsSender sends the ListEventHubConsumerGroups request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ListEventHubConsumerGroupsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListEventHubConsumerGroupsResponder handles the response to the ListEventHubConsumerGroups request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ListEventHubConsumerGroupsResponder(resp *http.Response) (result EventHubConsumerGroupsListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listEventHubConsumerGroupsNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) listEventHubConsumerGroupsNextResults(lastResults EventHubConsumerGroupsListResult) (result EventHubConsumerGroupsListResult, err error) {
req, err := lastResults.eventHubConsumerGroupsListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listEventHubConsumerGroupsNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListEventHubConsumerGroupsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listEventHubConsumerGroupsNextResults", resp, "Failure sending next results request")
}
result, err = client.ListEventHubConsumerGroupsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listEventHubConsumerGroupsNextResults", resp, "Failure responding to next results request")
}
return
}
// ListEventHubConsumerGroupsComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) ListEventHubConsumerGroupsComplete(ctx context.Context, resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResultIterator, err error) {
result.page, err = client.ListEventHubConsumerGroups(ctx, resourceGroupName, resourceName, eventHubEndpointName)
return
}
// ListJobs get a list of all the jobs in an IoT hub. For more information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) ListJobs(ctx context.Context, resourceGroupName string, resourceName string) (result JobResponseListResultPage, err error) {
result.fn = client.listJobsNextResults
req, err := client.ListJobsPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListJobs", nil, "Failure preparing request")
return
}
resp, err := client.ListJobsSender(req)
if err != nil {
result.jrlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListJobs", resp, "Failure sending request")
return
}
result.jrlr, err = client.ListJobsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListJobs", resp, "Failure responding to request")
}
return
}
// ListJobsPreparer prepares the ListJobs request.
func (client IotHubResourceClient) ListJobsPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-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.Devices/IotHubs/{resourceName}/jobs", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListJobsSender sends the ListJobs request. The method will close the
// http.Response Body if it receives an error.
func (client IotHubResourceClient) ListJobsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListJobsResponder handles the response to the ListJobs request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ListJobsResponder(resp *http.Response) (result JobResponseListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listJobsNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) listJobsNextResults(lastResults JobResponseListResult) (result JobResponseListResult, err error) {
req, err := lastResults.jobResponseListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listJobsNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListJobsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listJobsNextResults", resp, "Failure sending next results request")
}
result, err = client.ListJobsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listJobsNextResults", resp, "Failure responding to next results request")
}
return
}
// ListJobsComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) ListJobsComplete(ctx context.Context, resourceGroupName string, resourceName string) (result JobResponseListResultIterator, err error) {
result.page, err = client.ListJobs(ctx, resourceGroupName, resourceName)
return
}
// ListKeys get the security metadata for an IoT hub. For more information, see:
// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
// Parameters:
// resourceGroupName - the name of the resource group that contains the IoT hub.
// resourceName - the name of the IoT hub.
func (client IotHubResourceClient) ListKeys(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultPage, err error) {
result.fn = client.listKeysNextResults
req, err := client.ListKeysPreparer(ctx, resourceGroupName, resourceName)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListKeys", nil, "Failure preparing request")
return
}
resp, err := client.ListKeysSender(req)
if err != nil {
result.sasarlr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListKeys", resp, "Failure sending request")
return
}
result.sasarlr, err = client.ListKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "ListKeys", resp, "Failure responding to request")
}
return
}
// ListKeysPreparer prepares the ListKeys request.
func (client IotHubResourceClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"resourceName": autorest.Encode("path", resourceName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-07-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/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 IotHubResourceClient) ListKeysSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListKeysResponder handles the response to the ListKeys request. The method always
// closes the http.Response Body.
func (client IotHubResourceClient) ListKeysResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRuleListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listKeysNextResults retrieves the next set of results, if any.
func (client IotHubResourceClient) listKeysNextResults(lastResults SharedAccessSignatureAuthorizationRuleListResult) (result SharedAccessSignatureAuthorizationRuleListResult, err error) {
req, err := lastResults.sharedAccessSignatureAuthorizationRuleListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listKeysNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListKeysSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listKeysNextResults", resp, "Failure sending next results request")
}
result, err = client.ListKeysResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "listKeysNextResults", resp, "Failure responding to next results request")
}
return
}
// ListKeysComplete enumerates all values, automatically crossing page boundaries as required.
func (client IotHubResourceClient) ListKeysComplete(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultIterator, err error) {
result.page, err = client.ListKeys(ctx, resourceGroupName, resourceName)
return
}
| mit |
seuffert/rclone | vendor/github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network/publicipaddresses.go | 17872 | package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 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"
"net/http"
)
// PublicIPAddressesClient is the network Client
type PublicIPAddressesClient struct {
BaseClient
}
// NewPublicIPAddressesClient creates an instance of the PublicIPAddressesClient client.
func NewPublicIPAddressesClient(subscriptionID string) PublicIPAddressesClient {
return NewPublicIPAddressesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewPublicIPAddressesClientWithBaseURI creates an instance of the PublicIPAddressesClient client.
func NewPublicIPAddressesClientWithBaseURI(baseURI string, subscriptionID string) PublicIPAddressesClient {
return PublicIPAddressesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate the Put PublicIPAddress operation creates/updates a stable/dynamic PublicIP address
// Parameters:
// resourceGroupName - the name of the resource group.
// publicIPAddressName - the name of the publicIpAddress.
// parameters - parameters supplied to the create/update PublicIPAddress operation
func (client PublicIPAddressesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (result PublicIPAddressesCreateOrUpdateFuture, err error) {
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, publicIPAddressName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client PublicIPAddressesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (*http.Request, error) {
pathParameters := map[string]interface{}{
"publicIpAddressName": autorest.Encode("path", publicIPAddressName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}/", 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 PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (future PublicIPAddressesCreateOrUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated))
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPAddress, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete the delete publicIpAddress operation deletes the specified publicIpAddress.
// Parameters:
// resourceGroupName - the name of the resource group.
// publicIPAddressName - the name of the subnet.
func (client PublicIPAddressesClient) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) (result PublicIPAddressesDeleteFuture, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, publicIPAddressName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client PublicIPAddressesClient) DeletePreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"publicIpAddressName": autorest.Encode("path", publicIPAddressName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-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.Network/publicIPAddresses/{publicIpAddressName}/", 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 PublicIPAddressesClient) DeleteSender(req *http.Request) (future PublicIPAddressesDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get the Get publicIpAddress operation retreives information about the specified pubicIpAddress
// Parameters:
// resourceGroupName - the name of the resource group.
// publicIPAddressName - the name of the subnet.
func (client PublicIPAddressesClient) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string) (result PublicIPAddress, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, publicIPAddressName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client PublicIPAddressesClient) GetPreparer(ctx context.Context, resourceGroupName string, publicIPAddressName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"publicIpAddressName": autorest.Encode("path", publicIPAddressName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-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.Network/publicIPAddresses/{publicIpAddressName}/", 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 PublicIPAddressesClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result PublicIPAddress, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List the List publicIpAddress opertion retrieves all the publicIpAddresses in a resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
func (client PublicIPAddressesClient) List(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.pialr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request")
return
}
result.pialr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client PublicIPAddressesClient) ListPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-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.Network/publicIPAddresses", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client PublicIPAddressesClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result PublicIPAddressListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client PublicIPAddressesClient) listNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) {
req, err := lastResults.publicIPAddressListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client PublicIPAddressesClient) ListComplete(ctx context.Context, resourceGroupName string) (result PublicIPAddressListResultIterator, err error) {
result.page, err = client.List(ctx, resourceGroupName)
return
}
// ListAll the List publicIpAddress opertion retrieves all the publicIpAddresses in a subscription.
func (client PublicIPAddressesClient) ListAll(ctx context.Context) (result PublicIPAddressListResultPage, err error) {
result.fn = client.listAllNextResults
req, err := client.ListAllPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request")
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.pialr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request")
return
}
result.pialr, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to request")
}
return
}
// ListAllPreparer prepares the ListAll request.
func (client PublicIPAddressesClient) ListAllPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2015-05-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListAllSender sends the ListAll request. The method will close the
// http.Response Body if it receives an error.
func (client PublicIPAddressesClient) ListAllSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListAllResponder handles the response to the ListAll request. The method always
// closes the http.Response Body.
func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (result PublicIPAddressListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listAllNextResults retrieves the next set of results, if any.
func (client PublicIPAddressesClient) listAllNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) {
req, err := lastResults.publicIPAddressListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure sending next results request")
}
result, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "listAllNextResults", resp, "Failure responding to next results request")
}
return
}
// ListAllComplete enumerates all values, automatically crossing page boundaries as required.
func (client PublicIPAddressesClient) ListAllComplete(ctx context.Context) (result PublicIPAddressListResultIterator, err error) {
result.page, err = client.ListAll(ctx)
return
}
| mit |
zuazo-forks/rubocop | spec/rubocop/cop/lint/block_alignment_spec.rb | 17585 | # encoding: utf-8
require 'spec_helper'
describe RuboCop::Cop::Lint::BlockAlignment do
subject(:cop) { described_class.new }
context 'when the block has no arguments' do
it 'registers an offense for mismatched block end' do
inspect_source(cop,
['test do',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `test do` at 1, 0'])
end
it 'auto-corrects alignment' do
new_source = autocorrect_source(cop, ['test do',
' end'
])
expect(new_source).to eq(['test do',
'end'].join("\n"))
end
end
context 'when the block has arguments' do
it 'registers an offense for mismatched block end' do
inspect_source(cop,
['test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `test do |ala|` at 1, 0'])
end
it 'auto-corrects alignment' do
new_source = autocorrect_source(cop, ['test do |ala|',
' end'
])
expect(new_source).to eq(['test do |ala|',
'end'].join("\n"))
end
end
it 'acepts a block end that does not begin its line' do
inspect_source(cop,
[' scope :bar, lambda { joins(:baz)',
' .distinct }'
])
expect(cop.offenses).to be_empty
end
context 'when the block is a logical operand' do
it 'accepts a correctly aligned block end' do
inspect_source(cop,
['(value.is_a? Array) && value.all? do |subvalue|',
' type_check_value(subvalue, array_type)',
'end',
'a || b do',
'end'
])
expect(cop.offenses).to be_empty
end
end
it 'accepts end aligned with a variable' do
inspect_source(cop,
['variable = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
context 'when there is an assignment chain' do
it 'registers an offense for an end aligned with the 2nd variable' do
inspect_source(cop,
['a = b = c = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 4 is not aligned with' \
' `a = b = c = test do |ala|` at 1, 0'])
end
it 'accepts end aligned with the first variable' do
inspect_source(cop,
['a = b = c = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'auto-corrects alignment to the block start' do
new_source = autocorrect_source(cop,
['a = b = c = test do |ala|',
' end'
])
expect(new_source).to eq(['a = b = c = test do |ala|',
' end'
].join("\n"))
end
end
context 'and the block is an operand' do
it 'accepts end aligned with a variable' do
inspect_source(cop,
['b = 1 + preceding_line.reduce(0) do |a, e|',
' a + e.length + newline_length',
'end + 1'
])
expect(cop.offenses).to be_empty
end
end
it 'registers an offense for mismatched block end with a variable' do
inspect_source(cop,
['variable = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `variable = test do |ala|`' \
' at 1, 0'])
end
context 'when the block is defined on the next line' do
it 'accepts end aligned with the block expression' do
inspect_source(cop,
['variable =',
' a_long_method_that_dont_fit_on_the_line do |v|',
' v.foo',
' end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offenses for mismatched end alignment' do
inspect_source(cop,
['variable =',
' a_long_method_that_dont_fit_on_the_line do |v|',
' v.foo',
'end'
])
expect(cop.messages)
.to eq(['`end` at 4, 0 is not aligned with' \
' `a_long_method_that_dont_fit_on_the_line do |v|` at 2, 2'])
end
it 'auto-corrects alignment' do
new_source = autocorrect_source(
cop,
['variable =',
' a_long_method_that_dont_fit_on_the_line do |v|',
' v.foo',
'end'
])
expect(new_source)
.to eq(['variable =',
' a_long_method_that_dont_fit_on_the_line do |v|',
' v.foo',
' end'
].join("\n"))
end
end
context 'when the method part is a call chain that spans several lines' do
# Example from issue 346 of bbatsov/rubocop on github:
it 'accepts pretty alignment style' do
src = [
'def foo(bar)',
' bar.get_stuffs',
' .reject do |stuff| ',
' stuff.with_a_very_long_expression_that_doesnt_fit_the_line',
' end.select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
' .select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
'end']
inspect_source(cop, src)
expect(cop.offenses).to be_empty
end
it 'registers offenses for misaligned ends' do
src = [
'def foo(bar)',
' bar.get_stuffs',
' .reject do |stuff|',
' stuff.with_a_very_long_expression_that_doesnt_fit_the_line',
' end.select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
' .select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
'end']
inspect_source(cop, src)
expect(cop.messages)
.to eq(['`end` at 5, 8 is not aligned with `bar.get_stuffs` at 2, 2' \
' or `.reject do |stuff|` at 3, 6',
'`end` at 7, 4 is not aligned with `bar.get_stuffs` at 2, 2' \
' or `end.select do |stuff|` at 5, 8',
'`end` at 10, 8 is not aligned with `bar.get_stuffs` at 2, 2' \
' or `.select do |stuff|` at 8, 6'])
end
# Example from issue 393 of bbatsov/rubocop on github:
it 'accepts end indented as the start of the block' do
src = ['my_object.chaining_this_very_long_method(with_a_parameter)',
' .and_one_with_a_block do',
' do_something',
'end',
'', # Other variant:
'my_object.chaining_this_very_long_method(',
' with_a_parameter).and_one_with_a_block do',
' do_something',
'end']
inspect_source(cop, src)
expect(cop.offenses).to be_empty
end
# Example from issue 447 of bbatsov/rubocop on github:
it 'accepts two kinds of end alignment' do
src = [
# Aligned with start of line where do is:
'params = default_options.merge(options)',
' .delete_if { |k, v| v.nil? }',
' .each_with_object({}) do |(k, v), new_hash|',
' new_hash[k.to_s] = v.to_s',
' end',
# Aligned with start of the whole expression:
'params = default_options.merge(options)',
' .delete_if { |k, v| v.nil? }',
' .each_with_object({}) do |(k, v), new_hash|',
' new_hash[k.to_s] = v.to_s',
'end'
]
inspect_source(cop, src)
expect(cop.offenses).to be_empty
end
it 'auto-corrects misaligned ends with the start of the expression' do
src = [
'def foo(bar)',
' bar.get_stuffs',
' .reject do |stuff|',
' stuff.with_a_very_long_expression_that_doesnt_fit_the_line',
' end.select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
' .select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
'end']
aligned_src = [
'def foo(bar)',
' bar.get_stuffs',
' .reject do |stuff|',
' stuff.with_a_very_long_expression_that_doesnt_fit_the_line',
' end.select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
' .select do |stuff|',
' stuff.another_very_long_expression_that_doesnt_fit_the_line',
' end',
'end'].join("\n")
new_source = autocorrect_source(cop, src)
expect(new_source).to eq(aligned_src)
end
end
context 'when variables of a mass assignment spans several lines' do
it 'accepts end aligned with the variables' do
src = ['e,',
'f = [5, 6].map do |i|',
' i - 5',
'end']
inspect_source(cop, src)
expect(cop.offenses).to be_empty
end
it 'registers an offense for end aligned with the block' do
src = ['e,',
'f = [5, 6].map do |i|',
' i - 5',
' end']
inspect_source(cop, src)
expect(cop.messages)
.to eq(['`end` at 4, 4 is not aligned with `e,` at 1, 0 or' \
' `f = [5, 6].map do |i|` at 2, 0'])
end
it 'can not auto-correct' do
src = ['e,',
'f = [5, 6].map do |i|',
' i - 5',
' end']
new_source = autocorrect_source(cop, src)
expect(new_source).to eq(src.join("\n"))
end
end
it 'accepts end aligned with an instance variable' do
inspect_source(cop,
['@variable = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with' \
' an instance variable' do
inspect_source(cop,
['@variable = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `@variable = test do |ala|`' \
' at 1, 0'])
end
it 'accepts end aligned with a class variable' do
inspect_source(cop,
['@@variable = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with a class variable' do
inspect_source(cop,
['@@variable = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `@@variable = test do |ala|`' \
' at 1, 0'])
end
it 'accepts end aligned with a global variable' do
inspect_source(cop,
['$variable = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with a global variable' do
inspect_source(cop,
['$variable = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `$variable = test do |ala|`' \
' at 1, 0'])
end
it 'accepts end aligned with a constant' do
inspect_source(cop,
['CONSTANT = test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with a constant' do
inspect_source(cop,
['Module::CONSTANT = test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with' \
' `Module::CONSTANT = test do |ala|` at 1, 0'])
end
it 'accepts end aligned with a method call' do
inspect_source(cop,
['parser.childs << lambda do |token|',
' token << 1',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with a method call' do
inspect_source(cop,
['parser.childs << lambda do |token|',
' token << 1',
' end'
])
expect(cop.messages)
.to eq(['`end` at 3, 2 is not aligned with' \
' `parser.childs << lambda do |token|` at 1, 0'])
end
it 'accepts end aligned with a method call with arguments' do
inspect_source(cop,
['@h[:f] = f.each_pair.map do |f, v|',
' v = 1',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched end with a method call' \
' with arguments' do
inspect_source(cop,
['@h[:f] = f.each_pair.map do |f, v|',
' v = 1',
' end'
])
expect(cop.messages)
.to eq(['`end` at 3, 2 is not aligned with' \
' `@h[:f] = f.each_pair.map do |f, v|` at 1, 0'])
end
it 'does not raise an error for nested block in a method call' do
inspect_source(cop,
['expect(arr.all? { |o| o.valid? })'
])
expect(cop.offenses).to be_empty
end
it 'accepts end aligned with the block when the block is a method argument' do
inspect_source(cop,
['expect(arr.all? do |o|',
' o.valid?',
' end)'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched end not aligned with the block' \
' that is an argument' do
inspect_source(cop,
['expect(arr.all? do |o|',
' o.valid?',
' end)'
])
expect(cop.messages)
.to eq(['`end` at 3, 2 is not aligned with `arr.all? do |o|` at 1, 7 or' \
' `expect(arr.all? do |o|` at 1, 0'])
end
it 'accepts end aligned with an op-asgn (+=, -=)' do
inspect_source(cop,
['rb += files.select do |file|',
' file << something',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with an op-asgn (+=, -=)' do
inspect_source(cop,
['rb += files.select do |file|',
' file << something',
' end'
])
expect(cop.messages)
.to eq(['`end` at 3, 2 is not aligned with `rb` at 1, 0'])
end
it 'accepts end aligned with an and-asgn (&&=)' do
inspect_source(cop,
['variable &&= test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with an and-asgn (&&=)' do
inspect_source(cop,
['variable &&= test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `variable &&= test do |ala|`' \
' at 1, 0'])
end
it 'accepts end aligned with an or-asgn (||=)' do
inspect_source(cop,
['variable ||= test do |ala|',
'end'
])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with an or-asgn (||=)' do
inspect_source(cop,
['variable ||= test do |ala|',
' end'
])
expect(cop.messages)
.to eq(['`end` at 2, 2 is not aligned with `variable ||= test do |ala|`' \
' at 1, 0'])
end
it 'accepts end aligned with a mass assignment' do
inspect_source(cop,
['var1, var2 = lambda do |test|',
' [1, 2]',
'end'
])
expect(cop.offenses).to be_empty
end
it 'accepts end aligned with a call chain left hand side' do
inspect_source(cop,
['parser.diagnostics.consumer = lambda do |diagnostic|',
' diagnostics << diagnostic',
'end'])
expect(cop.offenses).to be_empty
end
it 'registers an offense for mismatched block end with a mass assignment' do
inspect_source(cop,
['var1, var2 = lambda do |test|',
' [1, 2]',
' end'
])
expect(cop.messages)
.to eq(['`end` at 3, 2 is not aligned with `var1, var2` at 1, 0'])
end
end
| mit |
kilikkuo/py_simple_host_target | simple_host_target/simple_host_target/client.py | 1956 | import os
import sys
import socket
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
from simple_host_target.definition import OP_HT_DATA_BEGIN, OP_HT_DATA_END,\
OP_SH_DATA_PREFIX, OP_SH_DATA_POSTFIX,\
OP_SH_DATA_MIDFIX
class Client(object):
def __init__(self, ip = "127.0.0.1", port = 5000):
self.socket = socket.socket()
self.socket.connect((ip, port))
def shutdown(self):
if self.socket:
print(" Client goes down ... ")
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
self.socket = None
def send_sh_data(self, ip_port = "", serialized_task = ""):
# Sample data to be sent !
self.send(OP_SH_DATA_PREFIX)
self.send(ip_port)
self.send(OP_SH_DATA_MIDFIX)
self.send(serialized_task)
self.send(OP_SH_DATA_POSTFIX)
def send_ht_data(self, info_package):
# Sample data to be sent !
self.send(OP_HT_DATA_BEGIN)
self.send(info_package)
self.send(OP_HT_DATA_END)
def send(self, msg):
assert (self.socket != None)
data = bytearray(msg, "ASCII") if msg != None and type(msg) == str else msg
if data != None:
totalsent = 0
while totalsent < len(data):
sent = self.socket.send(data[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
print("%d bytes data has been sent successfully !"%(totalsent))
if __name__ == "__main__":
tc = Client()
tc2 = Client()
tc.send_ht_data()
tc2.send_ht_data("THIS IS A TEST !!!")
tc.shutdown()
tc2.shutdown()
| mit |
marcusdarmstrong/cloth-io | src/html-handler.js | 989 | // @flow
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { createStore } from 'redux';
import layout from './layout';
import App from './components/app';
import reducer from './reducer';
import onError from './util/on-error';
import { Map as map } from 'immutable';
const namespaces = {};
type Socket = {
of: (name: string) => string;
};
export default (io: Socket) => (handler: (req: Request) => Promise<Object>) =>
onError(async (req, res) => {
const state = map(await handler(req));
if (state.has('socket')) {
const socket = state.get('socket');
if (socket.has('name')) {
const name = socket.get('name');
namespaces[name] = io.of(name);
}
}
const store = createStore(reducer, state);
res.send(
layout(
state.get('title'),
ReactDOMServer.renderToString(<App store={store} />),
state
)
);
}, (req, res) => res.status(500).send('Something broke!'));
| mit |
vulcansteel/autorest | AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/HeadExceptions/HeadExceptionOperationsExtensions.cs | 4272 | // 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.
namespace Fixtures.Azure.AcceptanceTestsHeadExceptions
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
public static partial class HeadExceptionOperationsExtensions
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head200(this IHeadExceptionOperations operations)
{
Task.Factory.StartNew(s => ((IHeadExceptionOperations)s).Head200Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head200Async( this IHeadExceptionOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head204(this IHeadExceptionOperations operations)
{
Task.Factory.StartNew(s => ((IHeadExceptionOperations)s).Head204Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head204Async( this IHeadExceptionOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head204WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head404(this IHeadExceptionOperations operations)
{
Task.Factory.StartNew(s => ((IHeadExceptionOperations)s).Head404Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head404Async( this IHeadExceptionOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head404WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
}
}
| mit |
eberson/chunker-florestal | rule-extraction/src/main/java/br/usp/nlp/chunk/rule/extraction/identifiers/GramaticalCategory.java | 899 | package br.usp.nlp.chunk.rule.extraction.identifiers;
import static br.usp.nlp.chunk.rule.extraction.Constants.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GramaticalCategory implements ValueRecognizer{
@Override
public boolean apply(String content) {
return Pattern.matches(REGEX_GRAMATICAL_CHECK, content);
}
@Override
public String get(String content) {
if (!apply(content)){
return "";
}
Matcher matcher = Pattern.compile(REGEX_GRAMATICAL_EXTRACT).matcher(content);
if (matcher.find()){
return matcher.group();
}
return "";
}
public static void main(String[] args) {
// String value = "=ADVL:np";
String value = "==H:prop('Brasília' F S) Brasília";
GramaticalCategory syntagma = new GramaticalCategory();
System.out.println(syntagma.apply(value));
System.out.println(syntagma.get(value));
}
}
| mit |
Phyrra/javasql | src/main/java/ch/sama/sql/dbo/generator/ObjectGenerator.java | 5702 | package ch.sama.sql.dbo.generator;
import ch.sama.sql.dbo.Field;
import ch.sama.sql.dbo.IType;
import ch.sama.sql.dbo.Table;
import ch.sama.sql.dbo.schema.ISchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ObjectGenerator {
private static final Logger logger = LoggerFactory.getLogger(ObjectGenerator.class);
private Function<IType, Class<?>> typeConverter;
public ObjectGenerator(Function<IType, Class<?>> typeConverter) {
this.typeConverter = typeConverter;
}
public void generate(String srcFolder, String pkg, ISchema schema, Function<String, Boolean> filter) throws IOException {
generate(
srcFolder,
pkg,
schema.getTables().stream()
.filter(table -> filter.apply(table.getName()))
.collect(Collectors.toList())
);
}
public void generate(String srcFolder, String pkg, ISchema schema) throws IOException {
generate(srcFolder, pkg, schema.getTables());
}
public void generate(String srcFolder, String pkg, List<Table> tables) throws IOException {
for (Table table : tables) {
String className = getTableClassName(table);
BufferedWriter file = createClassFile(srcFolder, pkg, className);
try {
file.write("package " + pkg + ";\n\n");
file.write("import ch.sama.sql.dbo.result.obj.JpaObject;\n\n");
file.write("import ch.sama.sql.jpa.Entity;\n");
file.write("import ch.sama.sql.jpa.Column;\n");
file.write("import ch.sama.sql.jpa.PrimaryKey;\n");
file.write("import ch.sama.sql.jpa.AutoIncrement;\n\n");
file.write("import ch.sama.sql.jpa.Default;\n\n");
file.write("import java.util.UUID;\n");
file.write("import java.util.Date;\n\n");
file.write("@Entity\n");
file.write("public class " + className + " extends JpaObject {\n");
String fieldBlocks = table.getColumns().stream()
.map(this::generateFieldBlock)
.collect(Collectors.joining("\n\n"));
file.write(fieldBlocks);
file.write("}");
logger.debug("Generated: " + table.getName());
// don't catch, forward exception
} finally {
file.close();
}
}
}
private BufferedWriter createClassFile(String srcFolder, String pkg, String className) throws IOException {
String separator = System.getProperty("file.separator");
String path = pkg.replace(".", separator);
File file = new File(srcFolder + separator + path + separator + className + ".java");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), false);
BufferedWriter writer = new BufferedWriter(fileWriter);
return writer;
}
private String getTableClassName(Table table) {
String name = table.getName();
return Character.toString(name.charAt(0)).toUpperCase() + name.substring(1);
}
private String getFieldMemberName(Field field) {
String name = field.getName();
return Character.toString(name.charAt(0)).toLowerCase() + name.substring(1);
}
private String getFieldFunctionName(Field field) {
String name = field.getName();
return Character.toString(name.charAt(0)).toUpperCase() + name.substring(1);
}
private String generateFieldBlock(Field field) {
StringBuilder builder = new StringBuilder();
String type = typeConverter.apply(field.getDataType()).getSimpleName();
String memberName = getFieldMemberName(field);
String functionName = getFieldFunctionName(field);
if (field.isPrimaryKey()) {
builder.append("\t@PrimaryKey\n");
}
if (field.isAutoIncrement()) {
builder.append("\t@AutoIncrement\n");
}
if (field.hasDefaultValue()) {
builder.append(String.format("\t@Default(value = \"%s\")\n", field.getDefaultValue().getValue()));
}
if (field.isNullable()) {
builder.append(String.format("\t@Column(name = \"%s\", nullable = true)\n", field.getName()));
} else {
builder.append(String.format("\t@Column(name = \"%s\", nullable = false)\n", field.getName()));
}
builder.append(String.format("\tprivate %s %s;\n\n", type, memberName));
builder.append(String.format("\tpublic void set%s(%s arg) {\n", functionName, type));
builder.append(String.format("\t\tthis.%s = arg;\n", memberName));
builder.append("\t}\n\n");
builder.append(String.format("\tpublic %s get%s() {\n", type, functionName));
builder.append(String.format("\t\treturn %s;\n", memberName));
builder.append("\t}");
return builder.toString();
}
} | mit |
selvasingh/azure-sdk-for-java | sdk/loganalytics/mgmt-v2020_08_01/src/main/java/com/microsoft/azure/management/loganalytics/v2020_08_01/implementation/OperationStatusesInner.java | 7065 | /**
* 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.
*/
package com.microsoft.azure.management.loganalytics.v2020_08_01.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.CloudException;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in OperationStatuses.
*/
public class OperationStatusesInner {
/** The Retrofit service to perform REST calls. */
private OperationStatusesService service;
/** The service client containing this operation class. */
private OperationalInsightsManagementClientImpl client;
/**
* Initializes an instance of OperationStatusesInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public OperationStatusesInner(Retrofit retrofit, OperationalInsightsManagementClientImpl client) {
this.service = retrofit.create(OperationStatusesService.class);
this.client = client;
}
/**
* The interface defining all the services for OperationStatuses to be
* used by Retrofit to perform actually REST calls.
*/
interface OperationStatusesService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.loganalytics.v2020_08_01.OperationStatuses get" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.OperationalInsights/locations/{location}/operationStatuses/{asyncOperationId}")
Observable<Response<ResponseBody>> get(@Path("location") String location, @Path("asyncOperationId") String asyncOperationId, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Get the status of a long running azure asynchronous operation.
*
* @param location The region name of operation.
* @param asyncOperationId The operation Id.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the OperationStatusInner object if successful.
*/
public OperationStatusInner get(String location, String asyncOperationId) {
return getWithServiceResponseAsync(location, asyncOperationId).toBlocking().single().body();
}
/**
* Get the status of a long running azure asynchronous operation.
*
* @param location The region name of operation.
* @param asyncOperationId The operation Id.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<OperationStatusInner> getAsync(String location, String asyncOperationId, final ServiceCallback<OperationStatusInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(location, asyncOperationId), serviceCallback);
}
/**
* Get the status of a long running azure asynchronous operation.
*
* @param location The region name of operation.
* @param asyncOperationId The operation Id.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the OperationStatusInner object
*/
public Observable<OperationStatusInner> getAsync(String location, String asyncOperationId) {
return getWithServiceResponseAsync(location, asyncOperationId).map(new Func1<ServiceResponse<OperationStatusInner>, OperationStatusInner>() {
@Override
public OperationStatusInner call(ServiceResponse<OperationStatusInner> response) {
return response.body();
}
});
}
/**
* Get the status of a long running azure asynchronous operation.
*
* @param location The region name of operation.
* @param asyncOperationId The operation Id.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the OperationStatusInner object
*/
public Observable<ServiceResponse<OperationStatusInner>> getWithServiceResponseAsync(String location, String asyncOperationId) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (asyncOperationId == null) {
throw new IllegalArgumentException("Parameter asyncOperationId is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.get(location, asyncOperationId, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<OperationStatusInner>>>() {
@Override
public Observable<ServiceResponse<OperationStatusInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<OperationStatusInner> clientResponse = getDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<OperationStatusInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<OperationStatusInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<OperationStatusInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
quteron/algorithmify | algorithms/sorting/comparison-sort/bubble-sort/bubble-sort.js | 3644 | /*
* Implementation of the Bubble Sort algorithm using JavaScript programming language.
* Copyright (c) 2016 Quteron
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function () {
/**
* Swaps two elements in an array by their indexes.
* @param {Array} array original array
* @param {int} i index of the first element to swap
* @param {int} j index of the second element to swap
* @return {void}
*/
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
* Checks whether first passed element is less than second passed element.
* @param {int} a first element to compare
* @param {int} b second element to compare
* @return {boolean} true if first element is less than second, otherwise - false.
*/
function less(a, b) {
return a < b;
}
/**
* Checks whether passed array is sorted.
* @param {Array} array to be checked
* @param {int} lo index of the first element to be sorted
* @param {int} hi index of the last element to be sorted
* @return {boolean} true if array is sorted, otherwise - false.
*/
function sorted(array, lo, hi) {
var n = array.length,
i;
if (lo === undefined) {
lo = 0;
}
if (hi === undefined) {
hi = n - 1;
}
for (i = lo; i <= hi; i++) {
if (less(array[i], array[i - 1])) {
return false;
}
}
return true;
}
/**
* Sorts in-place an array using bubble sort algorithm.
* @param {Array} array original array to be sort
* @param lo index of the first element to be sorted
* @param hi index of the last element to be sorted
* @return {Array} sorted array
*/
function sort(array, lo, hi) {
var n = array.length,
k = 0,
i, swapped;
if (lo === undefined) {
lo = 0;
}
if (hi === undefined) {
hi = n - 1;
}
do {
swapped = false;
for (i = lo; i < hi - k; i++) {
if (less(array[i + 1], array[i])) {
swap(array, i + 1, i);
swapped = true;
}
}
k++;
} while (swapped);
return array;
}
var a1 = [5, 2, 1, 3, 4];
sort(a1);
console.log(sorted(a1));
console.log(a1); // [1, 2, 3, 4, 5]
var a2 = [5, 2, 1, 3, 4];
sort(a2, 1, 3);
console.log(a2); // [5, 1, 2, 3, 4]
}());
| mit |
choodur/aviator | test/aviator/openstack/compute/v2/admin/bulk_delete_floating_ips_test.rb | 2540 | require 'test_helper'
class Aviator::Test
describe 'aviator/openstack/compute/v2/admin/bulk_delete_floating_ips' do
def create_request(session_data = get_session_data, &block)
block ||= lambda do |p|
p[:ip_range] = '192.168.6.56/29'
end
klass.new(session_data, &block)
end
def get_session_data
session.send :auth_info
end
def helper
Aviator::Test::RequestHelper
end
def klass
@klass ||= helper.load_request('openstack', 'compute', 'v2', 'admin', 'bulk_delete_floating_ips.rb')
end
def session
unless @session
@session = Aviator::Session.new(
config_file: Environment.path,
environment: 'openstack_admin'
)
@session.authenticate
end
@session
end
validate_attr :anonymous? do
klass.anonymous?.must_equal false
end
validate_attr :api_version do
klass.api_version.must_equal :v2
end
validate_attr :body do
klass.body?.must_equal true
create_request.body?.must_equal true
end
validate_attr :endpoint_type do
klass.endpoint_type.must_equal :admin
end
validate_attr :headers do
session_data = get_session_data
headers = { 'X-Auth-Token' => session_data.token }
request = create_request(session_data)
request.headers.must_equal headers
end
validate_attr :http_method do
create_request.http_method.must_equal :put
end
validate_attr :url do
session_data = get_session_data
service_spec = session_data[:catalog].find{|s| s[:type] == 'compute' }
url = "#{ service_spec[:endpoints].find{|a| a[:interface] == 'admin'}[:url] }/os-floating-ips-bulk/delete"
request = create_request
request.url.must_equal url
end
validate_response 'valid parameters are provided' do
response = session.compute_service.request :bulk_delete_floating_ips do |params|
params[:ip_range] = '192.168.7.56/29'
end
response.status.must_equal 200
response.body.wont_be_nil
response.body[:floating_ips_bulk_delete].wont_be_nil
response.headers.wont_be_nil
end
validate_response 'invalid parameters are provided' do
response = session.compute_service.request :bulk_delete_floating_ips do |params|
params[:ip_range] = 'this-is-invalid!'
end
response.status.must_equal 400
response.body.wont_be_nil
response.headers.wont_be_nil
end
end
end
| mit |
webforge-labs/minimock | bootstrap.php | 455 | <?php
use Psc\Boot\BootLoader;
/**
* Bootstrap and Autoload whole application
*
* you can use this file to bootstrap for tests or bootstrap for scripts / others
*/
$ds = DIRECTORY_SEPARATOR;
require_once __DIR__.$ds.'lib'.$ds.'package.boot.php';
$bootLoader = new BootLoader(__DIR__, 'Webforge\Setup\BootContainer');
$bootLoader->loadComposer();
$container = $bootLoader->registerContainer();
$bootLoader->registerPackageRoot();
return $container; | mit |
dcastro/JSendWebApi | tests/JSend.WebApi.Tests/JSendAuthorizeAttributeTests.cs | 3042 | using System;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using FluentAssertions;
using JSend.WebApi.Properties;
using JSend.WebApi.Responses;
using JSend.WebApi.Tests.FixtureCustomizations;
using Newtonsoft.Json;
using Xunit;
namespace JSend.WebApi.Tests
{
public class JSendAuthorizeAttributeTests
{
public class TestableJSendAuthorizeAttribute : JSendAuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//skip null-check for actionContext at this stage
//in order to verify that HandleUnauthorizedRequest performs a null-check itself
//automatically fail authorization
base.HandleUnauthorizedRequest(actionContext);
}
}
[Theory, JSendAutoData]
public void IsAuthorizeAttribute(JSendAuthorizeAttribute attribute)
{
// Exercise system and verify outcome
attribute.Should().BeAssignableTo<JSendAuthorizeAttribute>();
}
[Theory, JSendAutoData]
public void ThrowsWhenContextIsNull(TestableJSendAuthorizeAttribute attribute)
{
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() => attribute.OnAuthorization(null));
}
[Theory, JSendAutoData]
public void CreatesResponse(HttpActionContext context, TestableJSendAuthorizeAttribute attribute)
{
// Fixture setup
context.Response = null;
// Exercise system
attribute.OnAuthorization(context);
// Verify outcome
context.Response.Should().NotBeNull();
}
[Theory, JSendAutoData]
public async Task CreatesFailResponse(HttpActionContext context, TestableJSendAuthorizeAttribute attribute)
{
// Fixture setup
var expectedMessage = JsonConvert.SerializeObject(new FailResponse(StringResources.RequestNotAuthorized));
// Exercise system
attribute.OnAuthorization(context);
// Verify outcome
var message = await context.Response.Content.ReadAsStringAsync();
message.Should().Be(expectedMessage);
}
[Theory, JSendAutoData]
public void SetsStatusCode(HttpActionContext context, TestableJSendAuthorizeAttribute attribute)
{
// Exercise system
attribute.OnAuthorization(context);
// Verify outcome
context.Response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Theory, JSendAutoData]
public void SetsContentTypeHeader(HttpActionContext context, TestableJSendAuthorizeAttribute attribute)
{
// Exercise system
attribute.OnAuthorization(context);
// Verify outcome
context.Response.Content.Headers.ContentType.MediaType.Should().Be("application/json");
}
}
}
| mit |
Fafa87/EP | ep/evalplatform/gather_results.py | 14971 | import shutil
from PIL import Image
from ep.evalplatform.create_report import create_report, create_sensible_report
from ep.evalplatform.plotting import Plotter
from ep.evalplatform.utils import *
images_sufixes = [SEGPLOT_SUFFIX, TRACKPLOT_SUFFIX]
SUMMARY_GNUPLOT_FILE = "plot_summary.plt"
terminal_type = "png"
def join2(path):
border = 5
imA = Image.open(os.path.join(path, "M1.png"))
imB = Image.open(os.path.join(path, "M2.png"))
image_size = imA.size
half_size = (image_size[0] // 2, image_size[1] // 2)
imA = imA.resize(half_size, Image.ANTIALIAS)
imB = imB.resize(half_size, Image.ANTIALIAS)
merged = Image.new('RGB', (2 * border + image_size[0], 2 * border + half_size[1]))
merged.paste(imA, (border, border))
merged.paste(imB, (border + half_size[0], border))
merged.save(os.path.join(path, "Glued.png"))
def join4(path):
border = 5
imA = Image.open(os.path.join(path, "M1.png"))
imB = Image.open(os.path.join(path, "M2.png"))
imC = Image.open(os.path.join(path, "M3.png"))
imD = Image.open(os.path.join(path, "M4.png"))
image_size = imA.size
half_size = (image_size[0] // 2, image_size[1] // 2)
imA = imA.resize(half_size, Image.ANTIALIAS)
imB = imB.resize(half_size, Image.ANTIALIAS)
imC = imC.resize(half_size, Image.ANTIALIAS)
imD = imD.resize(half_size, Image.ANTIALIAS)
merged = Image.new('RGB', (2 * border + half_size[0] * 2, 2 * border + half_size[1] * 2))
merged.paste(imA, (border, border))
merged.paste(imB, (border + half_size[0], border))
merged.paste(imC, (border, border + half_size[1]))
merged.paste(imD, (border + half_size[0], border + half_size[1]))
merged.save(os.path.join(path, "Glued.png"))
def join6(path):
border = 5
imA = Image.open(os.path.join(path, "M1.png"))
imB = Image.open(os.path.join(path, "M2.png"))
imC = Image.open(os.path.join(path, "M3.png"))
imD = Image.open(os.path.join(path, "M4.png"))
imE = Image.open(os.path.join(path, "M5.png"))
if os.path.isfile(os.path.join(path, "M6.png")):
imF = Image.open(os.path.join(path, "M6.png"))
image_size = imA.size
half_size = (image_size[0] // 2, image_size[1] // 2)
imA = imA.resize(half_size, Image.ANTIALIAS)
imB = imB.resize(half_size, Image.ANTIALIAS)
imC = imC.resize(half_size, Image.ANTIALIAS)
imD = imD.resize(half_size, Image.ANTIALIAS)
imE = imE.resize(half_size, Image.ANTIALIAS)
if os.path.isfile(os.path.join(path, "M6.png")):
imF = imF.resize(half_size, Image.ANTIALIAS)
merged = Image.new('RGB', (2 * border + half_size[0] * 3, 2 * border + half_size[1] * 2), "white")
merged.paste(imA, (border, border))
merged.paste(imB, (border + half_size[0], border))
merged.paste(imC, (border + half_size[0] * 2, border))
merged.paste(imD, (border, border + half_size[1]))
merged.paste(imE, (border + half_size[0], border + half_size[1]))
if os.path.isfile(os.path.join(path, "M6.png")):
merged.paste(imF, (border + half_size[0] * 2, border + half_size[1]))
merged.save(os.path.join(path, "Glued.png"))
imageglue_functions = {2: join2, 4: join4, 6: join6}
def read_algorithm_name(summary_path):
summary_file = open(summary_path, "rU")
linia = summary_file.readlines()[0]
summary_file.close()
return linia[len("Algorithm: "):].strip()
def check_existance(files, filter, get_path=None):
existing_files = []
for file in files:
get_path = get_path or (lambda x: x)
file_path = get_path(file)
if os.path.isfile(file_path) == 0:
debug_center.show_in_console(None, "Warning", "".join(["WARNING: ", "File don't exist: " + file_path]))
else:
existing_files.append(file)
if filter == 0:
return files
return existing_files
def run_show_results(showSuccess, showFailed, result):
if result == 0:
debug_center.show_in_console(None, "Info", showSuccess)
else:
debug_center.show_in_console(None, "Error", showFailed)
def create_additional_plots(title, name_data_paths, set_number, output_name):
"""
@param set_number: first element is 0
"""
try:
if not name_data_paths:
return -1
if len(name_data_paths) > 50:
debug_center.show_in_console(None, "Warning",
"WARNING: Too many plots given, merged plot would not make any sense.")
return -1
# Extract data from all the algorithms.
name_data = [(name, read_from_file(path)) for (name, path) in name_data_paths]
# Create data for the plot.
names, algo_datasets = zip(*name_data)
datasets = [datasets[set_number] for datasets in algo_datasets]
tmp_file = "create_additional_plots.tmp"
write_to_file(datasets, tmp_file)
plt_filename = package_path(SUMMARY_GNUPLOT_FILE, 0)
with Plotter(terminal_type, plt_filename, title) as plotter:
debug_center.show_in_console(None, "Progress", "".join(["Ploting " + output_name + "..."]))
plotter.setup_ploting_area(wide_plots, datasets[0])
plotter.use_generic_plots(names)
plotter.plot_it(tmp_file, output_name)
debug_center.show_in_console(None, "Progress", "".join(["Ploting done..."]))
# Clean up the mess
os.remove(tmp_file)
return 0
except IOError as e:
debug_center.show_in_console(None, "Error", ("ERROR: Could not create cross plot: {}".format(e)))
return -1
def merge_txt(file_paths, output):
results = []
for file in file_paths:
file = open(file, "rU")
results.append(file.readlines())
file.close()
merged_results = "\n\n".join(["".join(res) for res in results])
file = open(output, "w")
file.write(merged_results)
file.close()
def merge_images(images_paths, results_folder, output):
if len(images_paths) == 0:
debug_center.show_in_console(None, "Error", "".join(["ERROR: ", "No plots given"]))
return -1
elif len(images_paths) == 1:
debug_center.show_in_console(None, "Error",
"".join(["ERROR: ", "Too few plots (2 required): ", str(len(images_paths))]))
return -1
elif len(images_paths) == 3:
debug_center.show_in_console(None, "Warning", "".join(
["WARNING: ", "Too many plots given (2 expected): ", str(len(images_paths))]))
debug_center.show_in_console(None, "Warning", "".join(["WARNING: ", "Only first 2 are considered."]))
images_paths = images_paths[:2]
elif len(images_paths) == 5:
debug_center.show_in_console(None, "Warning", "".join(
["WARNING: ", "Too many plots given (4 expected): ", str(len(images_paths))]))
debug_center.show_in_console(None, "Warning", "".join(["WARNING: ", "Only first 4 are considered."]))
images_paths = images_paths[:4]
elif len(images_paths) > 6:
debug_center.show_in_console(None, "Warning", "".join(
["WARNING: ", "Too many plots given (6 expected): ", str(len(images_paths))]))
debug_center.show_in_console(None, "Warning", "".join(["WARNING: ", "Only first 6 are considered."]))
images_paths = images_paths[:6]
for i in range(len(images_paths)):
shutil.copy(images_paths[i], os.path.join(results_folder, "M" + str(i + 1) + ".png"))
# join images pipeline
try:
spaces = len(images_paths)
imageglue_functions[spaces](results_folder)
shutil.move(os.path.join(results_folder, "Glued.png"), output)
except Exception as e:
debug_center.show_in_console(None, "Error",
"ERROR: Could not run PIL to merge plots: {0} {1}".format(sys.exc_info()[0], e))
return -1
for i in range(len(images_paths)):
os.remove(os.path.join(results_folder, "M" + str(i + 1) + ".png"))
return 0
def run_script(args):
global terminal_type, wide_plots
if len(args) % 2 == 0 and len(args) < 4:
print("".join(["Wrong number (" + str(len(args) - 1) + ") of arguments (1+2(1+k) required)."]))
print(args)
print("".join(["Program usage: gather_results.py <results_folder> [<algorithm_subpath> <algorithm_name>]x+"]))
else:
debug_center.configure(CONFIG_FILE)
if read_ini(CONFIG_FILE, 'plot', 'terminal') != '':
terminal_type = read_ini(CONFIG_FILE, 'plot', 'terminal').strip()
if read_ini(CONFIG_FILE, 'plot', 'wideplots') != '':
wide_plots = bool(int(read_ini(CONFIG_FILE, 'plot', 'wideplots')))
algorithm_number = (len(args) - 1) // 2
results_folder = args[1]
algorithm_results = []
for i in range(algorithm_number):
algorithm_results.append((args[2 + i * 2], args[2 + i * 2 + 1]))
# Calculate image paths and check existance
summaries_paths = []
algorithms_surname = [] # now taken from summary files
images_paths = []
segmentation_data_paths = []
tracking_data_paths = []
for (algo_results, algo_name) in algorithm_results:
summary_path = os.path.join(results_folder, algo_results, algo_name + SUMMARY_SUFFIX)
segmentation_data_path = os.path.join(results_folder, algo_results, algo_name + SEGPLOTDATA_SUFFIX)
tracking_data_path = os.path.join(results_folder, algo_results, algo_name + TRACKPLOTDATA_SUFFIX)
result_paths = [os.path.join(results_folder, algo_results, algo_name + sufix) for sufix in images_sufixes]
# we require summary file for algorithm name
if check_existance([summary_path], 1):
algorithms_surname.append(read_algorithm_name(summary_path))
summaries_paths.append(summary_path)
segmentation_data_paths.append(segmentation_data_path)
tracking_data_paths.append(tracking_data_path)
images_paths += result_paths
summaries_paths = check_existance(summaries_paths, 1)
images_paths = check_existance(images_paths, 1)
segmentation_data = check_existance(zip(algorithms_surname, segmentation_data_paths), 1, lambda x: x[1])
tracking_data = check_existance(zip(algorithms_surname, tracking_data_paths), 1, lambda x: x[1])
debug_center.show_in_console(None, "Progress", "Merging files...")
# Merge summaries
merge_txt(summaries_paths, os.path.join(results_folder, "Summary.txt"))
debug_center.show_in_console(None, "Progress", "Summaries merged")
# Produce additional report
create_report(os.path.join(results_folder, "Summary.txt"), 4, "csv", os.path.join(results_folder, "Report.csv"))
create_sensible_report(os.path.join(results_folder, "Summary.txt"), 4,
os.path.join(results_folder, "Sensible Report.csv"))
debug_center.show_in_console(None, "Progress", "CSV summary created")
# Merge images (using Image module)
if terminal_type != "svg":
result_merged_segmentation = merge_images([p for p in images_paths if p.endswith(SEGPLOT_SUFFIX)],
results_folder,
os.path.join(results_folder, "Plot_segmentation.png"))
run_show_results("Segmentation plots merged", "Segmentation plots NOT merged", result_merged_segmentation)
result_merged_tracking = merge_images([p for p in images_paths if p.endswith(TRACKPLOT_SUFFIX)],
results_folder, os.path.join(results_folder, "Plot_tracking.png"))
run_show_results("Tracking plots merged", "Tracking plots NOT merged", result_merged_tracking)
else:
debug_center.show_in_console(None, "Info",
"Skipping merging plots as it is unavailable for '" + terminal_type + "' plotting terminal.")
debug_center.show_in_console(None, "Progress", "...merging done")
debug_center.show_in_console(None, "Progress", "Additional cross-algorithm ploting...")
# Create additional cross-algorithm plots
# F value for all algorithms for segmentation
# Precision
# Recall
plot_success = create_additional_plots("F value for segmentation", segmentation_data, 3,
os.path.join(results_folder, "Plot_segmentation_F_summary.png"))
run_show_results("Segmentation F value comparison plot was created...",
"Segmentation F value comparison plot was NOT created...", plot_success)
plot_success = create_additional_plots("Precision of segmentation", segmentation_data, 1,
os.path.join(results_folder, "Plot_segmentation_precision_summary.png"))
run_show_results("Segmentation precision comparison plot was created...",
"Segmentation precision comparison plot was NOT created...", plot_success)
plot_success = create_additional_plots("Recall value for segmentation", segmentation_data, 2,
os.path.join(results_folder, "Plot_segmentation_recall_summary.png"))
run_show_results("Segmentation recall value comparison plot was created...",
"Segmentation recall value comparison plot was NOT created...", plot_success)
# F value for all algorithms for tracking
# Precision
# Recall
plot_success = create_additional_plots("F value for tracking", tracking_data, 2,
os.path.join(results_folder, "Plot_tracking_F_summary.png"))
run_show_results("Tracking F value comparison plot was created",
"Tracking F value comparison plot was NOT created", plot_success)
plot_success = create_additional_plots("Precision of tracking", tracking_data, 0,
os.path.join(results_folder, "Plot_tracking_precision_summary.png"))
run_show_results("Tracking precision comparison plot was created...",
"Tracking precision comparison plot was NOT created...", plot_success)
plot_success = create_additional_plots("Recall value for tracking", tracking_data, 1,
os.path.join(results_folder, "Plot_tracking_recall_summary.png"))
run_show_results("Tracking recall value comparison plot was created...",
"Tracking recall value comparison plot was NOT created...", plot_success)
debug_center.show_in_console(None, "Progress", "...ploting done")
if __name__ == '__main__':
run_script(sys.argv)
| mit |
dchq/dchq-core | app/models/store.rb | 17809 | class Store < ActiveRecord::Base
has_paper_trail
include CurrentUserInfo
belongs_to :company
belongs_to :currency
has_and_belongs_to_many :users
has_many :certification_levels
has_many :certification_level_costs
has_many :payment_methods
has_many :tax_rates
has_many :commission_rates
has_many :event_trips
has_many :events
has_many :course_events
has_many :other_events
has_many :event_customer_participants, through: :sales
has_many :customer_participants, through: :events
has_many :boats, class_name: "Stores::Boat"
has_many :events_with_boats, through: :boats, source: :events, order: :starts_at
has_many :working_times, class_name: "Stores::WorkingTime"
has_many :event_tariffs, class_name: "Stores::EventTariff"
has_many :finance_reports, class_name: "Stores::FinanceReport"
has_many :invoices, class_name: "Stores::Invoice"
has_many :credits, class_name: "Stores::Credit"
has_one :email_setting, class_name: "Stores::EmailSetting"
has_many :kit_hires, class_name: "ExtraEvents::KitHire"
has_many :transports, class_name: "ExtraEvents::Transport"
has_many :insurances, class_name: "ExtraEvents::Insurance"
has_many :additionals, class_name: "ExtraEvents::Additional"
has_many :type_of_services, class_name: "Services::TypeOfService"
has_many :service_kits, class_name: "Services::ServiceKit"
has_many :services
has_many :categories
has_many :brands
has_many :products
has_many :miscellaneous_products
has_many :sales
has_many :sale_customers, through: :sales
has_many :sale_products, through: :sales
has_many :credit_notes, through: :sales
has_many :tills, dependent: :destroy
has_many :sold_products, through: :sales, source: :products do
def week_ago
where(sale_products: { :created_at.gt => 1.week.ago })
end
def brand_ids
select("DISTINCT(brand_id)")
end
def category_ids
select("DISTINCT(category_id)")
end
end
has_many :payments, through: :sales
has_many :rental_products
has_many :rentals
has_many :renteds, through: :rentals
has_one :xero, class_name: "Stores::Xero"
has_one :scuba_tribe, class_name: 'Stores::ScubaTribe'
has_one :avatar, as: :imageable, class_name: "Image", dependent: :destroy
accepts_nested_attributes_for :avatar, allow_destroy: true
accepts_nested_attributes_for :email_setting
with_options allow_destroy: true do |ad|
ad.accepts_nested_attributes_for :type_of_services, reject_if: ->(pm){ pm[:name].blank? }
ad.accepts_nested_attributes_for :boats
ad.accepts_nested_attributes_for :service_kits, reject_if: ->(pm){ pm[:name].blank? }
ad.accepts_nested_attributes_for :payment_methods, reject_if: ->(pm){ pm[:name].blank? }
ad.accepts_nested_attributes_for :event_tariffs, reject_if: ->(pm){ pm[:name].blank? }
ad.accepts_nested_attributes_for :xero
ad.accepts_nested_attributes_for :finance_reports
ad.accepts_nested_attributes_for :tills
ad.with_options reject_if: ->(rate){ rate[:amount].blank? } do |ri|
ri.accepts_nested_attributes_for :tax_rates
ri.accepts_nested_attributes_for :commission_rates
end
ad.accepts_nested_attributes_for :certification_levels, reject_if: ->(pm){ pm[:name].blank? }
ad.with_options reject_if: ->(pricing){ pricing[:name].blank? && pricing[:cost].blank? } do |ri|
ri.accepts_nested_attributes_for :event_trips
ri.accepts_nested_attributes_for :kit_hires
ri.accepts_nested_attributes_for :transports
ri.accepts_nested_attributes_for :insurances
ri.accepts_nested_attributes_for :additionals
end
end
with_options presence: true do |o|
o.validates :company
o.validates :name, length: { maximum: 255 }
o.validates :location
o.validates :time_zone, inclusion: { in: ActiveSupport::TimeZone.all.map(&:name) }
o.validates :currency
o.validates :public_key, uniqueness: true
o.validates :api_key, uniqueness: true
o.validates :printer_type, inclusion: { in: ->(s){ Store.printer_types.keys } }
o.validates :calendar_type, inclusion: { in: ->(s){ Store.calendar_types.keys } }
#TODO add to tests
o.validates :tsp_url, if: ->(u){ u.printer_type.eql?('tsp') }
o.validate :invoice_id, unless: ->(u){ u.main }
end
validates :standart_rental_term, length: { maximum: 65536 }
validates :calendar_header, length: { maximum: 65536 }
validates :calendar_footer, length: { maximum: 65536 }
validates :invoice_title, length: { maximum: 255 }
validates :receipt_title, length: { maximum: 255 }
validates :initial_receipt_number, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, allow_blank: true
scope :extra, ->{ where(main: false) }
#TODO Remek scope
scope :enable_low_inventory_email, ->{ joins(:email_setting).where( email_setting: { disable_low_inventory_product_reminder_email: false } ) }
attr_accessible :company_id, :name, :location, :currency, :currency_id, :printer_type, :time_zone, :main,
:invoice_id, :calendar_type, :standart_term, :barcode_printing_type, :tax_rate_inclusion,
:email_setting_attributes, :type_of_services_attributes, :boats_attributes,
:service_kits_attributes, :payment_methods_attributes, :event_tariffs_attributes,
:avatar_attributes, :xero_attributes, :tax_rates_attributes, :commission_rates_attributes,
:certification_levels_attributes, :event_trips_attributes, :transports_attributes,
:insurances_attributes, :kit_hires_attributes, :additionals_attributes, :tsp_url,
:finance_reports_attributes, :tills_attributes, :standart_rental_term, :invoice_title, :receipt_title,
:calendar_header, :calendar_footer, :initial_receipt_number
class << self
def calendar_types
{"agendaDay" => I18n.t('models.store.calendar_type.day'),
"agendaWeek" => I18n.t('models.store.calendar_type.week'),
"month" => I18n.t('models.store.calendar_type.month') }
end
def printer_types
{
"80mm" => I18n.t('models.store.printer_types.80mm'),
"70mm" => I18n.t('models.store.printer_types.70mm'),
"tsp" => I18n.t('models.store.printer_types.tsp')
}
end
def barcode_printing_type
{ a4: I18n.t('models.store.barcode_printing_types.a4'),
zebra: I18n.t('models.store.barcode_printing_types.zebra') }
end
end
def all_events type
events = []
if type == 'all_events' || type == 'additionals'
events += additionals.with_costs
events += insurances.with_costs
events += kit_hires.with_costs
events += transports.with_costs
end
if type == 'all_events' || type == 'certification_levels'
events += get_certification_levels_with_costs
end
if type == 'all_events' || type == 'trips'
events += event_trips.with_costs
end
events.sort{|a,b| a['name'] <=> b['name']}
end
before_validation :generate_keys, on: :create
before_validation :smart_add_tsp_url_protocol
after_create :create_requirements
before_destroy :check_main_store, if: -> { ENV['from_rake_task'].blank? }
after_destroy :destroy_all_childrens
after_destroy :remove_invoice, if: ->{ ENV['from_rake_task'].blank? }
def tax_rates_list
tax_rates.map{ |tr| [tr.amount, tr.id] }
end
def commission_rates_list
commission_rates.map{ |cr| [cr.amount, cr.id] }
end
def line_chart
grouped_sales = sales.completed_for_current_month.group_by{ |s| "#{s.created_at.month}-#{s.created_at.day}" }
trend_data = date_interval.map.with_index{ |d, index| [index+1, grouped_sales[d] ? grouped_sales[d].map(&:grand_total).sum.to_f.round(2) : 0.0] }
trend_data
end
def get_certification_levels_with_costs
certification_levels.with_cost
end
def search_events q
result = events.search(q).map{|u| {name: "#{u.name} (#{u.event_short_time})", type: u.class.name.downcase, id: u.id }}
result += products.search(q).map{|u| {name: "#{u.name} (#{u.sku_code})", type: u.class.name.downcase, id: u.id }}
result += services.search(q).map{|u| {name: "#{u.kit} (#{u.serial_number})".truncate(30), type: u.class.name.downcase, id: u.id }}
end
def get_credit_note_payment_method
payment_methods.find_by_name("Credit Note")
end
def has_service_settings?
!type_of_services.blank?
end
def sale_products_for_current_month_in_numbers
sale_products.where(sale_id: sales_per_current_month).only_products.count
end
def sale_services_for_current_month_in_numbers
sale_products.where(sale_id: sales_per_current_month).only_services.count
end
def sale_events_for_current_month_in_numbers
@sale_events_for_current_month_in_number ||= sale_products.where(sale_productable_type: 'EventCustomerParticipant', sale_id: sales_per_current_month).count
end
def rentals_for_current_month_in_numbers
@rentals_for_current_month_in_numbers ||= renteds.where(rental_id: rentals_per_current_month).count
end
def total_sales_for_current_month_in_numbers
sale_events_for_current_month_in_numbers +
sale_products.where(sale_id: sales_per_current_month).count +
rentals_for_current_month_in_numbers
end
def sale_products_for_current_month_in_percentage
return 0 if total_sales_for_current_month_in_numbers.zero?
sale_products_for_current_month_in_numbers * 100 / total_sales_for_current_month_in_numbers
end
def sale_events_for_current_month_in_percentage
return 0 if total_sales_for_current_month_in_numbers.zero?
sale_events_for_current_month_in_numbers * 100 / total_sales_for_current_month_in_numbers
end
def sale_services_for_current_month_in_percentage
return 0 if total_sales_for_current_month_in_numbers.zero?
sale_services_for_current_month_in_numbers * 100 / total_sales_for_current_month_in_numbers
end
def rentals_for_current_month_in_percentage
return 0 if total_sales_for_current_month_in_numbers.zero?
rentals_for_current_month_in_numbers * 100 / total_sales_for_current_month_in_numbers
end
def generate_sale_targets_for_chart
data = []
sales_completed = sales.completed.for_this_period(Date.today.beginning_of_month)
company.users.where(sale_target_show_dashboard: true).each do |user|
data << [[user.sale_target.to_f, sales_completed.select{ |s| s.creator_id == user.id }.map(&:grand_total).sum.to_f], user.full_name ]
end
data
end
def close?
add_working_time if working_times.blank?
!working_times.last.close_at.blank?
end
def closed_info
working_time = working_times.last
{user_full_name: working_time.closed_user.full_name, time: working_time.close_at, open_time: working_time.open_at }
end
def xero_connected?
create_xero if xero.blank?
return false if xero.xero_consumer_key.blank? or xero.xero_consumer_secret.blank?
true
end
def scubatribe_connected?
!!scuba_tribe.try(:api_key)
end
def send_product_reminder_email
products_list = products.need_to_remind
StoreMailer.delay.remind_product(self, products_list)
products_list.update_all(sent_at: Time.now)
end
def set_close!
@working_time = working_times.last
transaction do
@working_time.update_attributes close_at: Time.now, closed_user: current_user_info
generate_invoice
generate_credit
end
close?
end
def reopen!
working_time = working_times.last
return unless working_time.open_at.today?
transaction do
working_time.tap do |w|
w.close_at = nil
w.closed_user = nil
w.opened_user = current_user_info
w.save(validate: false)
end
working_time.finance_report.each do |report|
if report.sent?
xero = Xero.new(self)
xero.delete_report(report)
end
report.destroy
end
end
end
def average_sale_per_customer
customers_count = customes_with_sales_this_month
customers_count = customers_count.eql?(0) ? 1 : customers_count
revenue_this_month.to_f / customers_count
end
def services_complete_this_month
services.complete.where(created_at: Time.now.beginning_of_month .. Time.now).count
end
def revenue_this_month
sales.sales_without_refunded_childs_per_month.sum(:grand_total)
end
def event_registrations_this_month
event_customer_participants.where(created_at: Time.now.beginning_of_month .. Time.now).count
end
def customers_this_month
customer_participants.where(created_at: Time.now.beginning_of_month .. Time.now).count
end
def has_epay_payment_method?
!payment_methods.where(name: 'Epay').blank?
end
private
def sales_per_current_month
@sales_per_current_month ||= sales.completed_for_current_month
end
def rentals_per_current_month
@rentals_per_current_month ||= rentals.completed_for_current_month
end
def customes_with_sales_this_month
SaleCustomer.where(sale_id: sales_per_current_month).uniq.count
end
def total_store_revenue
sales.sales_without_refunded_childs_all_time.sum(:grand_total)
end
def create_requirements
create_default_sales
add_managers_to_store
add_payment_methods
add_working_time
add_email_settings
end
def date_interval
(Date.today.beginning_of_month.to_date..Date.today).to_a.map{|d| "#{d.month}-#{d.day}"}
end
def generate_keys
self.public_key = Digest::SHA2.hexdigest("#{Time.now}--#{self.name}")
self.api_key = Digest::SHA2.hexdigest("#{Time.now}--#{self.name}")
end
def company_should_has_one_or_more_stores
if company.stores.count < 2
errors.add(:base, I18n.t('models.store.company_error'))
false
end
end
def destroy_all_childrens
PurchaseOrder.destroy_all(delivery_location_id: id)
[Stores::Boat, Brand, Category, CertificationLevelCost, CertificationLevel, CommissionRate, Stores::EmailSetting,
Stores::EventTariff, EventTrip, Event, ExtraEvents::ExtraEvent, Stores::FinanceReport, MiscellaneousProduct,
PaymentMethod, Rental, Sale, Services::ServiceKit, Service, StoreProduct, TaxRate, Services::TypeOfService, Till,
Stores::WorkingTime, Stores::Xero].map{|u| u.destroy_all(store_id: id)}
end
def add_managers_to_store
unless on_migration
company.staff_members.manager.each do |manager|
manager.stores << self
manager.save
end
end
end
def add_working_time
self.working_times.create open_at: Time.now, opened_user: company.owner
end
def create_default_sales
tax_rates.create amount: 0.0
commission_rates.create amount: 0.0
end
def add_managers_to_store
company.users.managers.each do |user|
user.stores << self
user.save
end
end
def add_payment_methods
payment_methods.create [{ name: 'Paypal' }, { name: 'Credit Card' }, { name: 'Cash'}]
end
def check_main_store
call_stack = caller.join("!").include?("update_stores")
return !self.main if call_stack
return true
end
def remove_invoice
return if main or invoice_id.blank?
Stripe.api_key = Figaro.env.stripe_api_key
ii = Stripe::InvoiceItem.retrieve(invoice_id)
ii.delete
end
def add_email_settings
self.create_email_setting
end
def generate_invoice
@complete_sales = sales.for_invoice(@working_time)
@rentals = rentals.for_invoice(@working_time)
return if @complete_sales.empty? && @rentals.empty?
@invoice = self.invoices.build(
working_time: @working_time,
total_payments: @complete_sales.sum(:grand_total) + @rentals.sum(:grand_total),
discounts: @complete_sales.sum(&:calc_discount) + @rentals.sum(&:calc_discount),
tax_total: @complete_sales.sum(:tax_rate_total) + @rentals.sum(&:tax_rate_total),
complete_payments: @complete_sales.where( status: 'complete' ).sum(:grand_total) + @rentals.sum(:grand_total)
)
generate_payments_for_invoice
@invoice.save!
end
def generate_payments_for_invoice
payments = []
@complete_sales.each do |sale|
sale.payments.each_with_index do |payment, index|
payments << {payment.payment_method_id => (index + 1 == sale.payments.count) ? payment.amount - sale.change_amount : payment.amount}
end
end
@rentals.each do |rental|
rental.rental_payments.each_with_index do |payment, index|
payments << {payment.payment_method_id => (index + 1 == rental.rental_payments.count) ? payment.amount - rental.change_amount : payment.amount}
end
end
return if payments.blank?
payments.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}.each do |pm|
@invoice.finance_report_payments.build name: PaymentMethod.find_by_id(pm.first).name, amount: pm.last, custom_amount: pm.last
end
end
def generate_credit
@refund_sales = sales.for_credit(@working_time)
return if @refund_sales.empty?
@credit = self.credits.build(
working_time: @working_time,
total_payments: @refund_sales.sum(:grand_total).abs,
complete_payments: @refund_sales.sum(:grand_total).abs,
discounts: 0,
tax_total: @refund_sales.sum(:tax_rate_total).abs
)
generate_payments_for_credit
@credit.save!
end
def generate_payments_for_credit
Payment.where(sale_id: @refund_sales.map(&:id)).sum(:amount, group: 'payment_method_id').each do |pm|
@credit.finance_report_payments.build name: PaymentMethod.find_by_id(pm.first).name, amount: pm.last.abs, custom_amount: pm.last.abs
end
end
def smart_add_tsp_url_protocol
return if tsp_url.blank?
unless tsp_url[/\Ahttp:\/\//] || tsp_url[/\Ahttps:\/\//]
self.tsp_url = "http://#{tsp_url}"
end
end
end
| mit |
duhaly/MVC6.Template | test/MvcTemplate.Tests/Unit/Components/Mvc/Adapters/MaxValueAdapterTests.cs | 1358 | using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.ModelBinding.Validation;
using MvcTemplate.Components.Mvc;
using MvcTemplate.Tests.Objects;
using System;
using System.Linq;
using Xunit;
namespace MvcTemplate.Tests.Unit.Components.Mvc
{
public class MaxValueAdapterTests
{
#region Method: GetClientValidationRules(ClientModelValidationContext context)
[Fact]
public void GetClientValidationRules_ReturnsMaxRangeValidationRule()
{
IModelMetadataProvider provider = new EmptyModelMetadataProvider();
MaxValueAdapter adapter = new MaxValueAdapter(new MaxValueAttribute(128));
ModelMetadata metadata = provider.GetMetadataForProperty(typeof(AdaptersModel), "MaxValue");
ClientModelValidationContext context = new ClientModelValidationContext(metadata, provider, null);
ModelClientValidationRule actual = adapter.GetClientValidationRules(context).Single();
String expectedMessage = new MaxValueAttribute(128).FormatErrorMessage("MaxValue");
Assert.Equal(128M, actual.ValidationParameters["max"]);
Assert.Equal(expectedMessage, actual.ErrorMessage);
Assert.Equal("range", actual.ValidationType);
Assert.Single(actual.ValidationParameters);
}
#endregion
}
}
| mit |
kvnbai/revtrial | dockersymfonytrial/symfonytrial/app/DoctrineMigrations/Version20170408072031_alter_user_table_for_authentication_listener.php | 1379 | <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20170408072031_alter_user_table_for_authentication_listener extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('
ALTER TABLE organization_users
ADD failed_login_count INT NOT NULL,
ADD last_login DATETIME DEFAULT NULL,
ADD last_logout DATETIME DEFAULT NULL,
ADD account_locked_duration DATETIME DEFAULT NULL
');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE organization_users DROP failed_login_count, DROP last_login, DROP last_logout, DROP account_locked_duration');
}
}
| mit |
Glank/Java-Games | Frogger/src/FroggerLevel.java | 493 | public class FroggerLevel implements java.io.Serializable
{
//public static final FroggerLevel TEST = new FroggerLevel(new int[]{1,1,1}, new String[]{"RRR LLL BB MM ","RRR LLL BB MM ","RRR LLL BB MM "});
private int[] speeds;
private String[] patterns;
public FroggerLevel(int[] speeds, String[] patterns)
{
this.speeds = speeds;
this.patterns = patterns;
}
public int[] getSpeeds()
{
return speeds;
}
public String[] getPatterns()
{
return patterns;
}
} | mit |
sallyyoo/ced2 | shop/components/dialog/dialog.js | 6791 | /**
* 模块化组件
* @author https://github.com/skyvow
* @param {Object} options 配置项
* @param {String} options.scope 组件的命名空间
* @param {Object} options.data 组件的动态数据
* @param {Object} options.methods 组件的事件函数
*
* confirm,toast通用参数
* @skin {String} 自定义皮肤类名
* @backdrop {Bolean} 遮罩层
* @title {String} 标题
* @content {String} 内容
*
* 1、confirm @param {Object}
* @positionCls {String} 垂直位置的类名 'top','bottom' 默认水平垂直居中
* @buttons {Object} @text 按钮文字 @onTap 按钮绑定事件,可以只传一个按钮
*
* 2、toast @param {Object}
* @icon {String} 小程序icon组件的type
* @duration {Number} 自动消失时间,单位毫秒,默认1500
*
* 3、加载中 @param {Object}
* 调用方式showLoading,需要手动调用关闭hideLoading
*
* 4、通知 @param {Object} 窗口顶部消息提示
* @icon {String} 小程序icon组件的type,调用方式success,fail有默认icon
* @content {String} 内容
*/
class Component {
constructor(options = {}) {
Object.assign(this, {
options,
})
this.__init()
}
/**
* 初始化
*/
__init() {
this.page = getCurrentPages()[getCurrentPages().length - 1]
this.setData = this.page.setData.bind(this.page)
this.__initState()
}
/**
* 初始化组件状态
*/
__initState() {
this.options.data && this.__initData()
this.options.methods && this.__initMethods()
}
/**
* 绑定组件动态数据
*/
__initData() {
const scope = this.options.scope
const data = this.options.data
this._data = {}
// 筛选非函数类型,更改参数中函数的 this 指向
if (!this.isEmptyObject(data)) {
for (let key in data) {
if (data.hasOwnProperty(key)) {
if (typeof data[key] === `function`) {
data[key] = data[key].bind(this)
} else {
this._data[key] = data[key]
}
}
}
}
// 将数据同步到 page.data 上面方便渲染组件
this.page.setData({
[`${scope}`]: this._data,
})
}
/**
* 绑定组件事件函数
*/
__initMethods() {
const scope = this.options.scope
const methods = this.options.methods
// 筛选函数类型
if (!this.isEmptyObject(methods)) {
for (let key in methods) {
if (methods.hasOwnProperty(key) && typeof methods[key] === `function`) {
this[key] = methods[key] = methods[key].bind(this)
// 将 methods 内的方法重命名并挂载到 page 上面,否则 template 内找不到事件
this.page[`${scope}.${key}`] = methods[key]
// 将方法名同步至 page.data 上面,方便在模板内使用 {{ method }} 方式绑定事件
this.setData({
[`${scope}.${key}`]: `${scope}.${key}`,
})
}
}
}
}
/**
* 获取组件的 data 数据
*/
getComponentData() {
let data = this.page.data
let name = this.options.scope && this.options.scope.split(`.`)
name.forEach((n, i) => {
data = data[n]
})
return data
}
/**
* 判断 object 是否为空
*/
isEmptyObject(e) {
for (let t in e)
return !1
return !0
}
/**
* 设置元素显示
*/
setVisible(className = `w-animate-fade-in`,notifyCls = 'notify-fade-in') {
this.setData({
[`${this.options.scope}.animateCss`]: className,
[`${this.options.scope}.visible`]: !0,
[`${this.options.scope}.notifyCls`]: notifyCls,
})
}
/**
* 设置元素隐藏
*/
setHidden(className = `w-animate-fade-out`, timer = 300, notifyCls = 'notify-fade-out') {
this.setData({
[`${this.options.scope}.animateCss`]: className,
[`${this.options.scope}.notifyCls`]: notifyCls,
})
setTimeout(() => {
this.setData({
[`${this.options.scope}.visible`]: !1,
})
}, timer)
}
}
export default {
setDefaults(){
return {
title:undefined,
content:undefined,
buttons:undefined,
icon:undefined,
duration:undefined,
backdrop:true
}
},
data(){
return {
onConfirm(){},
onCancel(){},
confirmText:"确定",
cancelText:"取消",
loadingText:"loading...",
duration:1500,
successIcon:'/common/images/icon_success_small.png',
failIcon:'/common/images/icon_fail_small.png'
}
},
open(opts = {}){
const options = Object.assign({
visible:!1
},this.setDefaults(),opts);
const component = new Component({
scope:`$w.dialog`,
data:options,
methods:{
hide(cb){
this.setHidden();
setTimeout(() => typeof cb === 'function' && cb(),300);
},
show(){
this.setVisible();
},
buttonTapped(e) {
const index = e.currentTarget.dataset.index
const button = options.buttons[index];
this.hide(() => typeof button.onTap === `function` && button.onTap(e))
},
hideDialog(){
if (this.lock == true){
this.setHidden();
}
if(options.type !== 'loading'){
}
}
}
});
if(options.type === 'toast' || options.type === 'notice'){
component.show();
setTimeout(function(){
component.hide();
}, options.duration || this.data().duration);
}
else if (options.type === 'hideLoading'){
setTimeout(function () {
component.hide();
}, 0);
}else{
component.show();
return component.hide;
}
},
confirm(opts = {}){
return this.open(Object.assign({
buttons:[
{
text: opts.confirmText || this.data().confirmText,
onTap(e) {
typeof opts.onConfirm === `function` && opts.onConfirm(e)
},
},
{
text: opts.cancelText || this.data().cancelText,
onTap(e) {
typeof opts.onCancel === `function` && opts.onCancel(e)
},
}
]
},opts))
},
toast(opts = {}){
return this.open(Object.assign({
type:'toast'
},opts))
},
showLoading(opts={}){
return this.open(Object.assign({
type:"loading",
title:opts.title || this.data().loadingText
},opts))
},
hideLoading(opts={}){
return this.open(Object.assign({
type:"hideLoading"
},opts))
},
success(opts={}){
return this.open(Object.assign({
type:"notice",
icon:opts.icon || this.data().successIcon
},opts))
},
fail(opts = {}) {
return this.open(Object.assign({
type: "notice",
icon: opts.icon || this.data().failIcon
}, opts))
}
} | mit |
ozym/ros | tool_macserver.go | 1202 | package ros
// only manage the default mac-server
func toolMacServer(legacy bool) Command {
if legacy {
return Command{
Path: "/tool mac-server",
Command: "print",
Flags: map[string]bool{
"default": true,
},
Detail: true,
}
}
return Command{
Path: "/tool mac-server",
Command: "print",
Detail: true,
}
}
func (r *Ros) ToolMacServer() (map[string]string, error) {
return r.First(toolMacServer(!r.AtLeast(6, 41)))
}
func setToolMacServer(key, value string, legacy bool) Command {
if legacy {
return Command{
Path: "/tool mac-server",
Command: "set",
Filter: map[string]string{
"default": "",
},
Params: map[string]string{
key: value,
},
}
}
return Command{
Path: "/tool mac-server",
Command: "set",
Params: map[string]string{
key: value,
},
}
}
func (r *Ros) SetToolMacServerDisabled(disabled bool) error {
if !r.AtLeast(6, 41) {
return r.Exec(setToolMacServer("disabled", FormatBool(disabled), true))
}
return nil
}
func (r *Ros) SetToolMacServerAllowedInterfaceList(list string) error {
if r.AtLeast(6, 41) {
return r.Exec(setToolMacServer("allowed-interface-list", list, false))
}
return nil
}
| mit |
eyeofhorus-world/eyeofhorus | src/app/agents/client/framework/config/shadows.js | 489 |
import palette from './palette';
import dimens from './dimens';
const shadowStyle = elevationPixels => `0 0 ${elevationPixels} 0 ${palette.semiTransparentGrey}, 0 ${elevationPixels} ${elevationPixels} 0 ${palette.semiTransparentGreyDouble}`;
export default {
elevationPixels0: 'none',
elevationPixels2: shadowStyle(dimens.pixels2),
elevationPixels4: shadowStyle(dimens.pixels4),
elevationPixels6: shadowStyle(dimens.pixels6),
elevationPixels8: shadowStyle(dimens.pixels8),
};
| mit |
garafu/express-junction | lib/authorizer.js | 1245 | var Validator = require("./validator.js");
/**
* Authorizer class.
* @constructor
* @param {Validator[]} validators
*/
var Authorizer = function (validators) {
this.validators = validators || [];
};
/**
* Get whether specified condition is authorized or not.
* @param {Request} request Request object of express.
* @param {string} user User name.
* @param {string} role Role nema.
*/
Authorizer.prototype.validate = function (request, user, role) {
for (let validator of this.validators) {
if (validator.match(request, user, role)) {
return validator.allowed;
}
}
return false; // default denay.
};
/**
* Allow specified user or role.
* @param {Validator[]} rules Allow users or roles.
* @return {Validator}
*/
var allow = function (rules) {
return new Validator(true, rules);
};
/**
* Deny specified user or role.
* @param {Validator[]} rules Deny users or roles.
* @return {Validator}
*/
var deny = function (rules) {
return new Validator(false, rules);
};
// export module.
module.exports.Authorizer = Authorizer;
module.exports.allow = allow;
module.exports.deny = deny;
| mit |
gotmc/ivi | fgen/keysight/key33220/stdfunc.go | 7273 | // Copyright (c) 2017-2022 The ivi developers. All rights reserved.
// Project site: https://github.com/gotmc/ivi
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE.txt file for the project.
package key33220
import (
"fmt"
"strings"
"github.com/gotmc/ivi/fgen"
)
// Make sure that the key33220 driver implements the IviFgenStdFunc capability
// group.
var _ fgen.StdFuncChannel = (*Channel)(nil)
// Amplitude reads the difference between the maximum and minimum waveform
// values, i.e., the peak-to-peak voltage value. Amplitude is the getter for
// the read-write IviFgenStdFunc Attribute Amplitude described in Section 5.2.1
// of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) Amplitude() (float64, error) {
return ch.QueryFloat64("VOLT?\n")
}
// SetAmplitude specifies the difference between the maximum and minimum
// waveform values, i.e., the peak-to-peak voltage value. Amplitude is the
// setter for the read-write IviFgenStdFunc Attribute Amplitude described in
// Section 5.2.1 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) SetAmplitude(amp float64) error {
return ch.Set("VOLT %f VPP\n", amp)
}
// DCOffset reads the difference between the average of the maximum and minimum
// waveform values and the x-axis (0 volts). DCOffset is the getter for
// the read-write IviFgenStdFunc Attribute DC Offset described in Section 5.2.2
// of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) DCOffset() (float64, error) {
return ch.QueryFloat64("VOLT:OFFS?\n")
}
// SetDCOffset sets the difference between the average of the maximum and
// minimum waveform values and the x-axis (0 volts). SetDCOffset is the setter
// for the read-write IviFgenStdFunc Attribute DC Offset described in Section
// 5.2.2 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) SetDCOffset(amp float64) error {
return ch.Set("VOLT:OFFS %f\n", amp)
}
// DutyCycleHigh reads the percentage of time, specified as 0-100, during one
// cycle for which the square wave is at its high value. DutyCycle is the
// getter for the read-write IviFgenStdFunc Attribute Duty Cycle High described
// in Section 5.2.3 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) DutyCycleHigh() (float64, error) {
return ch.QueryFloat64("FUNC:SQU:DCYC?\n")
}
// SetDutyCycleHigh sets the percentage of time, specified as 0-100, during one
// cycle for which the square wave is at its high value. SetDutyCycle is the
// setter for the read-write IviFgenStdFunc Attribute Duty Cycle High described
// in Section 5.2.3 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) SetDutyCycleHigh(duty float64) error {
return ch.Set("FUNC:SQU:DCYC %f\n", duty)
}
// Frequency reads the number of waveform cycles generated in one second (i.e.,
// Hz). Frequency is not applicable for a DC waveform. Frequency is the getter
// for the read-write IviFgenStdFunc Attribute Frequency described in Section
// 5.2.4 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) Frequency() (float64, error) {
return ch.QueryFloat64("FREQ?\n")
}
// SetFrequency sets the number of waveform cycles generated in one second
// (i.e., Hz). Frequency is not applicable for a DC waveform. SetFrequency is
// the setter for the read-write IviFgenStdFunc Attribute Frequency described
// in Section 5.2.4 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) SetFrequency(freq float64) error {
return ch.Set("FREQ %f\n", freq)
}
// StartPhase reads the start phase of the standard waveform the function
// generator produces. When the Waveform attribute is set to Waveform DC, this
// attribute does not affect signal output. The units are degrees. StartPhase
// is the getter for the read-write IviFgenStdFunc Attribute Start Phase described
// in Section 5.2.5 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) StartPhase() (float64, error) {
return ch.QueryFloat64("PHAS?\n")
}
// SetStartPhase writes the start phase of the standard waveform the function
// generator produces. When the Waveform attribute is set to Waveform DC, this
// attribute does not affect signal output. The units are degrees. StartPhase
// is the getter for the read-write IviFgenStdFunc Attribute Start Phase described
// in Section 5.2.5 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) SetStartPhase(freq float64) error {
return ch.Set("PHAS %f\n", freq)
}
// StandardWaveform determines if one of the IVI Standard Waveforms is being
// output by the function generator. If not, an error is returned.
// StandardWaveform is the getter for the read-write IviFgenStdFunc Attribute
// Waveform described in Section 5.2.6 of IVI-4.3: IviFgen Class Specification.
func (ch *Channel) StandardWaveform() (fgen.StandardWaveform, error) {
var wave fgen.StandardWaveform
s, err := ch.QueryString("FUNC?\n")
if err != nil {
return wave, err
}
s = strings.TrimSpace(s)
switch s {
case "SIN":
return fgen.Sine, nil
case "SQU":
return fgen.Square, nil
case "DC":
return fgen.DC, nil
case "RAMP":
symm, err := ch.QueryFloat64("FUNC:RAMP:SYMM?\n")
if err != nil {
return wave, fmt.Errorf("unable to get symmetry to determine standard waveform: %s", err)
}
switch symm {
case 0.0:
return fgen.RampDown, nil
case 100.0:
return fgen.RampUp, nil
case 50.0:
return fgen.Triangle, nil
default:
return wave, fmt.Errorf("unable to determine waveform type RAMP with SYMM %f", symm)
}
}
return wave, fmt.Errorf("unable to determine standard waveform type: %s", s)
}
// SetStandardWaveform specifies which standard waveform the function generator
// produces. SetStandardWaveform is the setter for the read-write
// IviFgenStdFunc Attribute Waveform described in Section 5.2.6 of IVI-4.3:
// IviFgen Class Specification.
func (ch *Channel) SetStandardWaveform(wave fgen.StandardWaveform) error {
// FIXME(mdr): May need to change the phase offset in order to match the
// waveforms shown in Figure 5-1 of IVI-4.3: IviFgen Class Specification.
return ch.Set(waveformCommand[wave])
}
var waveformCommand = map[fgen.StandardWaveform]string{
fgen.Sine: "FUNC SIN\n",
fgen.Square: "FUNC SQU\n",
fgen.Triangle: "FUNC RAMP; RAMP:SYMM 50\n",
fgen.RampUp: "FUNC RAMP; RAMP:SYMM 100\n",
fgen.RampDown: "FUNC RAMP; RAMP:SYMM 0\n",
fgen.DC: "FUNC DC\n",
}
var waveformApplyCommand = map[fgen.StandardWaveform]string{
fgen.Sine: "APPL:SIN %.4f, %.4f, %.4f\n",
fgen.Square: "APPL:SQU %.4f, %.4f, %.4f\n",
fgen.Triangle: "APPL:RAMP %.4f, %.4f, %.4f;:FUNC:RAMP:SYMM 50\n",
fgen.RampUp: "APPL:RAMP %.4f, %.4f, %.4f;:FUNC:RAMP:SYMM 100\n",
fgen.RampDown: "APPL:RAMP %.4f, %.4f, %.4f;:FUNC:RAMP:SYMM 0\n",
fgen.DC: "APPL:DC %.4f, %.4f, %.4f\n",
}
// ConfigureStandardWaveform configures the attributes of the function
// generator that affect standard waveform generation.
// ConfigureStandardWaveform is the method that implements the Configure
// Standard Waveform function described in Section 5.3.1 of IVI-4.3: IviFgen
// Class Specification.
func (ch *Channel) ConfigureStandardWaveform(wave fgen.StandardWaveform, amp float64,
offset float64, freq float64, phase float64) error {
return ch.Set(waveformApplyCommand[wave], freq, amp, offset)
}
| mit |
asiboro/asiboro.github.io | vsdoc/search--/s_4322.js | 74 | search_result['4322']=["topic_0000000000000A4A.html","StatusVm Class",""]; | mit |
maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s01/CWE78_OS_Command_Injection__char_console_execl_82_goodG2B.cpp | 1218 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_console_execl_82_goodG2B.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-82_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: console Read input from the console
* GoodSource: Fixed string
* Sinks: execl
* BadSink : execute command with execl
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__char_console_execl_82.h"
#ifdef _WIN32
#include <process.h>
#define EXECL _execl
#else /* NOT _WIN32 */
#define EXECL execl
#endif
namespace CWE78_OS_Command_Injection__char_console_execl_82
{
void CWE78_OS_Command_Injection__char_console_execl_82_goodG2B::action(char * data)
{
/* execl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
}
#endif /* OMITGOOD */
| mit |
dmzubr/testing-store | app/scripts/controllers/createuser.js | 595 | 'use strict';
/**
* @ngdoc function
* @name testerApp.controller:CreateuserCtrl
* @description
* # CreateuserCtrl
* Controller of the testerApp
*/
angular.module('testerApp')
.controller('CreateuserCtrl',['$scope', 'toastr', 'userProvider', '$location', function ($scope, toastr, userProvider, $location) {
function createUser(createdUser) {
userProvider.CreateUser(createdUser)
.then(function() {
$location.path('/user');
}, function() {
toastr.error('Пиздец настал!','Ошибка');
});
}
$scope.createUser = createUser;
}]);
| mit |
ctrutmann/bootbook | app/controllers/follows_controller.rb | 668 | class FollowsController < ApplicationController
def index
@followers = Follow.where(followee_id: current_user.id)
@following = Follow.where(follower_id: current_user.id)
end
def new
end
def create
@follow = Follow.create(follow_params)
if @follow.save
@follow.save
redirect_to user_path(params[:followee_id])
else
flash[:danger] = @user.errors.full_messages
redirect_to 'users'
end
end
def edit
end
def destroy
Follow.find(params[:id]).destroy
redirect_to user_path(params[:followee_id])
end
private
def follow_params
params.permit(:id, :followee_id, :follower_id)
end
end
| mit |
res4j/res4j | res4j-jar/src/main/java/org/res4j/strategy/ContextStrategy.java | 802 | package org.res4j.strategy;
import org.res4j.provider.AbstractContextProvider;
public class ContextStrategy extends AbstractFilterStrategy {
protected AbstractContextProvider provider;
@Override
public void initialize(ClassLoader classloader) throws Exception {
assert provider != null : "ContextStrategy must include a providerId attribute or provider element.";
// FIXME: set provider from Res4j.Context.provider, if any.
super.initialize(classloader);
// Propagate initialization.
provider.initialize(classloader);
}
@Override
public <T> T get(String name, Object context) throws Exception {
// Providing context, if required.
if (context == null) {
context = provider.getContext(name);
}
// Delegate.
T result = delegate.get(name, context);
return result;
}
}
| mit |
Facepunch/arcade-SmashBloxTS | Entities/Ball.ts | 2896 | /// <reference path="GameEntity.ts"/>
class Ball extends GameEntity {
private _paddleHit: GameAPI.BudgetBoy.Sound;
private _blockHit: GameAPI.BudgetBoy.Sound;
private _velocity: GameAPI.Vector2f;
private _alive: boolean;
onLoadAudio() {
this._paddleHit = audio.getSound("bounce2");
this._blockHit = audio.getSound("bounce");
}
onLoadGraphics() {
var img = graphics.getImage("ball");
var swatch = graphics.palette.findSwatch(0xffffff, 0xffffff, 0xffffff);
this.add(new GameAPI.BudgetBoy.Sprite(img, swatch), new GameAPI.Vector2i(-2, -2));
this.calculateBounds();
}
setVelocity(velocity: GameAPI.Vector2f) {
this._velocity = velocity;
}
setAlive(alive: boolean) {
this._alive = alive;
}
bounce(normal: GameAPI.Vector2f, scale: number) {
var dot = this._velocity.dot(normal);
if (dot >= 0) return;
this._velocity = this._velocity.sub(normal.mul(dot).mul(1 + scale));
}
onUpdate() {
if (!this._alive) return;
this.position = this.position.add(this._velocity.mul(this.stage.timestep));
this.updateCollision();
}
updateCollision() {
if (this.x < 8.0) {
this.x = 8.0;
this.bounce(GameAPI.Vector2f.UNIT_X, 1.0);
audio.play(this._paddleHit, this.panValue, 1.0, 1.0);
}
else if (this.x > graphics.width - 8.0) {
this.x = graphics.width - 8.0;
this.bounce(new GameAPI.Vector2f(-1, 0), 1.0);
audio.play(this._paddleHit, this.panValue, 1.0, 1.0);
}
if (this.y > graphics.height - 20.0) {
this.y = graphics.height - 20.0;
this.bounce(new GameAPI.Vector2f(0, -1.0), 1.0);
audio.play(this._paddleHit, this.panValue, 1.0, 1.0);
}
if (this.bounds.intersects(this.getStage().getPaddle().bounds)) {
this.bounce(GameAPI.Vector2f.UNIT_Y, 1.0);
this.getStage().onPaddleHit();
audio.play(this._paddleHit, this.panValue, 1.0, 1.0);
}
var collisionResult = this.getStage().getBlocks().checkForCollision(this);
if (collisionResult.hit) {
if (collisionResult.getNormal().x > 0) {
this.bounce(GameAPI.Vector2f.UNIT_X, 1.0);
}
else if (collisionResult.getNormal().x < 0) {
this.bounce(new GameAPI.Vector2f(-1, 0), 1.0);
}
if (collisionResult.getNormal().y > 0) {
this.bounce(GameAPI.Vector2f.UNIT_Y, 1.0);
}
else if (collisionResult.getNormal().y < 0) {
this.bounce(new GameAPI.Vector2f(0, -1), 1.0);
}
audio.play(this._blockHit, this.panValue, 1.0, 1.0 - Math.log(collisionResult.phase) / Math.LN10 / 2.0);
}
}
}
| mit |
lyndn/weixin | public/js/mainlayout/rollover.js | 720 | /**
* jQuery.Preload - Multifunctional preloader
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
* Dual licensed under MIT and GPL.
* Date: 3/12/2008
* @author Ariel Flesler
* @version 1.0.7
*/
function initRollOverImages() {
var image_cache = new Object();
$("img.swap").each(function(i) {
var imgsrc = this.src;
var dot = this.src.lastIndexOf('.');
var imgsrc_o = this.src.substr(0, dot) + '_o' + this.src.substr(dot, 4);
image_cache[this.src] = new Image();
image_cache[this.src].src = imgsrc_o;
$(this).hover(
function() { this.src = imgsrc_o; },
function() { this.src = imgsrc; });
});
}
$(document).ready(initRollOverImages);
| mit |
kamilogorek/galaxy-shooter | app/scripts/main.js | 4463 | /* global Engine */
'use strict';
/*
* TODO:
* [ ] - Debug overall performance issue
* [ ] - Fix particles performance issue
* [ ] - Fix grunt build
* [ ] - Fix keys persistence bug that happens from time to time
*
*/
require(['config', 'game', 'background', 'player', 'ui', 'asteroids', 'sounds'], function (config, game, background, player, ui, asteroids, sounds) {
var startScreen = document.querySelector('.start-screen');
var uiScreen = document.querySelector('.ui');
var shipScreen = document.querySelector('.ship-screen');
var endScreen = document.querySelector('.end-screen');
var ships = document.querySelectorAll('.ship');
var startButton = document.querySelector('.start-game');
var restartButton = document.querySelector('.restart-game');
var pauseScreen = document.querySelector('.pause-screen');
background.init();
function initGame (color) {
shipScreen.style.display = 'none';
uiScreen.style.display = 'block';
sounds.pressButton.play();
player.init(color);
ui.init(color);
asteroids.init();
}
function showShipsScreen () {
startScreen.style.display = 'none';
shipScreen.style.display = 'block';
endScreen.style.display = 'none';
}
function showEndScreen () {
endScreen.style.display = 'block';
uiScreen.style.display = 'none';
}
startButton.addEventListener('click', function () {
showShipsScreen();
});
[].forEach.call(ships, function (ship) {
ship.addEventListener('click', function () {
initGame(this.id);
});
});
restartButton.addEventListener('click', function () {
showShipsScreen();
});
game.on('gameover', function () {
showEndScreen();
});
game.on('pause', function () {
pauseScreen.style.display = 'block';
});
game.on('unpause', function () {
pauseScreen.style.display = 'none';
});
Engine.Input.on('keyup', function (e) {
switch (e.key) {
case config.keys.enter:
// Allow to init game only when start/restart or ship choosing screen is visible
if (window.getComputedStyle(startScreen).getPropertyValue('display') === 'block' ||
window.getComputedStyle(endScreen).getPropertyValue('display') === 'block') {
showShipsScreen();
} else if (window.getComputedStyle(shipScreen).getPropertyValue('display') === 'block') {
initGame(document.querySelector('.ship.active').id);
}
break;
case config.keys.left:
// Allow to use arrows only when ship choosing screen is visible
if (window.getComputedStyle(shipScreen).getPropertyValue('display') === 'none') {
return;
}
[].forEach.call(ships, function (ship) {
ship.classList.toggle('active');
});
break;
case config.keys.right:
// Allow to use arrows only when ship choosing screen is visible
if (window.getComputedStyle(shipScreen).getPropertyValue('display') === 'none') {
return;
}
[].forEach.call(ships, function (ship) {
ship.classList.toggle('active');
});
break;
case config.keys.pause:
// Allow to use pause only while game is already started
if (window.getComputedStyle(startScreen).getPropertyValue('display') === 'block' ||
window.getComputedStyle(endScreen).getPropertyValue('display') === 'block' ||
window.getComputedStyle(shipScreen).getPropertyValue('display') === 'block') {
return;
}
if (!game.paused) {
game.stop();
game.paused = true;
game.trigger('pause');
} else {
game.play();
game.paused = false;
game.trigger('unpause');
}
break;
}
});
// Simple console.log wrapper to enable debugMode
window.debugMode = false;
window.log = function () {
if (!window.debugMode) { return; }
window.console.log.apply(console, arguments);
};
// Init game without any start screens for faster debugging
if (window.debugMode) {
initGame('red');
}
});
| mit |
sigaind/cupon | src/sigaind/siagBundle/Entity/TmEnfermedadesRepository.php | 587 | <?php
namespace sigaind\siagBundle\Entity;
use Doctrine\ORM\EntityRepository;
class TmEnfermedadesRepository extends EntityRepository
{
public function allEnfermedadesActivosPorEmpresa($empId)
{
$sql="SELECT e.enfid, e.enfcodigo, e.enfnombre, e.prioridad "
." FROM sigaind\siagBundle\Entity\TmEnfermedades e "
." where e.estid = 1 AND e.empid = :empresa ";
return $this->getEntityManager()
->createQuery($sql)
->setParameter('empresa', $empId)
->getResult();
}
}
| mit |
raphaelstary/highfive.js | src/publicexposedinternals/resizeutils/changePath.js | 1476 | H5.changePath = (function (BezierCurvePath, LinePath, Vectors, CirclePath) {
'use strict';
function changePath(path, startX_or_x, startY_or_y, endX_or_radius, endY, p1_x, p1_y, p2_x, p2_y) {
var curve = path.curve;
if (curve instanceof LinePath) {
var vector = Vectors.get(startX_or_x, startY_or_y, endX_or_radius, endY);
var length = Vectors.magnitude(vector.x, vector.y);
var unitVector = Vectors.normalize(vector.x, vector.y);
curve.startX = startX_or_x;
curve.startY = startY_or_y;
curve.endX = endX_or_radius;
curve.endY = endY;
curve.length = length;
curve.unitVectorX = unitVector.x;
curve.unitVectorY = unitVector.y;
curve.vectorX = vector.x;
curve.vectorY = vector.y;
} else if (curve instanceof CirclePath) {
curve.x = startX_or_x;
curve.y = startY_or_y;
curve.radius = endX_or_radius;
} else if (curve instanceof BezierCurvePath) {
curve.pointA_x = startX_or_x;
curve.pointA_y = startY_or_y;
curve.pointB_x = p1_x;
curve.pointB_y = p1_y;
curve.pointC_x = p2_x;
curve.pointC_y = p2_y;
curve.pointD_x = endX_or_radius;
curve.pointD_y = endY;
}
}
return changePath;
})(H5.BezierCurvePath, H5.LinePath, H5.Vectors, H5.CirclePath);
| mit |
clibc/howabout | features/steps/levenshtein_steps.py | 1581 | import random
from behave import given, when, then
from howabout import get_levenshtein
@given('two long strings')
def step_two_long_strings(context):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
random_str = lambda size: [random.choice(alphabet) for _ in range(0, size)]
context.first = random_str(1024)
context.second = random_str(1024)
@given('two empty strings')
def step_two_empty_strings(context):
context.first = ''
context.second = ''
@when('we compare them')
def step_compare_two_strings(context):
context.distance = get_levenshtein(context.first, context.second)
@then('the interpreter should not overflow')
def step_assert_no_overflow(context):
assert not context.failed
@given('"{string}" and the empty string')
def step_a_string_and_the_emtpy_string(context, string):
context.first = string
context.second = ''
@given('a string "{string}"')
def step_a_string(context, string):
context.first = string
@when('we compare it to itself')
def step_compare_string_to_itself(context):
string = context.first, context.first
context.distance = get_levenshtein(string, string)
@then('the distance is {distance:d}')
def step_assert_distance(context, distance):
assert context.distance == distance
@given('the first string "{first}" and the second string "{second}" starting with "{prefix}"')
def step_impl2(context, first, second, prefix):
"""
:type context behave.runner.Context
:type first str
:type second str
:type prefix str
"""
context.first = first
context.second = second | mit |
mug3n/entity | src/entity/model/base/processor/Processor/Processor.js | 665 | /**
* Created by mugen on 6/13/16.
*/
import {Stream} from '../../../../stream/Stream/Stream';
//var worker = new Worker('src/model/base/processor/Worker/Worker.js');
class Process {
constructor (method, args) {
this.stream = new Stream();
worker.postMessage(
{
method: method,
arguments: args
}
);
return this.stream;
}
}
class processor {
constructor () {
this.processes = [];
}
process () {
this.processes.push(
new Process()
)
}
processed (data) {
this.stream.carry(data);
}
}
export let Processor = new processor();
worker.addEventListener(
'message',
function (e) {
Processor.processed(e);
}, false);
| mit |
dodekeract/bitwise | source/buffer/create.test.ts | 964 | import bitwise from '../'
test('with less than one byte', () => {
const buffer: Buffer = bitwise.buffer.create(bitwise.string.toBits('10011'))
expect(bitwise.buffer.read(buffer).join()).toBe(
bitwise.string.toBits('1001 1000').join()
)
})
test('with one byte', () => {
const buffer: Buffer = bitwise.buffer.create(
bitwise.string.toBits('0111 1100')
)
expect(bitwise.buffer.read(buffer).join()).toBe(
bitwise.string.toBits('0111 1100').join()
)
})
test('with more than one byte', () => {
const buffer: Buffer = bitwise.buffer.create(
bitwise.string.toBits('1111 0001 1010')
)
expect(bitwise.buffer.read(buffer).join()).toBe(
bitwise.string.toBits('1111 0001 1010 0000').join()
)
})
test('with multiple bytes', () => {
const buffer: Buffer = bitwise.buffer.create(
bitwise.string.toBits('10101101 11100101 01100011')
)
expect(bitwise.buffer.read(buffer).join()).toBe(
bitwise.string.toBits('10101101 11100101 01100011').join()
)
})
| mit |
Lumbi/cookie | Cookie/Block.cpp | 345 | //
// Block.cpp
// Cookie
//
// Created by Gabriel Lumbi on 2014-10-13.
// Copyright (c) 2014 Gabriel Lumbi. All rights reserved.
//
#include "Block.h"
Cookie::Block::Block()
{
active_ = true;
}
Cookie::Block::~Block()
{
}
bool Cookie::operator==(const Cookie::Block& lhs, const Cookie::Block& rhs)
{
return &lhs == &rhs;
}; | mit |
drhenner/angel_deck | app/controllers/admin/inventory/receivings_controller.rb | 1302 | class Admin::Inventory::ReceivingsController < Admin::BaseController
def index
# by default find all POs that are not received
@purchase_orders = PurchaseOrder.receiving_admin_grid(params)
respond_to do |format|
format.html
format.json { render :json => @purchase_orders.to_jqgrid_json(
[ :supplier_name, :invoice_number, :tracking_number, :display_estimated_arrival_on, :display_received ],
@purchase_orders.per_page,
@purchase_orders.current_page,
@purchase_orders.total_entries)
}
end
end
#def new
#end
#def create
#end
def edit
@purchase_order = PurchaseOrder.includes([:variants ,
:supplier,
{:purchase_order_variants => {:variant => :product }}]).find(params[:id])
form_info
end
def update
@purchase_order = PurchaseOrder.find(params[:id])
respond_to do |format|
if @purchase_order.update_attributes(params[:purchase_order])
format.html { redirect_to(:action => :index, :notice => 'Purchase order was successfully updated.') }
else
form_info
format.html { render :action => "edit" }
end
end
end
def show
end
private
def form_info
end
end
| mit |
marinho/german-articles | webapp/resources/sap/ui/dt/ElementUtil-dbg.js | 7779 | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides object sap.ui.dt.ElementUtil.
sap.ui.define([
'jquery.sap.global'
],
function(jQuery) {
"use strict";
/**
* Class for ElementUtil.
*
* @class
* Utility functionality to work with élements, e.g. iterate through aggregations, find parents, ...
*
* @author SAP SE
* @version 1.32.10
*
* @private
* @static
* @since 1.30
* @alias sap.ui.dt.ElementUtil
* @experimental Since 1.30. This class is experimental and provides only limited functionality. Also the API might be changed in future.
*/
var ElementUtil = {};
/**
*
*/
ElementUtil.iterateOverAllPublicAggregations = function(oElement, fnCallback) {
var mAggregations = oElement.getMetadata().getAllAggregations();
if (!mAggregations) {
fnCallback();
}
for ( var sName in mAggregations) {
var oAggregation = mAggregations[sName];
var oValue = this.getAggregation(oElement, sName);
fnCallback(oAggregation, oValue);
}
};
/**
*
*/
ElementUtil.getElementInstance = function(vElement) {
if (typeof vElement === "string") {
return sap.ui.getCore().byId(vElement);
} else {
return vElement;
}
};
/**
*
*/
ElementUtil.hasAncestor = function(oElement, oAncestor) {
var oParent = oElement;
while (oParent && oParent !== oAncestor) {
oParent = oParent.getParent();
}
return !!oParent;
};
/**
*
*/
ElementUtil.findAllPublicElements = function(oElement) {
var aFoundElements = [];
var that = this;
var oCore = sap.ui.core;
function internalFind(oElement) {
if (!(oElement instanceof oCore.Element)) {
return;
}
if (oElement.getMetadata().getClass() === oCore.ComponentContainer) {
//This happens when the compontentConainer has not been rendered yet
if (!oElement.getComponentInstance()) {
return;
}
internalFind(oElement.getComponentInstance().getAggregation("rootControl"));
} else {
aFoundElements.push(oElement);
that.iterateOverAllPublicAggregations(oElement, function(oAggregation, vElements) {
if (vElements && vElements.length) {
for (var i = 0; i < vElements.length; i++) {
var oObj = vElements[i];
internalFind(oObj);
}
} else if (vElements instanceof oCore.Element) {
internalFind(vElements);
}
});
}
}
internalFind(oElement);
return aFoundElements;
};
/**
*
*/
ElementUtil.getDomRef = function(oElement) {
if (oElement) {
var oDomRef;
if (oElement.getDomRef) {
oDomRef = oElement.getDomRef();
}
if (!oDomRef && oElement.getRenderedDomRef) {
oDomRef = oElement.getRenderedDomRef();
}
return oDomRef;
}
};
/**
*
*/
ElementUtil.findAllPublicChildren = function(oElement) {
var aFoundElements = this.findAllPublicElements(oElement);
var iIndex = aFoundElements.indexOf(oElement);
if (iIndex > -1) {
aFoundElements.splice(iIndex, 1);
}
return aFoundElements;
};
/**
*
*/
ElementUtil.isElementFiltered = function(oControl, aType) {
var that = this;
aType = aType || this.getControlFilter();
var bFiltered = false;
aType.forEach(function(sType) {
bFiltered = that.isInstanceOf(oControl, sType);
if (bFiltered) {
return false;
}
});
return bFiltered;
};
/**
*
*/
ElementUtil.findClosestControlInDom = function(oNode) {
if (oNode && oNode.getAttribute("data-sap-ui")) {
return sap.ui.getCore().byId(oNode.getAttribute("data-sap-ui"));
} else {
if (oNode.parentNode) {
this.findClosestControlInDom(oNode.parentNode);
} else {
return null;
}
}
};
/**
*
*/
ElementUtil.getAggregationMutators = function(oElement, sAggregationName) {
var oMetadata = oElement.getMetadata();
oMetadata.getJSONKeys();
var oAggregationMetadata = oMetadata.getAggregation(sAggregationName);
return {
get : oAggregationMetadata._sGetter,
add : oAggregationMetadata._sMutator,
remove : oAggregationMetadata._sRemoveMutator,
insert : oAggregationMetadata._sInsertMutator
};
};
/**
*
*/
ElementUtil.getAggregation = function(oElement, sAggregationName) {
var sGetMutator = this.getAggregationMutators(oElement, sAggregationName).get;
var oValue = oElement[sGetMutator]();
//ATTENTION:
//under some unknown circumstances the return oValue looks like an Array but jQuery.isArray() returned undefined => false
//that is why we use array ducktyping with a null check!
//reproducible with Windows and Chrome (currently 35), when creating a project and opening WYSIWYG editor afterwards on any file
//sap.m.Panel.prototype.getHeaderToolbar() returns a single object but an array
/*eslint-disable no-nested-ternary */
oValue = oValue && oValue.splice ? oValue : (oValue ? [oValue] : []);
/*eslint-enable no-nested-ternary */
return oValue;
};
/**
*
*/
ElementUtil.addAggregation = function(oParent, sAggregationName, oElement) {
if (this.hasAncestor(oParent, oElement)) {
throw new Error("Trying to add an element to itself or its successors");
}
var sAggregationAddMutator = this.getAggregationMutators(oParent, sAggregationName).add;
oParent[sAggregationAddMutator](oElement);
};
/**
*
*/
ElementUtil.removeAggregation = function(oParent, sAggregationName, oElement) {
var sAggregationRemoveMutator = this.getAggregationMutators(oParent, sAggregationName).remove;
oParent[sAggregationRemoveMutator](oElement);
};
/**
*
*/
ElementUtil.insertAggregation = function(oParent, sAggregationName, oElement, iIndex) {
if (this.hasAncestor(oParent, oElement)) {
throw new Error("Trying to add an element to itself or its successors");
}
if (this.getAggregation(oParent, sAggregationName).indexOf(oElement) !== -1) {
// ManagedObject.insertAggregation won't reposition element, if it's already inside of same aggregation
// therefore we need to remove the element and then insert it again. To prevent ManagedObjectObserver from firing
// setParent event with parent null, private flag is set.
oElement.__bSapUiDtSupressParentChangeEvent = true;
try {
// invalidate should be supressed, because if the controls have some checks and sync on invalidate,
// internal structure can be also removed (SimpleForm invalidate destroyed all content temporary)
oParent.removeAggregation(sAggregationName, oElement, true);
} finally {
delete oElement.__bSapUiDtSupressParentChangeEvent;
}
}
var sAggregationInsertMutator = this.getAggregationMutators(oParent, sAggregationName).insert;
oParent[sAggregationInsertMutator](oElement, iIndex);
};
/**
*
*/
ElementUtil.isValidForAggregation = function(oParent, sAggregationName, oElement) {
// Make sure that the parent is not inside of the element, or is not the element itself,
// e.g. insert a layout inside it's content aggregation.
// This check needed as UI5 will have a maximum call stack error otherwise.
if (this.hasAncestor(oParent, oElement)) {
return false;
}
var oAggregationMetadata = oParent.getMetadata().getAggregation(sAggregationName);
// TODO : test altTypes
return this.isInstanceOf(oElement, oAggregationMetadata.type);
};
/**
*
*/
ElementUtil.isInstanceOf = function(oElement, sType) {
var oInstance = jQuery.sap.getObject(sType);
if (typeof oInstance === "function") {
return oElement instanceof oInstance;
} else {
return false;
}
};
/**
*
*/
ElementUtil.getDesignTimeMetadata = function(oElement) {
var oDTMetadata = oElement ? oElement.getMetadata().getDesignTime() : {};
return oDTMetadata || {};
};
return ElementUtil;
}, /* bExport= */ true);
| mit |
yzhnasa/TASSEL-iRods | src/net/maizegenetics/analysis/association/MLMPlugin.java | 26877 | package net.maizegenetics.analysis.association;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.plugindef.PluginEvent;
import net.maizegenetics.dna.snp.GeneticMap;
import net.maizegenetics.trait.MarkerPhenotype;
import net.maizegenetics.trait.Phenotype;
import net.maizegenetics.taxa.distance.DistanceMatrix;
import net.maizegenetics.gui.ReportDestinationDialog;
import javax.swing.*;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.apache.log4j.Logger;
/**
* Author: Peter Bradbury
* Date: Jan 17, 2010
*/
public class MLMPlugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(MLMPlugin.class);
protected DistanceMatrix kinshipMatrix;
protected boolean analyzeByColumn;
protected boolean useP3D = true;
protected CompressionType compressionType = CompressionType.Optimum;
protected double compression = 1;
private boolean writeOutputToFile = false;
private String outputName = null;
private boolean filterOutput = false;
private double maxp = 1;
public enum CompressionType {
Optimum, Custom, None
};
public MLMPlugin(Frame parentFrame, boolean isInteractive) {
super(parentFrame, isInteractive);
}
public DataSet performFunction(DataSet input) {
try {
//import a genetic map, if there is one
GeneticMap myMap;
List<Datum> maps = input.getDataOfType(GeneticMap.class);
if (maps.size() > 0) {
myMap = (GeneticMap) maps.get(0).getData();
} else {
myMap = null;
}
java.util.List<Datum> alignInList = input.getDataOfType(MarkerPhenotype.class);
if (alignInList.size() == 0) {
alignInList = input.getDataOfType(Phenotype.class);
}
java.util.List<Datum> kinshipList = input.getDataOfType(DistanceMatrix.class);
if (alignInList.size() < 1) {
String message = "Invalid selection. Please select sequence alignment or marker and trait data.";
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
if (kinshipList.size() != 1) {
String message = "Please select exactly one kinship matrix.";
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
kinshipMatrix = (DistanceMatrix) kinshipList.get(0).getData();
Iterator<Datum> itr = alignInList.iterator();
if (isInteractive()) {
MLMOptionDialog theOptions = new MLMOptionDialog(getParentFrame());
if (theOptions.runClicked) {
useP3D = theOptions.useP3D();
compressionType = theOptions.getCompressionType();
compression = theOptions.getCompressionLevel();
theOptions.dispose();
// give the user the option of sending the output to a file
ReportDestinationDialog rdd = new ReportDestinationDialog();
rdd.setLocationRelativeTo(getParentFrame());
rdd.setVisible(true);
if (!rdd.isOkayChecked()) {
return null;
}
writeOutputToFile = rdd.wasUseFileChecked();
if (writeOutputToFile) {
outputName = rdd.getOutputFileName();
}
filterOutput = rdd.wasRestrictOutputChecked();
if (filterOutput) {
maxp = rdd.getMaxP();
}
} else {
theOptions.dispose();
return null;
}
} else { //non-interactive stuff
}
List<DataSet> result = new ArrayList<DataSet>();
while (itr.hasNext()) {
Datum current = itr.next();
DataSet tds = null;
try {
if (useP3D) {
if (compressionType.equals(CompressionType.Optimum)) {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, true, true, Double.NaN, myMap);
tds = new DataSet(theAnalysis.solve(), this);
} else if (compressionType.equals(CompressionType.Custom)) {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, true, true, compression, myMap);
tds = new DataSet(theAnalysis.solve(), this);
} else {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, false, true, Double.NaN, myMap);
tds = new DataSet(theAnalysis.solve(), this);
}
} else {
if (compressionType.equals(CompressionType.Optimum)) {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, true, false, Double.NaN, myMap);
tds = new DataSet(theAnalysis.solve(), this);
} else if (compressionType.equals(CompressionType.Custom)) {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, true, false, compression, myMap);
tds = new DataSet(theAnalysis.solve(), this);
} else {
CompressedMLMusingDoubleMatrix theAnalysis = new CompressedMLMusingDoubleMatrix(this, current, kinshipMatrix, false, false, Double.NaN, myMap);
tds = new DataSet(theAnalysis.solve(), this);
}
}
} catch (Exception e) {
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
} else {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
if (tds != null) {
result.add(tds);
fireDataSetReturned(new PluginEvent(tds, MLMPlugin.class));
}
}
return DataSet.getDataSet(result, this);
} finally {
fireProgress(100);
}
}
public ImageIcon getIcon() {
URL imageURL = MLMPlugin.class.getResource("/net/maizegenetics/analysis/images/Mix.gif");
if (imageURL == null) {
return null;
} else {
return new ImageIcon(imageURL);
}
}
public String getButtonName() {
return "MLM";
}
public String getToolTipText() {
return "Association analysis using mixed model";
}
//a few stub functions to avoid producing errors in existing pipeline code
public void setAnalyzeByColumn(boolean analyzeByColumn) {
this.analyzeByColumn = analyzeByColumn;
}
public void setMaximumNumOfIteration(int max) {/*does nothing*/
}
public void setFinalIterMarker(boolean myFinalIterMarker) {/*does nothing*/
}
public void addFactors(int[] factors) {/*does nothing*/
}
public void setColumnTypes(String[] types) {/*does nothing*/
}
public void addFactors(String[] names) {/*does nothing*/
}
public void updateProgress(int progress) {
if (progress < 0) {
progress = 0;
} else if (progress > 100) {
progress = 100;
}
fireProgress(progress);
}
public void setVarCompEst(String value) {
if (value.equalsIgnoreCase("P3D")) {
useP3D = true;
} else if (value.equalsIgnoreCase("EachMarker")) {
useP3D = false;
} else {
throw new IllegalArgumentException("MLMPlugin: setVarCompEst: don't know how to handle value: " + value);
}
}
public void setCompressionType(CompressionType type) {
compressionType = type;
}
public boolean isWriteOutputToFile() {
return writeOutputToFile;
}
public void setWriteOutputToFile(boolean writeOutputToFile) {
this.writeOutputToFile = writeOutputToFile;
}
public String getOutputName() {
return outputName;
}
public void setOutputName(String outputName) {
this.outputName = outputName;
this.writeOutputToFile = true;
}
public boolean isFilterOutput() {
return filterOutput;
}
public void setFilterOutput(boolean filterOutput) {
this.filterOutput = filterOutput;
}
public double getMaxp() {
return maxp;
}
public void setMaxp(double maxp) {
this.maxp = maxp;
this.filterOutput = true;
}
public double getCustomCompression() {
return compression;
}
public void setCustomCompression(double value) {
compression = value;
}
}
class MLMOptionDialog extends JDialog implements ActionListener {
JRadioButton btnOptimum, btnCustom, btnNoCompression, btnEachMarker, btnP3D;
ButtonGroup bgCompress, bgVariance;
JTextField txtCustom;
boolean runClicked = false;
boolean useP3D = true;
MLMPlugin.CompressionType compressionType = MLMPlugin.CompressionType.Optimum;
JPanel distancePanel;
MLMOptionDialog(Frame parentFrame) {
super(parentFrame, true);
final Frame pframe = parentFrame;
setTitle("MLM Options");
setSize(new Dimension(350, 300));
setLocationRelativeTo(pframe);
Container theContentPane = getContentPane();
theContentPane.setLayout(new BorderLayout());
JPanel compressionPanel = new JPanel(new GridBagLayout());
compressionPanel.setBorder(BorderFactory.createTitledBorder("Compression Level"));
//the method radio buttons
btnOptimum = new JRadioButton("Optimum Level", true);
btnOptimum.setActionCommand("Optimum");
btnOptimum.addActionListener(this);
btnCustom = new JRadioButton("Custom Level:", false);
btnCustom.setActionCommand("Custom");
btnCustom.addActionListener(this);
btnNoCompression = new JRadioButton("No Compression", false);
btnNoCompression.setActionCommand("None");
btnNoCompression.addActionListener(this);
btnEachMarker = new JRadioButton("Re-estimate after each marker", false);
btnEachMarker.setActionCommand("Eachmarker");
btnEachMarker.addActionListener(this);
btnP3D = new JRadioButton("P3D (estimate once)", true);
btnP3D.setActionCommand("P3D");
btnP3D.addActionListener(this);
bgCompress = new ButtonGroup();
bgCompress.add(btnOptimum);
bgCompress.add(btnCustom);
bgCompress.add(btnNoCompression);
bgVariance = new ButtonGroup();
bgVariance.add(btnEachMarker);
bgVariance.add(btnP3D);
txtCustom = new JTextField(5);
Insets inset1 = new Insets(5, 15, 5, 5);
Insets inset2 = new Insets(5, 5, 5, 5);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = inset1; //top, left, bottom, right
compressionPanel.add(btnOptimum, gbc);
gbc.gridy++;
gbc.gridwidth = 1;
compressionPanel.add(btnCustom, gbc);
gbc.gridx++;
gbc.insets = inset2;
compressionPanel.add(txtCustom, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.insets = inset1;
compressionPanel.add(btnNoCompression, gbc);
theContentPane.add(compressionPanel, BorderLayout.NORTH);
JPanel variancePanel = new JPanel(new GridBagLayout());
variancePanel.setBorder(BorderFactory.createTitledBorder("Variance Component Estimation"));
gbc.gridy = 0;
variancePanel.add(btnP3D, gbc);
gbc.gridy++;
variancePanel.add(btnEachMarker, gbc);
theContentPane.add(variancePanel, BorderLayout.CENTER);
//the help me button
JButton btnHelpme = new JButton("Help Me Choose");
final String msg = "For faster analysis, impute marker values before running MLM and use P3D.\n"
+ "With imputed marker values (no missing data), P3D will be very fast but compression will actually increase execution time somewhat.\n"
+ "However, because compression will improve the overall model fit, it should still be used.\n"
+ "If there is missing marker data, compression with P3D will probably be faster than P3D alone.\n"
+ "With small to moderate sized data sets any of the methods should give reasonable performance. \n"
+ "With large data sets consider imputing marker data then using EMMA with both compression and P3D";
btnHelpme.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(pframe, msg, "EMMA methods", JOptionPane.INFORMATION_MESSAGE);
}
});
//the run and cancel buttons
JButton btnRun = new JButton("Run");
JButton btnCancel = new JButton("Cancel");
btnRun.setActionCommand("run");
btnRun.addActionListener(this);
btnCancel.setActionCommand("cancel");
btnCancel.addActionListener(this);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(Box.createGlue());
buttonBox.add(btnRun);
buttonBox.add(Box.createHorizontalStrut(50));
buttonBox.add(btnCancel);
buttonBox.add(Box.createHorizontalStrut(50));
buttonBox.add(btnHelpme);
buttonBox.add(Box.createGlue());
theContentPane.add(buttonBox, BorderLayout.SOUTH);
this.pack();
setLocationRelativeTo(getParent());
this.setVisible(true);
}
public boolean useP3D() {
return useP3D;
}
public MLMPlugin.CompressionType getCompressionType() {
return compressionType;
}
double getCompressionLevel() {
double comp;
try {
comp = Double.parseDouble(txtCustom.getText());
} catch (Exception e) {
comp = Double.NaN;
}
return comp;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("run")) {
runClicked = true;
this.setVisible(false);
} else if (e.getActionCommand().equals("cancel")) {
this.setVisible(false);
} else if (e.getActionCommand().equals("Optimum")) {
compressionType = MLMPlugin.CompressionType.Optimum;
} else if (e.getActionCommand().equals("Custom")) {
compressionType = MLMPlugin.CompressionType.Custom;
} else if (e.getActionCommand().equals("None")) {
compressionType = MLMPlugin.CompressionType.None;
} else if (e.getActionCommand().equals("Eachmarker")) {
useP3D = false;
} else if (e.getActionCommand().equals("P3D")) {
useP3D = true;
}
}
}
class MLMNewOptionDialog extends JDialog implements ActionListener {
JCheckBox chkP3D = new JCheckBox("P3D (Compute variance estimates once)", true);
JCheckBox chkCompression = new JCheckBox("Compression", true);
JCheckBox chkNoMarkers = new JCheckBox("Do not test markers", false);
JCheckBox chkUPGMA = new JCheckBox("UPGMA", true);
JCheckBox chkNJ = new JCheckBox("Neighbor Joining", false);
JCheckBox chkAvg = new JCheckBox("Average", true);
JCheckBox chkMin = new JCheckBox("Minimum", false);
JCheckBox chkMax = new JCheckBox("Maximum", false);
JCheckBox chkMedian = new JCheckBox("Median", false);
JTextField txtGroupFrom = new JTextField(5);
JTextField txtGroupTo = new JTextField(5);
JTextField txtGroupBy = new JTextField(5);
JTextField txtGroupNumberList = new JTextField(30);
JTextField txtCompFrom = new JTextField(5);
JTextField txtCompTo = new JTextField(5);
JTextField txtCompBy = new JTextField(5);
JTextField txtCompNumberList = new JTextField(30);
JTextField txtCompressionFrom = new JTextField(5);
JTextField txtCompressionTo = new JTextField(5);
JTextField txtCompressionLevels = new JTextField(5);
JRadioButton radioGroupRange = new JRadioButton("Range", false);
JRadioButton radioGroupList = new JRadioButton("List (comma-separated numbers)", false);
JRadioButton radioCompRange = new JRadioButton("Range", true);
JRadioButton radioCompList = new JRadioButton("List (comma-separated numbers)", false);
MLMNewOptionDialog(Frame parentFrame) {
super(parentFrame, true);
setTitle("MLM Options");
setSize(new Dimension(350, 300));
setLocationRelativeTo(getParent());
Container theContentPane = getContentPane();
theContentPane.setLayout(new BorderLayout());
JPanel optionPanel = new JPanel(new GridBagLayout());
optionPanel.setBorder(BorderFactory.createTitledBorder("MLM Options"));
JPanel compressionPanel = new JPanel(new GridBagLayout());
JPanel groupNumberPanel = new JPanel(new GridBagLayout());
JPanel centerPanel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel(new GridBagLayout());
String gnPanelTitle = "Specify Compression Levels or Group Sizes to Test";
compressionPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(5, 2, 4, 2), BorderFactory.createTitledBorder("Compression Options")));
groupNumberPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 2, 8, 2), BorderFactory.createTitledBorder(gnPanelTitle)));
chkCompression.addActionListener(this);
chkCompression.setActionCommand("compress");
chkNoMarkers.addActionListener(this);
chkNoMarkers.setActionCommand("nomarkers");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2,2,2,2);
optionPanel.add(chkP3D, gbc);
gbc.gridy = 1;
optionPanel.add(chkCompression, gbc);
gbc.gridy = 2;
optionPanel.add(chkNoMarkers, gbc);
theContentPane.add(optionPanel, BorderLayout.NORTH);
ButtonGroup numberGroup = new ButtonGroup();
numberGroup.add(radioGroupRange);
numberGroup.add(radioGroupList);
numberGroup.add(radioCompRange);
numberGroup.add(radioCompList);
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2,4,2,4);
compressionPanel.add(new JLabel("Clustering Algorithm"), gbc);
gbc.gridx++;
compressionPanel.add(chkUPGMA, gbc);
gbc.gridy++;
compressionPanel.add(chkNJ, gbc);
gbc.gridx = 0;
gbc.gridy++;
compressionPanel.add(new JLabel("Group Kinship"), gbc);
gbc.gridx++;
compressionPanel.add(chkAvg, gbc);
gbc.gridy++;
compressionPanel.add(chkMin, gbc);
gbc.gridy++;
compressionPanel.add(chkMax, gbc);
gbc.gridy++;
compressionPanel.add(chkMedian, gbc);
gbc.gridy = 0;
gbc.gridx = 0;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(6,4,6,4);
groupNumberPanel.add(new JLabel("Compression Levels"), gbc);
gbc.gridx++;
gbc.weightx = 0;
gbc.insets = new Insets(6,4,6,4);
groupNumberPanel.add(radioCompRange, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("From"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtCompFrom, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("To"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtCompTo, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("By"), gbc);
gbc.gridx++;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtCompBy, gbc);
gbc.gridx = 1;
gbc.gridy++;
groupNumberPanel.add(radioCompList, gbc);
gbc.gridx++;
gbc.gridwidth = 6;
groupNumberPanel.add(txtCompNumberList, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(6,4,6,4);
groupNumberPanel.add(new JLabel("Group Sizes"), gbc);
gbc.gridx++;
gbc.weightx = 0;
gbc.insets = new Insets(6,4,6,4);
groupNumberPanel.add(radioGroupRange, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("From"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtGroupFrom, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("To"), gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtGroupTo, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.EAST;
groupNumberPanel.add(new JLabel("By"), gbc);
gbc.gridx++;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
groupNumberPanel.add(txtGroupBy, gbc);
gbc.gridx = 1;
gbc.gridy++;
groupNumberPanel.add(radioGroupList, gbc);
gbc.gridx++;
gbc.gridwidth = 6;
groupNumberPanel.add(txtGroupNumberList, gbc);
centerPanel.add(compressionPanel, BorderLayout.NORTH);
centerPanel.add(groupNumberPanel, BorderLayout.CENTER);
theContentPane.add(centerPanel, BorderLayout.CENTER);
JButton btnOK = new JButton("Run");
btnOK.addActionListener(this);
btnOK.setActionCommand("OK");
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(this);
btnCancel.setActionCommand("Cancel");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(5,4,8,4);
buttonPanel.add(btnOK, gbc);
gbc.gridx++;
buttonPanel.add(btnCancel, gbc);
theContentPane.add(buttonPanel, BorderLayout.SOUTH);
pack();
}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand().equals("OK")) {
this.setVisible(false);
} else if (evt.getActionCommand().equals("Cancel")) {
this.setVisible(false);
} else if (evt.getActionCommand().equals("nomarkers")) {
if (chkNoMarkers.isSelected()) {
chkP3D.setEnabled(false);
} else {
chkP3D.setEnabled(true);
}
} else if (evt.getActionCommand().equals("compress")) {
if (chkCompression.isSelected()) {
chkUPGMA.setEnabled(true);
chkNJ.setEnabled(true);
chkAvg.setEnabled(true);
chkMin.setEnabled(true);
chkMax.setEnabled(true);
chkMedian.setEnabled(true);
radioGroupRange.setEnabled(true);
radioGroupList.setEnabled(true);
txtGroupBy.setEnabled(true);
txtGroupFrom.setEnabled(true);
txtGroupNumberList.setEnabled(true);
txtGroupTo.setEnabled(true);
// radioComp.setEnabled(true);
// txtCompressionFrom.setEnabled(true);
// txtCompressionTo.setEnabled(true);
// txtCompressionLevels.setEnabled(true);
} else {
chkUPGMA.setEnabled(false);
chkNJ.setEnabled(false);
chkAvg.setEnabled(false);
chkMin.setEnabled(false);
chkMax.setEnabled(false);
chkMedian.setEnabled(false);
// radioFromTo.setEnabled(false);
// radioList.setEnabled(false);
// txtBy.setEnabled(false);
// txtFrom.setEnabled(false);
// txtGroupNumberList.setEnabled(false);
// txtTo.setEnabled(false);
// radioComp.setEnabled(false);
// txtCompressionFrom.setEnabled(false);
// txtCompressionTo.setEnabled(false);
// txtCompressionLevels.setEnabled(false);
}
}
}
ArrayList<Integer> getListOfGroups() {
ArrayList<Integer> groupList = new ArrayList<Integer>();
if (radioGroupList.isSelected()) {
String[] groups = txtGroupNumberList.getText().split(",");
int n = groups.length;
try {
for (int i = 0; i < n; i++) groupList.add(Integer.parseInt(groups[i]));
} catch (Exception e) {
String msg = "Illegal character in group list.";
JOptionPane.showMessageDialog(getParent(), msg, "Illegal List", JOptionPane.ERROR_MESSAGE);
return null;
}
}
return null;
}
public static void main(String[] args) {
MLMNewOptionDialog mod = new MLMNewOptionDialog(null);
mod.setVisible(true);
System.exit(-1);
}
}
| mit |
doctrine/couchdb-odm | lib/Doctrine/ODM/CouchDB/Mapping/Annotations/Version.php | 226 | <?php
namespace Doctrine\ODM\CouchDB\Mapping\Annotations;
use Doctrine\Common\Annotations\Annotation;
/**
* @Annotation
*/
final class Version extends Field
{
public $type = 'string';
public $jsonName = '_rev';
}
| mit |
gavinfish/leetcode-share | python/125 Valid Palindrome.py | 827 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
'''
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
alphanumericS = [c for c in s.lower() if c.isalnum()]
return alphanumericS == alphanumericS[::-1]
if __name__ == "__main__":
assert Solution().isPalindrome("A man, a plan, a canal: Panama") == True
assert Solution().isPalindrome("race a car") == False | mit |
hendryluk/cormo | src/Cormo.Web/Impl/CormoHttpControllerSelector.cs | 2196 | using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using Cormo.Injects;
using Cormo.Web.Api;
namespace Cormo.Web.Impl
{
[ConditionalOnMissingComponent]
public class CormoHttpControllerSelector : DefaultHttpControllerSelector
{
[Inject] IComponentManager _manager;
private readonly HttpConfiguration _configuration;
private Dictionary<string, HttpControllerDescriptor> _restDescriptors;
[Inject]
public CormoHttpControllerSelector(HttpConfiguration httpConfiguration)
: base(httpConfiguration)
{
_configuration = httpConfiguration;
}
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
var name = GetControllerName(request);
if (name != null)
{
HttpControllerDescriptor descriptor;
if (_restDescriptors.TryGetValue(name.ToLower(), out descriptor))
return descriptor;
}
return base.SelectController(request);
}
public override IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
var mapping = base.GetControllerMapping();
var restDescriptors =
_manager.GetComponents(typeof(object), new RestControllerAttribute())
.Select(controller =>
{
var name = controller.Type.Name;
if (name.EndsWith(ControllerSuffix))
name = name.Substring(0, name.Length - ControllerSuffix.Length);
return new HttpControllerDescriptor(_configuration, name, controller.Type);
})
.Where(x=> !mapping.ContainsKey(x.ControllerName))
.ToArray();
foreach (var rest in restDescriptors)
mapping.Add(rest.ControllerName, rest);
_restDescriptors = restDescriptors.ToDictionary(x => x.ControllerName.ToLower(), x=> x);
return mapping;
}
}
} | mit |
MartynJones87/clubhouse.io.net | Clubhouse.io.net/Entities/Teams/ClubhouseTeam.cs | 1089 | using System;
using System.Collections.Generic;
using Clubhouse.io.net.Entities.Workflows;
using Newtonsoft.Json;
namespace Clubhouse.io.net.Entities.Teams
{
public class ClubhouseTeam
{
[JsonProperty(PropertyName = "created_at")]
public DateTime? CreatedAt { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "entity_type")]
public string EntityType { get; set; }
[JsonProperty(PropertyName = "id")]
public long ID { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "position")]
public long Position { get; set; }
[JsonProperty(PropertyName = "project_ids")]
public List<long> ProjectIDs { get; set; }
[JsonProperty(PropertyName = "updated_at")]
public DateTime? UpdatedAt { get; set; }
[JsonProperty(PropertyName = "workflow")]
public ClubhouseWorkflow Workflow { get; set; }
}
}
| mit |
szenekonzept/QPSCoin-Source | src/qt/locale/bitcoin_fr.ts | 122639 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="fr" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Litecoin</source>
<translation>À propos de QPSCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Litecoin</b> version</source>
<translation><b>QPSCoin</b> version</translation>
</message>
<message>
<location line="+57"/>
<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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Ce logiciel est en phase expérimentale.
Distribué sous licence MIT/X11, voir le fichier COPYING ou http://www.opensource.org/licenses/mit-license.php.
Ce produit comprend des fonctionnalités développées par le projet OpenSSL pour être utilisés dans la boîte à outils OpenSSL (http://www.openssl.org/), un logiciel cryptographique écrit par Eric Young ([email protected]), et des fonctionnalités développées pour le logiciel UPnP écrit par Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Droit d'auteur</translation>
</message>
<message>
<location line="+0"/>
<source>The Litecoin developers</source>
<translation>Les développeurs QPSCoin</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Carnet d'adresses</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Double cliquez afin de modifier l'adresse ou l'étiquette</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Créer une nouvelle adresse</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copier l'adresse sélectionnée dans le presse-papiers</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nouvelle adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Litecoin 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>Voici vos adresses QPSCoin qui vous permettent de recevoir des paiements. Vous pouvez donner une adresse différente à chaque expéditeur afin de savoir qui vous paye.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copier l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Afficher le &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Litecoin address</source>
<translation>Signer un message pour prouver que vous détenez une adresse QPSCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signer un &message</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Effacer l'adresse actuellement sélectionnée de la liste</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporter les données de l'onglet courant vers un fichier</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exporter</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Litecoin address</source>
<translation>Vérifier un message pour vous assurer qu'il a bien été signé avec l'adresse QPSCoin spécifiée</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Vérifier un message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Supprimer</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Litecoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Ce sont vos adresses QPSCoin pour émettre des paiements. Vérifiez toujours le montant et l'adresse du destinataire avant d'envoyer des pièces.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copier l'é&tiquette</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Éditer</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Envoyer des Bit&coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporter les données du carnet d'adresses</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Erreur lors de l'exportation</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Impossible d'écrire dans le fichier %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogue de phrase de passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Entrez la phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nouvelle phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Répétez la phrase de passe</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Entrez une nouvelle phrase de passe pour le porte-monnaie.<br/>Veuillez utiliser une phrase composée de <b>10 caractères aléatoires ou plus</b>, ou bien de <b>huit mots ou plus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Chiffrer le porte-monnaie</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déverrouiller le porte-monnaie.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Déverrouiller le porte-monnaie</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour décrypter le porte-monnaie.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Déchiffrer le porte-monnaie</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Changer la phrase de passe</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Entrez l’ancienne phrase de passe pour le porte-monnaie ainsi que la nouvelle.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmer le chiffrement du porte-monnaie</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>Attention : Si vous chiffrez votre porte-monnaie et perdez votre phrase de passe, vous <b>PERDREZ ACCÈS À TOUS VOS QPSCoinS</b> !</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Êtes-vous sûr de vouloir chiffrer votre porte-monnaie ?</translation>
</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>IMPORTANT : Les sauvegardes précédentes de votre fichier de porte-monnaie devraient être remplacées par le nouveau fichier crypté de porte-monnaie. Pour des raisons de sécurité, les précédentes sauvegardes de votre fichier de porte-monnaie non chiffré deviendront inutilisables dès que vous commencerez à utiliser le nouveau porte-monnaie chiffré.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Attention : la touche Verr. Maj. est activée !</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Porte-monnaie chiffré</translation>
</message>
<message>
<location line="-56"/>
<source>Litecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoins from being stolen by malware infecting your computer.</source>
<translation>QPSCoin va à présent se fermer pour terminer la procédure de cryptage. N'oubliez pas que le chiffrement de votre porte-monnaie ne peut pas fournir une protection totale contre le vol par des logiciels malveillants qui infecteraient votre ordinateur.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Le chiffrement du porte-monnaie a échoué</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Le chiffrement du porte-monnaie a échoué en raison d'une erreur interne. Votre porte-monnaie n'a pas été chiffré.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Les phrases de passe entrées ne correspondent pas.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Le déverrouillage du porte-monnaie a échoué</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La phrase de passe entrée pour décrypter le porte-monnaie était incorrecte.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Le déchiffrage du porte-monnaie a échoué</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La phrase de passe du porte-monnaie a été modifiée avec succès.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signer un &message...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronisation avec le réseau…</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vue d'ensemble</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Afficher une vue d’ensemble du porte-monnaie</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Parcourir l'historique des transactions</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Éditer la liste des adresses et des étiquettes stockées</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Afficher la liste des adresses pour recevoir des paiements</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Q&uitter</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quitter l’application</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Litecoin</source>
<translation>Afficher des informations à propos de QPSCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>À propos de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Afficher des informations sur Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options…</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Chiffrer le porte-monnaie...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Sauvegarder le porte-monnaie...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Modifier la phrase de passe...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importation des blocs depuis le disque...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Réindexation des blocs sur le disque...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Litecoin address</source>
<translation>Envoyer des pièces à une adresse QPSCoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Litecoin</source>
<translation>Modifier les options de configuration de QPSCoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Sauvegarder le porte-monnaie à un autre emplacement</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Modifier la phrase de passe utilisée pour le chiffrement du porte-monnaie</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Fenêtre de &débogage</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Ouvrir une console de débogage et de diagnostic</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Vérifier un message...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Litecoin</source>
<translation>QPSCoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Porte-monnaie</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Envoyer</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Recevoir</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adresses</translation>
</message>
<message>
<location line="+22"/>
<source>&About Litecoin</source>
<translation>À &propos de QPSCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Afficher / Cacher</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Afficher ou masquer la fenêtre principale</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Crypter les clefs privées de votre porte-monnaie</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Litecoin addresses to prove you own them</source>
<translation>Signer les messages avec vos adresses QPSCoin pour prouver que vous les détenez</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Litecoin addresses</source>
<translation>Vérifier les messages pour vous assurer qu'ils ont bien été signés avec les adresses QPSCoin spécifiées</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fichier</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Réglages</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Aide</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barre d'outils des onglets</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Litecoin client</source>
<translation>Client QPSCoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Litecoin network</source>
<translation><numerusform>%n connexion active avec le réseau QPSCoin</numerusform><numerusform>%n connexions actives avec le réseau QPSCoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Aucune source de bloc disponible...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>%1 blocs sur %2 (estimés) de l'historique des transactions traités.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>%1 blocs de l'historique des transactions traités.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n heure</numerusform><numerusform>%n heures</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n jour</numerusform><numerusform>%n jours</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semaine</numerusform><numerusform>%n semaines</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 en arrière</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Le dernier bloc reçu avait été généré il y a %1.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Les transactions après cela ne seront pas encore visibles.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+70"/>
<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>Cette transaction dépasse la limite de taille. Vous pouvez quand même l'envoyer en vous acquittant de frais d'un montant de %1 qui iront aux nœuds qui traiteront la transaction et aideront à soutenir le réseau. Voulez-vous payer les frais ?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>À jour</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Rattrapage…</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirmer les frais de transaction</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transaction envoyée</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transaction entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date : %1
Montant : %2
Type : %3
Adresse : %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Gestion des URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Litecoin address or malformed URI parameters.</source>
<translation>L'URI ne peut être analysé ! Cela peut être causé par une adresse QPSCoin invalide ou par des paramètres d'URI malformés.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Le porte-monnaie est <b>chiffré</b> et est actuellement <b>déverrouillé</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Le porte-monnaie est <b>chiffré</b> et est actuellement <b>verrouillé</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Litecoin can no longer continue safely and will quit.</source>
<translation>Une erreur fatale est survenue. QPSCoin ne peut plus continuer à fonctionner de façon sûre et va s'arrêter.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Alerte réseau</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Éditer l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Étiquette</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>L’étiquette associée à cette entrée du carnet d'adresses</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>L’adresse associée avec cette entrée du carnet d'adresses. Ne peut être modifiées que les adresses d’envoi.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nouvelle adresse de réception</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nouvelle adresse d’envoi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Éditer l’adresse de réception</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Éditer l’adresse d'envoi</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>L’adresse fournie « %1 » est déjà présente dans le carnet d'adresses.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Litecoin address.</source>
<translation>L'adresse fournie « %1 » n'est pas une adresse QPSCoin valide.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossible de déverrouiller le porte-monnaie.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Échec de la génération de la nouvelle clef.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Litecoin-Qt</source>
<translation>QPSCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>options de ligne de commande</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Options Interface Utilisateur</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Définir la langue, par exemple « de_DE » (par défaut : la langue du système)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Démarrer sous forme minimisée</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Afficher l'écran d'accueil au démarrage (par défaut : 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>Réglages &principaux</translation>
</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.</source>
<translation>Frais de transaction optionnel par ko qui aident à garantir un traitement rapide des transactions. La plupart des transactions utilisent 1 ko.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Payer des &frais de transaction</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Litecoin after logging in to the system.</source>
<translation>Démarrer QPSCoin automatiquement lors de l'ouverture une session sur l'ordinateur.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Litecoin on system login</source>
<translation>&Démarrer QPSCoin lors de l'ouverture d'une session</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Remettre toutes les options du client aux valeurs par défaut.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Remise à zéro des options</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Réseau</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Litecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Ouvrir le port du client QPSCoin automatiquement sur le routeur. Cela ne fonctionne que si votre routeur supporte l'UPnP et si la fonctionnalité est activée.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Ouvrir le port avec l'&UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Litecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connexion au réseau QPSCoin à travers un proxy SOCKS (par ex. lors d'une connexion via Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connexion à travers un proxy SOCKS :</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP du proxy :</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Adresse IP du proxy (par ex. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port :</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port du proxy (par ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Version SOCKS :</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Version SOCKS du serveur mandataire (par ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Fenêtre</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Afficher uniquement une icône système après minimisation.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiser dans la barre système au lieu de la barre des tâches</translation>
</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>Minimiser au lieu quitter l'application lorsque la fenêtre est fermée. Lorsque cette option est activée, l'application ne pourra être fermée qu'en sélectionnant Quitter dans le menu déroulant.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimiser lors de la fermeture</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Affichage</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Langue de l'interface utilisateur :</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Litecoin.</source>
<translation>La langue de l'interface utilisateur peut être définie ici. Ce réglage sera pris en compte après redémarrage de QPSCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unité d'affichage des montants :</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choisissez la sous-unité par défaut pour l'affichage dans l'interface et lors de l'envoi de pièces.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Litecoin addresses in the transaction list or not.</source>
<translation>Détermine si les adresses QPSCoin seront affichées sur la liste des transactions.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Afficher les adresses sur la liste des transactions</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Valider</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>A&nnuler</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Appliquer</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>par défaut</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirmer la remise à zéro des options</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>La prise en compte de certains réglages peut nécessiter un redémarrage du client.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Voulez-vous continuer ?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Litecoin.</source>
<translation>Ce réglage sera pris en compte après un redémarrage de QPSCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>L'adresse de proxy fournie est invalide.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulaire</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Litecoin network after a connection is established, but this process has not completed yet.</source>
<translation>Les informations affichées peuvent être obsolètes. Votre porte-monnaie est automatiquement synchronisé avec le réseau QPSCoin lorsque la connexion s'établit, or ce processus n'est pas encore terminé.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Solde :</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Non confirmé :</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Porte-monnaie</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immature :</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Le solde généré n'est pas encore mûr</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transactions récentes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Votre solde actuel</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total des transactions qui doivent encore être confirmées et qui ne sont pas prises en compte dans le solde actuel</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>désynchronisé</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start litecoin: click-to-pay handler</source>
<translation>Impossible de démarrer QPSCoin : gestionnaire de cliquer-pour-payer</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Dialogue de QR Code</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Demande de paiement</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Étiquette :</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message :</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Enregistrer sous...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Erreur de l'encodage de l'URI dans le QR Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Le montant entré est invalide, veuillez le vérifier.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>L'URI résultant est trop long, essayez avec un texte d'étiquette ou de message plus court.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Sauvegarder le QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Images PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nom du client</translation>
</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="+339"/>
<source>N/A</source>
<translation>Indisponible</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Version du client</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informations</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Version d'OpenSSL utilisée</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Date de démarrage</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Réseau</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Sur testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Chaîne de blocs</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nombre actuel de blocs</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Nombre total estimé de blocs</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Horodatage du dernier bloc</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Ouvrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Litecoin-Qt help message to get a list with possible Litecoin command-line options.</source>
<translation>Afficher le message d'aide de QPSCoin-Qt pour obtenir la liste des options de ligne de commande disponibles pour QPSCoin.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Afficher</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Date de compilation</translation>
</message>
<message>
<location line="-104"/>
<source>Litecoin - Debug window</source>
<translation>QPSCoin - Fenêtre de débogage</translation>
</message>
<message>
<location line="+25"/>
<source>Litecoin Core</source>
<translation>Noyau QPSCoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Journal de débogage</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Litecoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ouvrir le journal de débogage de QPSCoin depuis le répertoire de données actuel. Cela peut prendre quelques secondes pour les journaux de grande taille.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Nettoyer la console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Litecoin RPC console.</source>
<translation>Bienvenue sur la console RPC de QPSCoin.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utilisez les touches de curseur pour naviguer dans l'historique et <b>Ctrl-L</b> pour effacer l'écran.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Tapez <b>help</b> pour afficher une vue générale des commandes disponibles.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Envoyer des pièces</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Envoyer des pièces à plusieurs destinataires à la fois</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Ajouter un &destinataire</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Enlever tous les champs de transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Tout nettoyer</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Solde :</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirmer l’action d'envoi</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>E&nvoyer</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> à %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmer l’envoi des pièces</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Êtes-vous sûr de vouloir envoyer %1 ?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> et </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Cette adresse de destinataire n’est pas valide, veuillez la vérifier.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Le montant à payer doit être supérieur à 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Le montant dépasse votre solde.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Le montant dépasse votre solde lorsque les frais de transaction de %1 sont inclus.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Adresse dupliquée trouvée, il n'est possible d'envoyer qu'une fois à chaque adresse par opération d'envoi.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Erreur : Échec de la création de la transaction !</translation>
</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>Erreur : la transaction a été rejetée. Cela peut arriver si certaines pièces de votre porte-monnaie ont déjà été dépensées, par exemple si vous avez utilisé une copie de wallet.dat avec laquelle les pièces ont été dépensées mais pas marquées comme telles ici.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formulaire</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Montant :</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Payer &à :</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>L'adresse à laquelle le paiement sera envoyé (par ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Entrez une étiquette pour cette adresse afin de l’ajouter à votre carnet d’adresses</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Étiquette :</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Choisir une adresse dans le carnet d'adresses</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Coller une adresse depuis le presse-papiers</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Enlever ce destinataire</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Litecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Entrez une adresse QPSCoin (par ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Signer / Vérifier un message</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signer un message</translation>
</message>
<message>
<location line="+6"/>
<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>Vous pouvez signer des messages avec vos adresses pour prouver que les détenez. Faites attention à ne pas signer quoi que ce soit de vague car des attaques d'hameçonnage peuvent essayer d'usurper votre identité par votre signature. Ne signez que des déclarations entièrement détaillées et avec lesquelles vous serez d'accord.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>L'adresse avec laquelle le message sera signé (par ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Choisir une adresse depuis le carnet d'adresses</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Coller une adresse depuis le presse-papiers</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Entrez ici le message que vous désirez signer</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copier la signature actuelle dans le presse-papiers</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Litecoin address</source>
<translation>Signer le message pour prouver que vous détenez cette adresse QPSCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signer le &message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Remettre à zéro tous les champs de signature de message</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Tout nettoyer</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Vérifier un message</translation>
</message>
<message>
<location line="+6"/>
<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>Entrez ci-dessous l'adresse ayant servi à signer, le message (assurez-vous d'avoir copié exactement les retours à la ligne, les espacements, tabulations etc.) et la signature pour vérifier le message. Faites attention à ne pas déduire davantage de la signature que ce qui est contenu dans le message signé lui-même pour éviter d'être trompé par une attaque d'homme du milieu.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>L'adresse avec laquelle le message a été signé (par ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Litecoin address</source>
<translation>Vérifier le message pour vous assurer qu'il a bien été signé par l'adresse QPSCoin spécifiée</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Vérifier un &message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Remettre à zéro tous les champs de vérification de message</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Litecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Entrez une adresse QPSCoin (par ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Cliquez sur « Signer le message » pour générer la signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Litecoin signature</source>
<translation>Entrer une signature QPSCoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>L'adresse entrée est invalide.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Veuillez vérifier l'adresse et réessayez.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>L'adresse entrée ne fait pas référence à une clef.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Le déverrouillage du porte-monnaie a été annulé.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>La clef privée pour l'adresse indiquée n'est pas disponible.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>La signature du message a échoué.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Le message a été signé.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>La signature n'a pu être décodée.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Veuillez vérifier la signature et réessayez.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La signature ne correspond pas au hachage du message.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Échec de la vérification du message.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message vérifié.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Litecoin developers</source>
<translation>Les développeurs QPSCoin</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/hors ligne</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/non confirmée</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>État</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, diffusée à travers %n nœud</numerusform><numerusform>, diffusée à travers %n nœuds</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Génération</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>À</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>votre propre adresse</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>étiquette</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>arrive à maturité dans %n bloc</numerusform><numerusform>arrive à maturité dans %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>non accepté</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Frais de transaction</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Montant net</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Commentaire</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID de la transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Les pièces générées doivent mûrir pendant 120 blocs avant de pouvoir être dépensées. Lorsque vous avez généré ce bloc, il a été diffusé sur le réseau pour être ajouté à la chaîne de blocs. S’il échoue a intégrer la chaîne, son état sera modifié en « non accepté » et il ne sera pas possible de le dépenser. Cela peut arriver occasionnellement si un autre nœud génère un bloc quelques secondes avant ou après vous.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informations de débogage</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Entrées</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>vrai</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>faux</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, n’a pas encore été diffusée avec succès</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>inconnu</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Détails de la transaction</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ce panneau affiche une description détaillée de la transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Hors ligne (%1 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Non confirmée (%1 confirmations sur un total de %2)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmée (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Le solde généré (mined) sera disponible quand il aura mûri dans %n bloc</numerusform><numerusform>Le solde généré (mined) sera disponible quand il aura mûri dans %n blocs</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Généré mais pas accepté</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Reçue avec</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Reçue de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Envoyée à</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Paiement à vous-même</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Extraction</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(indisponible)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>État de la transaction. Laissez le pointeur de la souris sur ce champ pour voir le nombre de confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date et heure de réception de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type de transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>L’adresse de destination de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Montant ajouté au, ou enlevé du, solde.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Toutes</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Aujourd’hui</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Cette semaine</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Ce mois-ci</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mois dernier</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Cette année</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervalle…</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Reçues avec</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Envoyées à</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>À vous-même</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Extraction</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Autres</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Entrez une adresse ou une étiquette à rechercher</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Montant min</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Éditer l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Afficher les détails de la transaction</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exporter les données des transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Valeurs séparées par des virgules (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Erreur lors de l’exportation</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Impossible d'écrire dans le fichier %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervalle :</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>à</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Envoyer des pièces</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exporter</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporter les données de l'onglet courant vers un fichier</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Sauvegarder le porte-monnaie</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Données de porte-monnaie (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Échec de la sauvegarde</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Une erreur est survenue lors de l'enregistrement des données de porte-monnaie à un nouvel endroit</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Sauvegarde réussie</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Les données de porte-monnaie ont été enregistrées avec succès sur le nouvel emplacement.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Litecoin version</source>
<translation>Version de QPSCoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or litecoind</source>
<translation>Envoyer une commande à -server ou à QPSCoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Lister les commandes</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Obtenir de l’aide pour une commande</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Options :</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: litecoin.conf)</source>
<translation>Spécifier le fichier de configuration (par défaut : QPSCoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: litecoind.pid)</source>
<translation>Spécifier le fichier PID (par défaut : QPSCoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Spécifier le répertoire de données</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Écouter les connexions sur le <port> (par défaut : 9333 ou testnet : 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Garder au plus <n> connexions avec les pairs (par défaut : 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Spécifier votre propre adresse publique</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Seuil de déconnexion des pairs de mauvaise qualité (par défaut : 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Délai en secondes de refus de reconnexion aux pairs de mauvaise qualité (par défaut : 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Une erreur est survenue lors de la mise en place du port RPC %u pour écouter sur IPv4 : %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Écouter les connexions JSON-RPC sur le <port> (par défaut : 9332 ou tesnet : 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter les commandes de JSON-RPC et de la ligne de commande</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Utiliser le réseau de test</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepter les connexions entrantes (par défaut : 1 si -proxy ou -connect ne sont pas présents)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=litecoinrpc
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 "Litecoin Alert" [email protected]
</source>
<translation>%s, vous devez définir un mot de passe rpc dans le fichier de configuration :
%s
Il vous est conseillé d'utiliser le mot de passe aléatoire suivant :
rpcuser=litecoinrpc
rpcpassword=%s
(vous n'avez pas besoin de retenir ce mot de passe)
Le nom d'utilisateur et le mot de passe NE DOIVENT PAS être identiques.
Si le fichier n'existe pas, créez-le avec les droits de lecture accordés au propriétaire.
Il est aussi conseillé de régler alertnotify pour être prévenu des problèmes ;
par exemple : alertnotify=echo %%s | mail -s "Litecoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Une erreur est survenue lors de la mise en place du port RPC %u pour écouter sur IPv6, retour à IPv4 : %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Se lier à l'adresse donnée et toujours l'écouter. Utilisez la notation [host]:port pour l'IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Litecoin is probably already running.</source>
<translation>Impossible d’obtenir un verrou sur le répertoire de données %s. QPSCoin fonctionne probablement déjà.</translation>
</message>
<message>
<location line="+3"/>
<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>Erreur : la transaction a été rejetée ! Cela peut arriver si certaines pièces de votre porte-monnaie étaient déjà dépensées, par exemple si vous avez utilisé une copie de wallet.dat et les pièces ont été dépensées avec cette copie sans être marquées comme telles ici.</translation>
</message>
<message>
<location line="+4"/>
<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>Erreur : cette transaction nécessite des frais de transaction d'au moins %s en raison de son montant, de sa complexité ou parce que des fonds reçus récemment sont utilisés !</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Exécuter une commande lorsqu'une alerte correspondante est reçue (%s dans la commande sera remplacé par le message)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exécuter la commande lorsqu'une transaction de porte-monnaie change (%s dans la commande est remplacée par TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Définir la taille maximale en octets des transactions prioritaires/à frais modiques (par défaut : 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Ceci est une pré-version de test - utilisez à vos risques et périls - ne l'utilisez pas pour miner ou pour des applications marchandes</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Attention : -paytxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous émettez une transaction.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Avertissement : les transactions affichées pourraient être incorrectes ! Vous ou d'autres nœuds du réseau pourriez avoir besoin d'effectuer une mise à jour.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Litecoin will not work properly.</source>
<translation>Attention : veuillez vérifier que l'heure et la date de votre ordinateur sont correctes ! Si votre horloge n'est pas à l'heure, QPSCoin ne fonctionnera pas correctement.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Avertissement : une erreur est survenue lors de la lecture de wallet.dat ! Toutes les clefs ont été lues correctement mais les données de transaction ou les entrées du carnet d'adresses pourraient être incorrectes ou manquantes.</translation>
</message>
<message>
<location line="+3"/>
<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>Avertissement : wallet.dat corrompu, données récupérées ! Le fichier wallet.dat original a été enregistré en tant que wallet.{horodatage}.bak dans %s ; si votre solde ou transactions sont incorrects vous devriez effectuer une restauration depuis une sauvegarde.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tenter de récupérer les clefs privées d'un wallet.dat corrompu</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Options de création des blocs :</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Ne se connecter qu'au(x) nœud(s) spécifié(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Base de données des blocs corrompue détectée</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Découvrir sa propre adresse IP (par défaut : 1 lors de l'écoute et si -externalip n'est pas présent)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Voulez-vous reconstruire la base de données des blocs maintenant ?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Erreur lors de l'initialisation de la base de données des blocs</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Erreur lors de l'initialisation de l'environnement de la base de données du porte-monnaie %s !</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Erreur du chargement de la base de données des blocs</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Erreur lors de l'ouverture de la base de données</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Erreur : l'espace disque est faible !</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Erreur : Porte-monnaie verrouillé, impossible de créer la transaction !</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Erreur : erreur système :</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Échec de l'écoute sur un port quelconque. Utilisez -listen=0 si vous voulez cela.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>La lecture des informations de bloc a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>La lecture du bloc a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>La synchronisation de l'index des blocs a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>L''écriture de l'index des blocs a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>L'écriture des informations du bloc a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>L'écriture du bloc a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>L'écriture des informations de fichier a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>L'écriture dans la base de données des pièces a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>L'écriture de l'index des transactions a échoué</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>L'écriture des données d'annulation a échoué</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Trouver des pairs en utilisant la recherche DNS (par défaut : 1 sauf si -connect est utilisé)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Générer des pièces (défaut: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Nombre de blocs à vérifier au démarrage (par défaut : 288, 0 = tout)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Niveau d'approfondissement de la vérification des blocs (0-4, par défaut : 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Pas assez de descripteurs de fichiers disponibles.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Reconstruire l'index de la chaîne des blocs à partir des fichiers blk000??.dat actuels</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Définir le nombre d'exétrons pour desservir les appels RPC (par défaut : 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Vérification des blocs...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Vérification du porte-monnaie...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importe des blocs depuis un fichier blk000??.dat externe</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Définir le nombre de fils d’exécution pour la vérification des scripts (maximum 16, 0 = auto, < 0 = laisser ce nombre de cœurs libres, par défaut : 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Informations</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Adresse -tor invalide : « %s »</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -minrelayfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -mintxfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Maintenir un index complet des transactions (par défaut : 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Tampon maximal de réception par -connection, <n>*1000 octets (par défaut : 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Tampon maximal d'envoi par connexion, <n>*1000 octets (par défaut : 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>N'accepter que la chaîne de blocs correspondant aux points de vérification internes (par défaut : 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Se connecter uniquement aux nœuds du réseau <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Afficher des information de débogage supplémentaires. Cela signifie toutes les autres options -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Afficher des informations de débogage réseau supplémentaires</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Faire précéder les données de débogage par un horodatage</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Litecoin Wiki for SSL setup instructions)</source>
<translation>Options SSL : (cf. le wiki de QPSCoin pour les instructions de configuration du SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Sélectionner la version du proxy socks à utiliser (4-5, 5 étant la valeur par défaut)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Envoyer les informations de débogage/trace au débogueur</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Définir la taille maximale des blocs en octets (par défaut : 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Définir la taille minimale des blocs en octets (par défaut : 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 lorsque -debug n'est pas présent)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>La signature de la transaction a échoué</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Spécifier le délai d'expiration de la connexion en millisecondes (par défaut : 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Erreur système :</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Montant de la transaction trop bas</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Les montants de la transaction doivent être positifs</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaction trop volumineuse</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 1 lors de l'écoute)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utiliser un proxy pour atteindre les services cachés de Tor (par défaut : même valeur que -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'utilisateur pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Avertissement</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Avertissement : cette version est obsolète, une mise à jour est nécessaire !</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Vous devez reconstruire les bases de données avec -reindex pour modifier -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrompu, la récupération a échoué</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Mot de passe pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Autoriser les connexions JSON-RPC depuis l'adresse IP spécifiée</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envoyer des commandes au nœud fonctionnant à <ip> (par défaut : 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Exécuter la commande lorsque le meilleur bloc change (%s est remplacé par le hachage du bloc dans cmd)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Mettre à jour le format du porte-monnaie</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Régler la taille de la plage de clefs sur <n> (par défaut : 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Réanalyser la chaîne de blocs pour les transactions de porte-monnaie manquantes</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utiliser OpenSSL (https) pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Fichier de certificat serveur (par défaut : server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clef privée du serveur (par défaut : server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Clefs de chiffrement acceptables (par défaut : TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Ce message d'aide</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Impossible de se lier à %s sur cet ordinateur (bind a retourné l'erreur %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Connexion via un proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Chargement des adresses…</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erreur lors du chargement de wallet.dat : porte-monnaie corrompu</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Litecoin</source>
<translation>Erreur lors du chargement de wallet.dat : le porte-monnaie nécessite une version plus récente de QPSCoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Litecoin to complete</source>
<translation>Le porte-monnaie nécessitait une réécriture : veuillez redémarrer QPSCoin pour terminer l'opération</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Erreur lors du chargement de wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresse -proxy invalide : « %s »</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Réseau inconnu spécifié sur -onlynet : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Version inconnue de proxy -socks demandée : %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Impossible de résoudre l'adresse -bind : « %s »</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Impossible de résoudre l'adresse -externalip : « %s »</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -paytxfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Montant invalide</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fonds insuffisants</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Chargement de l’index des blocs…</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Litecoin is probably already running.</source>
<translation>Impossible de se lier à %s sur cet ordinateur. QPSCoin fonctionne probablement déjà.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Frais par Ko à ajouter aux transactions que vous enverrez</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Chargement du porte-monnaie…</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Impossible de revenir à une version antérieure du porte-monnaie</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Impossible d'écrire l'adresse par défaut</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Nouvelle analyse…</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Chargement terminé</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Pour utiliser l'option %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Vous devez ajouter la ligne rpcpassword=<mot-de-passe> au fichier de configuration :
%s
Si le fichier n'existe pas, créez-le avec les droits de lecture seule accordés au propriétaire.</translation>
</message>
</context>
</TS> | mit |
astrellon/Rouge | game/body_part_common.cpp | 2731 | #include "body_part_common.h"
#include <util/data_table.h>
#include <util/data_string.h>
#include <cstring>
namespace am {
namespace game {
const char *BodyPartType::sNiceBodyPartTypeNames[] =
{
"Unknown Part", "None", "Any", "Hand", "Arm", "Leg", "Head", "Torso", "Neck", "Shoulders", "Legs", "Feet", "MAX_BODY_TYPE_LENGTH"
};
const char *BodyPartType::sBodyPartTypeNames[] =
{
"unknown_part", "none", "any", "hand", "arm", "leg", "head", "torso", "neck", "shoulders", "legs", "feet", "MAX_BODY_TYPE_LENGTH"
};
const char *BodyPartType::getNiceBodyPartName(PartType type)
{
if (type < 0 || type >= MAX_BODY_TYPE_LENGTH)
{
return nullptr;
}
return sNiceBodyPartTypeNames[type];
}
const char *BodyPartType::getBodyPartName(PartType type)
{
if (type < 0 || type >= MAX_BODY_TYPE_LENGTH)
{
return nullptr;
}
return sBodyPartTypeNames[type];
}
const char *BodyPartType::getBodyPartName(int type)
{
if (type < 0 || type >= MAX_BODY_TYPE_LENGTH)
{
return nullptr;
}
return sBodyPartTypeNames[type];
}
BodyPartType::PartType BodyPartType::getBodyPartType(int typeValue)
{
if (typeValue < 0 || typeValue > MAX_BODY_TYPE_LENGTH)
{
return MAX_BODY_TYPE_LENGTH;
}
return static_cast<PartType>(typeValue);
}
BodyPartType::PartType BodyPartType::getBodyPartTypeFromNice(const char *typeName)
{
if (typeName == nullptr || typeName[0] == '\0')
{
return MAX_BODY_TYPE_LENGTH;
}
for (int i = 0; i < MAX_BODY_TYPE_LENGTH; i++)
{
if (strcmp(typeName, sNiceBodyPartTypeNames[i]) == 0)
{
return static_cast<PartType>(i);
}
}
return MAX_BODY_TYPE_LENGTH;
}
BodyPartType::PartType BodyPartType::getBodyPartType(const char *typeName)
{
if (typeName == nullptr || typeName[0] == '\0')
{
return MAX_BODY_TYPE_LENGTH;
}
for (int i = 0; i < MAX_BODY_TYPE_LENGTH; i++)
{
if (strcmp(typeName, sBodyPartTypeNames[i]) == 0)
{
return static_cast<PartType>(i);
}
}
return MAX_BODY_TYPE_LENGTH;
}
data::IData *BodyPartType::serialiseTypeList(const BodyPartType::TypeList &list)
{
data::Table *output = new data::Table();
for (size_t i = 0; i < list.size(); i++)
{
output->push(getBodyPartName(list[i]));
}
return output;
}
void BodyPartType::deserialiseTypeList(data::IData *data, BodyPartType::TypeList &result)
{
base::Handle<data::Table> typeList(data::Table::checkDataType(data, "body part type list"));
if (!typeList)
{
return;
}
for (auto iter = typeList->beginArray(); iter != typeList->endArray(); ++iter)
{
BodyPartType::PartType type = getBodyPartType(iter->get()->string());
if (type != BodyPartType::MAX_BODY_TYPE_LENGTH)
{
result.push_back(type);
}
}
}
}
}
| mit |
robbynshaw/stackattack | stackattack/Scripts/src/app/question-detail/question-detail.module.js | 121 | 'use strict';
// Define the `questionDetail` module
angular.module('questionDetail', ['core.user', 'core.question']); | mit |
fermin/workflow | lib/workflow/rails/routes/mapping.rb | 560 | module Workflow
module Rails
class Routes
class Mapping
attr_accessor :controllers, :as, :skips
def initialize
@controllers = {
work_categories: 'workflow/work_categories',
work_items: 'workflow/work_items',
work_events: 'workflow/work_events'
}
@as = []
@skips = []
end
def [](routes)
{
controllers: @controllers[routes]
}
end
def skipped?(controller)
@skips.include?(controller)
end
end
end
end
end
| mit |
nchambe2/excusify | sinatra-mvc-skeleton/db/migrate/20160204092731_create_users.rb | 273 | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name, null: false
t.string :last_name, null: false
t.string :password_hash, null: false
t.timestamps(null: false)
end
end
end
| mit |
KarrLab/wc_utils | wc_utils/util/__init__.py | 328 | from . import chem
from . import decorate_default_data_struct
from . import dict
from . import enumerate
from . import environ
from . import files
# from . import git
from . import list
from . import misc
from . import ontology
from . import rand
from . import stats
from . import string
from . import types
from . import units
| mit |
linjinjin123/BetaMoive | BetaMovie/src/main/java/com/example/model/Movie.java | 2048 | package com.example.model;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import java.sql.Date;
import java.sql.Timestamp;
public class Movie {
public String movie_name, movie_director, movie_types, movie_actors, movie_description;
public float movie_grade;
public int movie_id, movie_length;
public String movie_date;
public String getMovie_name() {
return movie_name;
}
public void setMovie_name(String movie_name) {
this.movie_name = movie_name;
}
public String getMovie_director() {
return movie_director;
}
public void setMovie_director(String movie_director) {
this.movie_director = movie_director;
}
public String getMovie_types() {
return movie_types;
}
public void setMovie_types(String movie_types) {
this.movie_types = movie_types;
}
public String getMovie_actors() {
return movie_actors;
}
public void setMovie_actors(String movie_actors) {
this.movie_actors = movie_actors;
}
public String getMovie_description() {
return movie_description;
}
public void setMovie_description(String movie_description) {
this.movie_description = movie_description;
}
public float getMovie_grade() {
return movie_grade;
}
public void setMovie_grade(float movie_grade) {
this.movie_grade = movie_grade;
}
public int getMovie_id() {
return movie_id;
}
public void setMovie_id(int movie_id) {
this.movie_id = movie_id;
}
public int getMovie_length() {
return movie_length;
}
public void setMovie_length(int movie_length) {
this.movie_length = movie_length;
}
public String getMovie_date() {
return movie_date;
}
public void setMovie_date(String movie_date) {
this.movie_date = movie_date;
}
@Override
public String toString() {
return "Movie [movie_name=" + movie_name + ", movie_director=" + movie_director + ", movie_types=" + movie_types
+ ", movie_actors=" + movie_actors + ", movie_description=" + movie_description + ", movie_grade="
+ movie_grade + ", movie_id=" + movie_id + ", movie_length=" + movie_length + "]";
}
}
| mit |
suuhui/code | laravel56/stud/live/admin/js/xadmin.js | 5154 | $(function () {
//加载弹出层
layui.use(['form','element'],
function() {
layer = layui.layer;
element = layui.element;
});
//触发事件
var tab = {
tabAdd: function(title,url,id){
//新增一个Tab项
element.tabAdd('xbs_tab', {
title: title
,content: '<iframe tab-id="'+id+'" frameborder="0" src="'+url+'" scrolling="yes" class="x-iframe"></iframe>'
,id: id
})
}
,tabDelete: function(othis){
//删除指定Tab项
element.tabDelete('xbs_tab', '44'); //删除:“商品管理”
othis.addClass('layui-btn-disabled');
}
,tabChange: function(id){
//切换到指定Tab项
element.tabChange('xbs_tab', id); //切换到:用户管理
}
};
tableCheck = {
init:function () {
$(".layui-form-checkbox").click(function(event) {
if($(this).hasClass('layui-form-checked')){
$(this).removeClass('layui-form-checked');
if($(this).hasClass('header')){
$(".layui-form-checkbox").removeClass('layui-form-checked');
}
}else{
$(this).addClass('layui-form-checked');
if($(this).hasClass('header')){
$(".layui-form-checkbox").addClass('layui-form-checked');
}
}
});
},
getData:function () {
var obj = $(".layui-form-checked").not('.header');
var arr=[];
obj.each(function(index, el) {
arr.push(obj.eq(index).attr('data-id'));
});
return arr;
}
}
//开启表格多选
tableCheck.init();
$('.container .left_open i').click(function(event) {
if($('.left-nav').css('left')=='0px'){
$('.left-nav').animate({left: '-221px'}, 100);
$('.page-content').animate({left: '0px'}, 100);
$('.page-content-bg').hide();
}else{
$('.left-nav').animate({left: '0px'}, 100);
$('.page-content').animate({left: '221px'}, 100);
if($(window).width()<768){
$('.page-content-bg').show();
}
}
});
$('.page-content-bg').click(function(event) {
$('.left-nav').animate({left: '-221px'}, 100);
$('.page-content').animate({left: '0px'}, 100);
$(this).hide();
});
$('.layui-tab-close').click(function(event) {
$('.layui-tab-title li').eq(0).find('i').remove();
});
//左侧菜单效果
// $('#content').bind("click",function(event){
$('.left-nav #nav li').click(function (event) {
if($(this).children('.sub-menu').length){
if($(this).hasClass('open')){
$(this).removeClass('open');
$(this).find('.nav_right').html('');
$(this).children('.sub-menu').stop().slideUp();
$(this).siblings().children('.sub-menu').slideUp();
}else{
$(this).addClass('open');
$(this).children('a').find('.nav_right').html('');
$(this).children('.sub-menu').stop().slideDown();
$(this).siblings().children('.sub-menu').stop().slideUp();
$(this).siblings().find('.nav_right').html('');
$(this).siblings().removeClass('open');
}
}else{
var url = $(this).children('a').attr('_href');
var title = $(this).find('cite').html();
var index = $('.left-nav #nav li').index($(this));
for (var i = 0; i <$('.x-iframe').length; i++) {
if($('.x-iframe').eq(i).attr('tab-id')==index+1){
tab.tabChange(index+1);
event.stopPropagation();
return;
}
};
tab.tabAdd(title,url,index+1);
tab.tabChange(index+1);
}
event.stopPropagation();
})
})
/*弹出层*/
/*
参数解释:
title 标题
url 请求的url
id 需要操作的数据id
w 弹出层宽度(缺省调默认值)
h 弹出层高度(缺省调默认值)
*/
function x_admin_show(title,url,w,h){
if (title == null || title == '') {
title=false;
};
if (url == null || url == '') {
url="404.html";
};
if (w == null || w == '') {
w=($(window).width()*0.9);
};
if (h == null || h == '') {
h=($(window).height() - 50);
};
layer.open({
type: 2,
area: [w+'px', h +'px'],
fix: false, //不固定
maxmin: true,
shadeClose: true,
shade:0.4,
title: title,
content: url
});
}
/*关闭弹出框口*/
function x_admin_close(){
var index = parent.layer.getFrameIndex(window.name);
parent.layer.close(index);
}
| mit |
mxcube/lucid | lucid/myutils.py | 3554 | from math import ceil
import numpy
def expand(input_img, sigma, mode="constant", cval=0.0):
"""Expand array a with its reflection on boundaries
@param a: 2D array
@param sigma: float or 2-tuple of floats
@param mode:"constant","nearest" or "reflect"
@param cval: filling value used for constant, 0.0 by default
"""
s0, s1 = input_img.shape
dtype = input_img.dtype
if isinstance(sigma, (list, tuple)):
k0 = int(ceil(float(sigma[0])))
k1 = int(ceil(float(sigma[1])))
else:
k0 = k1 = int(ceil(float(sigma)))
if k0 > s0 or k1 > s1:
raise RuntimeError("Makes little sense to apply a kernel (%i,%i)larger than the image (%i,%i)" % (k0, k1, s0, s1))
output = numpy.zeros((s0 + 2 * k0, s1 + 2 * k1), dtype=dtype) + float(cval)
output[k0:k0 + s0, k1:k1 + s1] = input_img
if (mode == "mirror"):
# 4 corners
output[s0 + k0:, s1 + k1:] = input_img[-2:-k0 - 2:-1, -2:-k1 - 2:-1]
output[:k0, :k1] = input_img[k0 - 0:0:-1, k1 - 0:0:-1]
output[:k0, s1 + k1:] = input_img[k0 - 0:0:-1, s1 - 2: s1 - k1 - 2:-1]
output[s0 + k0:, :k1] = input_img[s0 - 2: s0 - k0 - 2:-1, k1 - 0:0:-1]
# 4 sides
output[k0:k0 + s0, :k1] = input_img[:s0, k1 - 0:0:-1]
output[:k0, k1:k1 + s1] = input_img[k0 - 0:0:-1, :s1]
output[-k0:, k1:s1 + k1] = input_img[-2:s0 - k0 - 2:-1, :]
output[k0:s0 + k0, -k1:] = input_img[:, -2:s1 - k1 - 2:-1]
elif mode == "reflect":
# 4 corners
output[s0 + k0:, s1 + k1:] = input_img[-1:-k0 - 1:-1, -1:-k1 - 1:-1]
output[:k0, :k1] = input_img[k0 - 1::-1, k1 - 1::-1]
output[:k0, s1 + k1:] = input_img[k0 - 1::-1, s1 - 1: s1 - k1 - 1:-1]
output[s0 + k0:, :k1] = input_img[s0 - 1: s0 - k0 - 1:-1, k1 - 1::-1]
# 4 sides
output[k0:k0 + s0, :k1] = input_img[:s0, k1 - 1::-1]
output[:k0, k1:k1 + s1] = input_img[k0 - 1::-1, :s1]
output[-k0:, k1:s1 + k1] = input_img[:s0 - k0 - 1:-1, :]
output[k0:s0 + k0, -k1:] = input_img[:, :s1 - k1 - 1:-1]
elif mode == "nearest":
# 4 corners
output[s0 + k0:, s1 + k1:] = input_img[-1, -1]
output[:k0, :k1] = input_img[0, 0]
output[:k0, s1 + k1:] = input_img[0, -1]
output[s0 + k0:, :k1] = input_img[-1, 0]
# 4 sides
output[k0:k0 + s0, :k1] = numpy.outer(input_img[:, 0], numpy.ones(k1))
output[:k0, k1:k1 + s1] = numpy.outer(numpy.ones(k0), input_img[0, :])
output[-k0:, k1:s1 + k1] = numpy.outer(numpy.ones(k0), input_img[-1, :])
output[k0:s0 + k0, -k1:] = numpy.outer(input_img[:, -1], numpy.ones(k1))
elif mode == "wrap":
# 4 corners
output[s0 + k0:, s1 + k1:] = input_img[:k0,:k1]
output[:k0, :k1] = input_img[-k0:,-k1:]
output[:k0, s1 + k1:] = input_img[-k0:,:k1]
output[s0 + k0:, :k1] = input_img[:k0,-k1:]
# 4 sides
output[k0:k0 + s0, :k1] = input_img[:,-k1:]
output[:k0, k1:k1 + s1] = input_img[-k0:,:]
output[-k0:, k1:s1 + k1] = input_img[:k0,:]
output[k0:s0 + k0, -k1:] = input_img[:,:k1]
elif mode != "constant": raise RuntimeError("Unknown mode")
return output
def calc_size(shape, bloc_size):
'''
returns the adapted size padded to the next multiple of bloc_size
shape: 2-tuple
bloc_size: int or tuple
'''
if "__len__" in dir(bloc_size):
return tuple ((i + j - 1) & ~(j - 1) for i,j in zip(shape,bloc_size))
else:
return tuple ((i + bloc_size - 1) & ~(bloc_size - 1) for i in shape)
| mit |
williamrodriguezb/ascensos | frontend/e2e/app.e2e-spec.ts | 305 | import { FrontedPage } from './app.po';
describe('fronted App', () => {
let page: FrontedPage;
beforeEach(() => {
page = new FrontedPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('app works!');
});
});
| mit |
bkoprucu/distributed-counter | distributedcounter-service/src/main/java/org/berk/distributedcounter/rest/CounterResource.java | 3412 | package org.berk.distributedcounter.rest;
import org.berk.distributedcounter.api.Count;
import org.berk.distributedcounter.counter.Counter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Positive;
import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping(path = "counter", produces = MediaType.APPLICATION_JSON_VALUE)
@Validated
public class CounterResource {
private final Counter counter;
public CounterResource(Counter counter) {
this.counter = counter;
}
private final Logger log = LoggerFactory.getLogger(getClass());
@PutMapping("/count/{id}")
public Mono<ResponseEntity<Void>> increment(@NotEmpty(message = "Parameter 'id' is mandatory") @PathVariable("id") String counterId,
@RequestParam(name = "amount", required = false) @Positive(message = "amount must be positive") Long amount) {
log.debug("PUT /count/{} called", counterId);
return toCancellableMono(counter.incrementAsync(counterId, amount)
.thenApply(isNewRecord -> ResponseEntity.status(isNewRecord ? HttpStatus.CREATED
: HttpStatus.OK).build()));
}
@GetMapping("/count/{id}")
public Mono<ResponseEntity<Long>> getCounter(@NotEmpty(message = "Parameter 'id' is mandatory")
@PathVariable("id") String counterId) {
return toCancellableMono(counter.getCountAsync(counterId))
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.noContent().build());
}
@DeleteMapping("/count/{id}")
public Mono<ResponseEntity<Long>> removeCounter(@NotEmpty(message = "Parameter 'id' is mandatory")
@PathVariable("id") String counterId) {
log.debug("DELETE /count/{} called", counterId);
return toCancellableMono(counter.removeAsync(counterId))
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.noContent().build());
}
@GetMapping("/list")
public Flux<Count> listCounters(@RequestParam(name = "from_index", required = false) @Min(0) Integer fromIndex,
@RequestParam(name = "item_count", required = false) @Max(500_000) @Min(1) Integer itemCount) {
log.debug("GET /list called");
return Flux.fromStream(counter.listCounters(fromIndex, itemCount));
}
@GetMapping("/listsize")
public Mono<Integer> getSize() {
log.debug("GET /listsize called");
return Mono.fromCallable(counter::getSize);
}
private <T> Mono<T> toCancellableMono(CompletableFuture<T> completableFuture) {
return Mono.fromFuture(completableFuture)
.onErrorStop()
.doOnCancel(() -> completableFuture.cancel(false));
}
}
| mit |
kfrankc/kfrankc.github.io | js/debouncedresize.js | 1127 | /*
* debouncedresize: special jQuery event that happens once after a window resize
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*/
var $event = $.event,
$special,
resizeTimeout;
$special = $event.special.debouncedresize = {
setup: function() {
$( this ).on( "resize", $special.handler );
},
teardown: function() {
$( this ).off( "resize", $special.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments,
dispatch = function() {
// set correct event type
event.type = "debouncedresize";
$event.dispatch.apply( context, args );
};
if ( resizeTimeout ) {
clearTimeout( resizeTimeout );
}
execAsap ?
dispatch() :
resizeTimeout = setTimeout( dispatch, $special.threshold );
},
threshold: 250
}; | mit |
stopsopa/stopsopa-annotations | src/Stopsopa/Annotations/Cache/MemcacheService.php | 638 | <?php
namespace Stopsopa\Annotations\Cache;
use Memcache;
/**
* Stopsopa\Annotations\Cache\MemcacheService
*/
class MemcacheService {
/**
* @var Memcache
*/
protected static $m;
protected function __construct() {}
public static function getInstance() {
if (!static::$m) {
static::$m = new Memcache();
}
return static::$m;
}
public static function addServer($host, $port = 11211) {
static::getInstance()->addServer($host, $port);
}
public static function flush() {
static::getInstance()->flush();
}
} | mit |
So-Cool/xCave | xCave/helpers.py | 1201 | """
Helper functions for xCave.
"""
import sys
def parse_config(config):
conf = {}
for section in config.sections():
conf[section] = {}
for name, raw_value in config.items(section):
try:
# Ugly fix to avoid '0' and '1' to be parsed as a boolean value.
# We raise an exception to goto fail^w parse it as integer.
if config.get(section, name) in ["0", "1"]:
raise ValueError
value = config.getboolean(section, name)
except ValueError:
try:
value = config.getint(section, name)
except ValueError:
value = config.get(section, name)
conf[section][name] = value
return conf
def curate_tuples(d, type="int"):
dd = {}
for i in d:
dd[i] = str2tuple(d[i], type)
return dd
def str2tuple(d, type="int"):
dd = None
if d.strip().lower() == "none":
return dd
st = d.strip().strip(")").strip("(").split(",")
if type == "int":
dd = (int(st[0]), int(st[1]))
elif type == "float":
dd = (float(st[0]), float(st[1]))
return dd
| mit |
TheFive/osmbc | routes/auth.js | 8259 | "use strict";
const debug = require("debug")("OSMBC:routes:auth");
const async = require("../util/async_wrap.js");
const HttpStatus = require("http-status-codes");
const config = require("../config.js");
const logger = require("../config.js").logger;
const passport = require("passport");
const OpenStreetMapStrategy = require("passport-openstreetmap").Strategy;
const userModule = require("../model/user.js");
const htmlRoot = config.htmlRoot();
// taken from: https://github.com/jaredhanson/passport-openstreetmap/blob/master/examples/login/app.js
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete OpenStreetMap profile is
// serialized and deserialized.
// in OSMBC only the displayName is relevant (as long as there is no user database)
// so this is enough for serialising.
// if there will be a user database, this has to be integrated here
passport.serializeUser(function (user, done) {
debug("passport.serializeUser CB");
const username = (user.displayName) ? user.displayName : "";
done(null, username);
});
const createGuestUsersAutomatic = config.getValue("createGuestUsersAutomatic", { mustExist: true });
passport.deserializeUser(function (user, done) {
debug("passport.deserializeUser CB");
if (typeof user !== "string") {
logger.error("deserialise user with object called, expected string");
logger.error(JSON.stringify(user, null, 2));
return done(null, null);
}
userModule.find({ OSMUser: user }, function(err, result) {
if (err) return done(null, null);
if (result.length === 1) {
const overWriteRole = config.getValue("DefineRole");
if (overWriteRole && overWriteRole[result[0].OSMUser]) {
result[0].access = overWriteRole[result[0].OSMUser];
logger.error("DefineRole Overwrite: Switching user " + result[0].OSMUser + " to access " + overWriteRole[result[0].OSMUser]);
}
return done(null, result[0]);
}
if (createGuestUsersAutomatic && result.length === 0) {
userModule.createNewUser({ OSMUser: user, access: "guest", mdWeeklyAuthor: "anonymous" }, function(err, user) {
if (err) return done(null, null);
return done(null, user);
});
return;
}
if (result.length === 0) {
// no automatic guest creation
return done(new Error("User >" + user + "< does not exist"));
}
if (result.length > 1) return done(null, null);
});
});
// taken from https://github.com/jaredhanson/passport-openstreetmap/blob/master/examples/login/app.js
// Use the OpenStreetMapStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a token, tokenSecret, and OpenStreetMap profile), and
// invoke a callback with a user object.
let Strategy = null;
if (process.env.NODE_ENV === "test") {
Strategy = require("passport-mocked").Strategy;
} else {
Strategy = OpenStreetMapStrategy;
}
passport.use(new Strategy({
name: "openstreetmap",
consumerKey: config.getValue("OPENSTREETMAP_CONSUMER_KEY", { mustExist: true }),
consumerSecret: config.getValue("OPENSTREETMAP_CONSUMER_SECRET", { mustExist: true }),
callbackURL: config.getValue("callbackUrl", { mustExist: true }),
requestTokenURL: "https://www.openstreetmap.org/oauth/request_token",
accessTokenURL: "https://www.openstreetmap.org/oauth/access_token",
userAuthorizationURL: "https://www.openstreetmap.org/oauth/authorize"
},
function (token, tokenSecret, profile, done) {
debug("passport.use Token Function");
// asynchronous verification, for effect...
process.nextTick(function () {
debug("passport.use Token Function->prozess.nextTick");
// To keep the example simple, the user's OpenStreetMap profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the OpenStreetMap account with a user record in your database,
// and return that user instead.
return done(null, profile);
});
}
));
function checkRole(role, functions) {
debug("checkRole");
let roleArray = role;
let functionsArray = functions;
if (typeof role === "string") roleArray = [role];
if (typeof functions === "function") functionsArray = [functions];
return function checkAuthentification (req, res, next) {
debug("checkAuthentification");
if (!req.isAuthenticated()) return next(new Error("Check Authentication runs in unauthenticated branch. Please inform your OSMBC Admin."));
const accessIndex = roleArray.indexOf(req.user.access);
if (accessIndex >= 0) {
if (!functionsArray) return next();
if (!functionsArray[accessIndex]) return next();
return functionsArray[accessIndex](req, res, next);
}
return res.status(HttpStatus.FORBIDDEN).send("OSM User >" + req.user.OSMUser + "< has not enough access rights");
};
}
function checkUser(user) {
debug("checkUser");
let userArray = user;
if (typeof user === "string") userArray = [user];
return function checkAuthentificationUser (req, res, next) {
debug("checkAuthentificationUser");
if (!req.isAuthenticated()) return next(new Error("Check Authentication runs in unauthenticated branch. Please inform your OSMBC Admin."));
const accessIndex = userArray.indexOf(req.user.OSMUser);
if (accessIndex >= 0) {
return next();
}
return res.status(HttpStatus.FORBIDDEN).send("OSM User >" + req.user.OSMUser + "< has not enough access rights");
};
}
function hasRole(role) {
debug("hasRole");
let roleArray = role;
if (typeof role === "string") roleArray = [role];
return function checkAuthentification (req, res, next) {
debug("checkAuthentification");
if (!req.isAuthenticated()) return next(new Error("Check Authentication runs in unauthenticated branch. Please inform your OSMBC Admin."));
if (roleArray.indexOf(req.user.access) >= 0) return next();
return next("route");
};
}
let cookieMaxAge = config.getValue("cookieMaxAge");
if (isNaN(cookieMaxAge)) {
cookieMaxAge = null;
} else {
cookieMaxAge = cookieMaxAge * 1000 * 60 * 60 * 24;
}
function ensureAuthenticated (req, res, next) {
debug("ensureAuthenticated");
debug("Requested URL: %s", req.url);
if (req.isAuthenticated()) {
debug("ensureAuthenticated: OK");
if (req.user && req.user.access && req.user.access !== "denied") {
if (!req.session.prolonged) {
req.session.cookie.maxAge = cookieMaxAge;
req.session.prolonged = true;
}
const date = new Date();
const lastStore = new Date(req.user.lastAccess);
// only store last access when GETting something, not in POSTs.
if (req.method === "GET" && (!req.user.lastAccess || (date.getTime() - lastStore.getTime()) > 1000 * 5)) {
const stamp = new Date();
req.user.lastAccess = stamp;
req.user.save({ noVersionIncrease: true }, function (err) {
if (err) return next(err);
});
}
return next();
}
if (req.user && req.user.access === "denied") {
return res.status(403).send("OSM User >" + req.user.OSMUser + "< has no access rights. Please contact weeklyOSM Team to enable your account.");
}
return res.status(403).send("OSM User >" + req.user.OSMUser + "< is not an OSMBC user.");
}
// is not authenticated
debug("ensureAuthenticated: Not OK");
async.series([
function saveReturnTo(cb) {
if (!req.session.returnTo) {
logger.info("Setting session return to to " + req.originalUrl);
req.session.returnTo = req.originalUrl;
return req.session.save(cb);
}
return cb();
}
], function(err) {
if (err) return next(err);
res.redirect(htmlRoot + "/login");
});
}
module.exports.passport = passport;
module.exports.checkRole = checkRole;
module.exports.checkUser = checkUser;
module.exports.hasRole = hasRole;
module.exports.ensureAuthenticated = ensureAuthenticated;
| mit |
Hooked74/2048 | src/app/components/Scoresheet.tsx | 408 | import * as React from 'react';
import { Component } from 'react';
interface IProps {
value:number;
}
interface IState {}
export default class ScoresheetComponent extends Component<IProps, IState> {
public render() {
return (
<div className="scoresheet">
<span>{this.props.children}</span>
{this.props.value}
</div>
);
}
} | mit |
thedespicableknight/web_crawlers | flight_ticket_jet_airways.py | 7521 | '''
This script checks for jet airways round-trip flights, and sends an mail
notifying about the combined price falling below a set threshold value.
'''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
import smtplib
while 1:
# Initialization of variables
source_date, target_date = '20', '22'
source_month, target_month = 'JANUARY', 'JANUARY'
source_year, target_year= '2019', '2019'
source_city, target_city = 'DEL', 'BLR'
source_departure_time, target_arrival_time = '15:10', '17:55'
target_departure_time, source_arrival_time, = '18:55', '21:55'
departure_price_threshold, return_price_threshold = 8000, 4000
# Navigate to appropriate flight web page
browser = webdriver.Chrome('C:/Users/ranamihir/AppData/Local/Programs/Python/Python35-32/chromedriver.exe')
browser.maximize_window()
browser.get('https://www.jetairways.com/EN/IN/home.aspx')
label = browser.find_element_by_id('roundTrip__trigger')
label.click()
source_airport = browser.find_element_by_id('ObeFlights1_autoOriginHome_AutoText')
source_airport.clear()
source_airport.send_keys(source_city)
source_airport.send_keys(Keys.ENTER)
target_airport = browser.find_element_by_id('ObeFlights1_autoDestinationHome_AutoText')
target_airport.clear()
target_airport.send_keys(target_city)
target_airport.send_keys(Keys.ENTER)
info_dict = {
'source': [source_date, source_month, source_year, 'departureCalendar'],
'target': [target_date, target_month, target_year, 'returnCalendar']
}
for key in info_dict.keys():
date, month, year, calendar_type = info_dict[key]
calendar = browser.find_element_by_id(calendar_type)
calendar.click()
while 1:
month_elements = [calendar.find_element_by_class_name('ui-datepicker-group-first'), \
calendar.find_element_by_class_name('ui-datepicker-group-last')]
month_titles = [month_elements[0].find_element_by_class_name('ui-datepicker-month').text, \
month_elements[1].find_element_by_class_name('ui-datepicker-month').text]
year_titles = [month_elements[0].find_element_by_class_name('ui-datepicker-year').text, \
month_elements[1].find_element_by_class_name('ui-datepicker-year').text]
month_index = month_titles.index(month) if month in month_titles else -1
year_index = year_titles.index(year) if year in year_titles else -1
if not (month_index != -1 and year_index != -1 and month_index == year_index):
calendar.find_element_by_class_name('ui-datepicker-next').click()
else:
break
date_element = month_elements[month_index].find_element_by_link_text(date)
date_element.click()
submit_button = browser.find_element_by_id('ObeFlights1_btnBookOnline')
submit_button.click()
# Check for price of appropriate flight
time.sleep(10)
results_dict = {
'departure': ['flight-matrix-0', source_departure_time, target_arrival_time, departure_price_threshold, 0],
'return': ['flight-matrix-1', target_departure_time, source_arrival_time, return_price_threshold, 0]
}
for key in results_dict:
result, flight_departure_time, flight_arrival_time, flight_price_threshold, _ = results_dict[key]
search_result = browser.find_element_by_id(result).find_element_by_class_name('farematrix')
flight_rows = search_result.find_elements_by_tag_name('li')
flight_row = None
for row in flight_rows:
try:
journey_info = row.find_element_by_class_name('farematrix-journey-info')
departure_time = journey_info.find_element_by_class_name('left')\
.find_element_by_class_name('journey__time').text
arrival_time = journey_info.find_element_by_class_name('right')\
.find_element_by_class_name('journey__time').text
if departure_time == flight_departure_time and arrival_time == flight_arrival_time:
flight_row = row
break
except NoSuchElementException:
continue
if not flight_row:
print('{} flight not found.'.format(key.capitalize()))
continue
fare_bucket_container = flight_row.find_element_by_class_name('fare-bucket-container')\
.find_elements_by_tag_name('li')
for e in fare_bucket_container:
if 'economy-class' in e.get_attribute('class'):
economy_fare_bucket_container = e
break
assert economy_fare_bucket_container is not None, \
'Could not find economy fare bucket container.'
best_price = None
for economy_class in economy_fare_bucket_container.find_elements_by_class_name('fare-class'):
price_element = economy_class.find_element_by_class_name('price-wrap')
if price_element.text.strip() == 'Sold Out' or best_price:
continue
for e in price_element.find_elements_by_xpath('*'):
if 'price-striked' not in e.get_attribute('class'):
best_price = e.text
best_price = int(best_price.replace('INR', '').replace(',', '').strip())
print(best_price)
if best_price <= flight_price_threshold:
results_dict[key][-1] = 1
break
if not best_price:
print('All {} economy flights seem to be sold out.'.format(key))
continue
thresholds_passed = results_dict['departure'][-1]*results_dict['return'][-1]
message_sent = 0
if thresholds_passed:
# Send mail
sender_address = '[email protected]'
receiver_address = '[email protected]'
subject = 'Jet Airways {}-{}'.format(source_city, target_city)
text = 'The price for the Jet Airways {}-{} fight ({}-{}) on {} {}, {} has gone below INR {}'\
' and for the {}-{} fight ({}-{}) on {} {}, {} has gone below INR {}. Book them now!'\
.format(source_city, target_city, source_departure_time, target_arrival_time, \
source_month, source_date, source_year, departure_price_threshold, \
target_city, source_city, target_departure_time, source_arrival_time, \
target_month, target_date, target_year, return_price_threshold)
message = 'Subject: {}\n\n{}'.format(subject, text)
# Credentials
password = '<password>'
# The actual mail send
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(sender_address, password)
server.sendmail(sender_address, receiver_address, message)
server.quit()
print('Message sent successfully.')
message_sent = 1
except Exception as e:
print(str(e))
# Keep checking after every one hour if message not sent
if not message_sent:
'Requirements not met. Checking again in 1 hour.'
time.sleep(3600)
else:
browser.quit()
break
| mit |
Neil-Ni/ng2-bootstrap-sbadmin | src/client/app/components/home/home.spec.ts | 1252 | import {
TestComponentBuilder,
describe,
expect,
injectAsync,
it,
beforeEachProviders
} from 'angular2/testing';
import {Location, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {SpyLocation} from 'angular2/src/mock/location_mock';
import {RootRouter} from 'angular2/src/router/router';
import {Component, provide} from 'angular2/core';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {HomePage} from './home';
export function main() {
beforeEachProviders(() => [
RouteRegistry,
provide(Location, {useClass: SpyLocation}),
provide(ROUTER_PRIMARY_COMPONENT, {useValue: HomePage}),
provide(Router, {useClass: RootRouter})
]);
describe('Home component', () => {
it('should work',
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(TestComponent)
.then((rootTC) => {
let homeDOMEl = rootTC.debugElement.children[0].nativeElement;
expect(DOM.querySelectorAll(homeDOMEl, 'h1')[0].textContent).toEqual('Dashboard');
});
}));
});
}
@Component({
selector: 'test-cmp',
directives: [HomePage],
template: '<dashboard></dashboard>'
})
class TestComponent {}
| mit |
justinholzer/WinIoTLibLCD16x2 | LibLCD16x2/LibLCD16x2.cpp | 5095 | #include "pch.h"
#define LIBLCD16X2_EXPORT
#include "LibLcd16x2.h"
#include "LibLcd16x2Impl.h"
#include "Details.h"
namespace LibLCD16x2
{
LibLCD16x2::LibLCD16x2(
int select_command_reg_pin,
int select_read_write_reg_pin,
int send_data_reg_pin,
const std::vector<int>& data_pins_in) :
impl(new LibLcd16x2Impl)
{
// set 8-bit or 4-bit mode based on number of data pins used.
size_t npins = data_pins_in.size();
assert(npins == 4 || npins == 8);
// Set 8-bit 2 line mode
static const std::vector<GpioPinValue> setup_values = {
GpioPinValue::Low,
GpioPinValue::Low,
GpioPinValue::High, // font type
GpioPinValue::High, // lines 1 or 2
npins == 8 ? GpioPinValue::High : GpioPinValue::Low, // data length 8-bit or 4-bit
GpioPinValue::High,
GpioPinValue::Low,
GpioPinValue::Low
};
static const std::vector<GpioPinValue> init_values = {
GpioPinValue::Low,
GpioPinValue::Low,
GpioPinValue::Low,
GpioPinValue::Low,
GpioPinValue::High,
GpioPinValue::High,
GpioPinValue::Low,
GpioPinValue::Low
};
impl->controller = GpioController::GetDefault();
impl->reg_select = impl->controller->OpenPin(select_command_reg_pin);
impl->reg_read_write = impl->controller->OpenPin(select_read_write_reg_pin);
impl->send_data_reg = impl->controller->OpenPin(send_data_reg_pin);
impl->reg_select->SetDriveMode(GpioPinDriveMode::Output);
impl->reg_read_write->SetDriveMode(GpioPinDriveMode::Output);
impl->send_data_reg->SetDriveMode(GpioPinDriveMode::Output);
for(auto pin_num : data_pins_in)
{
GpioPin^ pin = impl->controller->OpenPin(pin_num);
pin->SetDriveMode(GpioPinDriveMode::Output);
impl->data_pins.push_back(pin);
}
// Init
// Sending in 8-bit mode,
// unused data pins should be grounded if using 4 pins.
Sleep(20);
ExecuteCommand8Bit(
GpioPinValue::Low,
GpioPinValue::Low,
init_values,
*impl,
4);
Sleep(20);
ExecuteCommand8Bit(
GpioPinValue::Low,
GpioPinValue::Low,
init_values,
*impl,
4);
Sleep(10);
ExecuteCommand8Bit(
GpioPinValue::Low,
GpioPinValue::Low,
init_values,
*impl,
4);
Sleep(1);
if(npins == 4)
{
// Send 8-bit (with 4 grouned) to set 4-bit mode.
ExecuteCommand8Bit(
GpioPinValue::Low,
GpioPinValue::Low,
setup_values,
*impl,
4);
// Now set line mode and font mode using 4-bit command mode
ExecuteCommand4Bit(
GpioPinValue::Low,
GpioPinValue::Low,
setup_values,
*impl);
Sleep(20);
}
else
{
// Send 8-bit command to setup line mode and font mode.
ExecuteCommand8Bit(
GpioPinValue::Low,
GpioPinValue::Low,
setup_values,
*impl);
}
}
LibLCD16x2::~LibLCD16x2()
{
}
void
LibLCD16x2::Print(
const char* msg,
Line line,
bool clear,
int delay_ms)
{
if(clear)
Clear();
unsigned char ddram_index = line;
int index = 0;
while(msg[index] != '\0')
{
// Set address
ExecuteCommand(
GpioPinValue::Low,
GpioPinValue::Low,
ByteToDDRamPinValues(ddram_index));
ddram_index++;
// Write char to address
// Set address
ExecuteCommand(
GpioPinValue::High,
GpioPinValue::Low,
ByteToPinValues(msg[index]));
++index;
Sleep(delay_ms);
}
}
void
LibLCD16x2::DisplayCursor()
{
ExecuteCommand(
GpioPinValue::Low,
GpioPinValue::Low,
DisplayCursorData);
Sleep(1);
}
void
LibLCD16x2::Clear()
{
ExecuteCommand(
GpioPinValue::Low,
GpioPinValue::Low,
ClearData);
Sleep(1);
}
void
LibLCD16x2::ExecuteCommand(
GpioPinValue reg_select_val,
GpioPinValue reg_read_write_val,
const std::vector<GpioPinValue>& pin_values)
{
if(this->impl->data_pins.size() == 8)
{
ExecuteCommand8Bit(reg_select_val, reg_read_write_val, pin_values, *impl);
}
else
{
ExecuteCommand4Bit(reg_select_val, reg_read_write_val, pin_values, *impl);
}
}
}
| mit |
0robustus1/specroutes | spec/specroutes/utility_belt/state_based_equality_spec.rb | 3316 | require 'rails_helper'
describe Specroutes::UtilityBelt::StateBasedEquality do
context 'with default implementation of equality_state' do
let(:klass) do
class SBE_ImplementingKlass_01
include Specroutes::UtilityBelt::StateBasedEquality
def initialize(a, b)
@a, @b = a, b
end
end
SBE_ImplementingKlass_01
end
let(:instance) { klass.new(1, 2) }
let(:equal_instance) { klass.new(1, 2) }
let(:inequal_instance) { klass.new(2, 1) }
context '#==' do
it 'should accept identity as equality' do
expect(instance == instance).to be(true)
end
it 'should recognize attribute-based equality' do
expect(instance == equal_instance).to be(true)
end
it 'should recognize inequality' do
expect(instance == inequal_instance).to be(false)
end
end
context '#eql?' do
it 'should accept identity as equality' do
expect(instance == instance).to be(true)
end
it 'should recognize equality_state based equality' do
expect(instance == equal_instance).to be(true)
end
it 'should recognize inequality' do
expect(instance == inequal_instance).to be(false)
end
end
context '#hash' do
it 'should accept identity as equality' do
expect(instance.hash == instance.hash).to be(true)
end
it 'should recognize equality_state based equality' do
expect(instance.hash == equal_instance.hash).to be(true)
end
it 'should recognize inequality' do
expect(instance.hash == inequal_instance.hash).to be(false)
end
end
end
context 'with custom implementation of equality_state' do
let(:klass) do
class SBE_ImplementingKlass_02
include Specroutes::UtilityBelt::StateBasedEquality
def initialize(a, b)
@a, @b = a, b
end
def equality_state
@a
end
end
SBE_ImplementingKlass_02
end
let(:instance) { klass.new(1, 2) }
let(:equal_instance) { klass.new(1, 3) }
let(:inequal_instance) { klass.new(2, 1) }
context '#==' do
it 'should accept identity as equality' do
expect(instance == instance).to be(true)
end
it 'should recognize equality_state based equality' do
expect(instance == equal_instance).to be(true)
end
it 'should recognize inequality' do
expect(instance == inequal_instance).to be(false)
end
end
context '#eql?' do
it 'should accept identity as equality' do
expect(instance == instance).to be(true)
end
it 'should recognize equality_state based equality' do
expect(instance == equal_instance).to be(true)
end
it 'should recognize inequality' do
expect(instance == inequal_instance).to be(false)
end
end
context '#hash' do
it 'should accept identity as equality' do
expect(instance.hash == instance.hash).to be(true)
end
it 'should recognize equality_state based equality' do
expect(instance.hash == equal_instance.hash).to be(true)
end
it 'should recognize inequality' do
expect(instance.hash == inequal_instance.hash).to be(false)
end
end
end
end
| mit |
akkirilov/SoftUniProject | 04_DB Frameworks_Hibernate+Spring Data/05_DB Apps Introduction/src/entity/User.java | 959 | package entity;
import java.sql.Date;
public class User {
private Long id;
private String name;
private int age;
private Date registrationDate;
public User(String name, int age, Date registrationDate) {
super();
this.name = name;
this.age = age;
this.registrationDate = registrationDate;
}
public User(long id, String name, int age, Date registrationDate) {
super();
this.id = id;
this.name = name;
this.age = age;
this.registrationDate = registrationDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
}
| mit |
hxxft/lynx-native | Core/third_party/JavaScriptCore/jit/ICStats.cpp | 3667 | /*
* Copyright (C) 2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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.
*/
#include "config.h"
#include "ICStats.h"
namespace JSC {
bool ICEvent::operator<(const ICEvent& other) const
{
if (m_classInfo != other.m_classInfo) {
if (!m_classInfo)
return true;
if (!other.m_classInfo)
return false;
return strcmp(m_classInfo->className, other.m_classInfo->className) < 0;
}
if (m_propertyName != other.m_propertyName)
return codePointCompare(m_propertyName.string(), other.m_propertyName.string()) < 0;
return m_kind < other.m_kind;
}
void ICEvent::dump(PrintStream& out) const
{
out.print(m_kind, "(", m_classInfo ? m_classInfo->className : "<null>", ", ", m_propertyName, ")");
}
void ICEvent::log() const
{
ICStats::instance().add(*this);
}
Atomic<ICStats*> ICStats::s_instance;
ICStats::ICStats()
{
m_thread = Thread::create(
"JSC ICStats",
[this] () {
LockHolder locker(m_lock);
for (;;) {
m_condition.waitFor(
m_lock, Seconds(1), [this] () -> bool { return m_shouldStop; });
if (m_shouldStop)
break;
dataLog("ICStats:\n");
auto list = m_spectrum.buildList();
for (unsigned i = list.size(); i--;)
dataLog(" ", list[i].key, ": ", list[i].count, "\n");
}
});
}
ICStats::~ICStats()
{
{
LockHolder locker(m_lock);
m_shouldStop = true;
m_condition.notifyAll();
}
m_thread->waitForCompletion();
}
void ICStats::add(const ICEvent& event)
{
m_spectrum.add(event);
}
ICStats& ICStats::instance()
{
for (;;) {
ICStats* result = s_instance.load();
if (result)
return *result;
ICStats* newStats = new ICStats();
if (s_instance.compareExchangeWeak(nullptr, newStats))
return *newStats;
delete newStats;
}
}
} // namespace JSC
namespace WTF {
using namespace JSC;
void printInternal(PrintStream& out, ICEvent::Kind kind)
{
switch (kind) {
#define ICEVENT_KIND_DUMP(name) case ICEvent::name: out.print(#name); return;
FOR_EACH_ICEVENT_KIND(ICEVENT_KIND_DUMP);
#undef ICEVENT_KIND_DUMP
}
RELEASE_ASSERT_NOT_REACHED();
}
} // namespace WTF
| mit |
MarcoAlducinR5/ProyectoFEX | application/controllers/api/cuentageneralrest.php | 7367 | <?php defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH.'/libraries/REST_Controller.php';
class Cuentageneralrest extends REST_Controller{
function __construct(){
parent::__construct();
$this->load->model('cuentageneralmodel');
$this->load->library('sessionclass');
}
function index(){}
/*******************************Regresa el número de integrantes de la cuenta ***********************/
function getnumintegrantescuenta_GET(){
if ( $this->sessionclass->is_logged_in() == 1) {
/*Capturamos datos*/
$this->response($this->getnumerointegrantesbyidusuario());
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}/*Termina función */
/*Consultamos el número de integrantes en la cuenta por id del usuario */
function getnumerointegrantesbyidusuario(){
$iduser = $this->sessionclass->getidusuario();
$numerointegrantes = $this->cuentageneralmodel->getintegrantesbyidusuario($iduser);
return $numerointegrantes;
//return $iduser;
}/*Termina la función*/
/*************************************************************************************************************/
function getintegrantesinfocuenta_GET(){
if ( $this->sessionclass->is_logged_in() == 1) {
/*Capturamos datos*/
$this->response($this->getintegrantesinformacion());
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}/*Termina la cuenta */
function getintegrantesinformacion(){
$iduser = $this->sessionclass->getidusuario();
$integrantes = $this->cuentageneralmodel->getintegrantesinforme($iduser);
return $integrantes;
}
/*************************************************************************************************************/
function getlistperfilesfisponiblesbycuenta_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
/*Capturamos datos*/
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->getplanesbyempresa($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getplanesbyempresa($idempresa){
//select idplan from empresa where idempresa
$perfiles = $this->cuentageneralmodel->getperfilesdelacuenta($idempresa);
return $perfiles;
}
function getnumeroclientes_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getnumeroclientesnotrepeat($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getnumeroclientesenvalidacion_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getnumeroclientesenvalidacion($idempresa) );
//$this->response( $idempresa );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getnumeroclientesquehesolicitado_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$iduser = $this->sessionclass->getidusuario();
$this->response( $this->cuentageneralmodel->getnumeroclientesquehesolicitado($idempresa, $iduser));
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getnumeroclientesquemeanaprobado_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$iduser = $this->sessionclass->getidusuario();
$this->response( $this->cuentageneralmodel->getnumeroclientesquemeanaprobado($idempresa, $iduser) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getnumeroclientesrechazados_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$iduser = $this->sessionclass->getidusuario();
$this->response( $this->cuentageneralmodel->getnumeroclientesrechazados($idempresa, $iduser) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getNumeroOmisionesGraves_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getNumeroOmisionesGraves($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getNumeroSinOmisiones_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getNumeroSinOmisiones($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getNumeroConOmisiones_get(){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getNumeroConOmisiones($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getNumeroPersonaFisica_get($idempresa){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getNumeroPersonaFisica($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
function getNumeroPersonaMoral_get($idempresa){
if ( $this->sessionclass->is_logged_in() == 1) {
$idempresa = $this->sessionclass->getidempresa();
$this->response( $this->cuentageneralmodel->getNumeroPersonaMoral($idempresa) );
/*Cuando no hay session*/
}else{
$this->sessionclass->logout();
}
}
/*Termina rest*/
}
?>
| mit |
OptimalPayments/node-js_SDK | lib/OptimalApiClient.js | 8488 |
/*
* Copyright (c) 2016 Paysafe
*
* 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.
*/
/**
* author: Anup W.
*/
var cardServiceHandler = require("./CardServiceHandler");
var CustomerServiceHandler = require("./CustomerServiceHandler");
var HostedApiServiceHandler = require("./HostedApiServiceHandler");
var DirectDebitServiceHandler = require("./DirectDebitServiceHandler");
var ThreeDsecureServiceHandler = require("./ThreeDsecureServiceHandler");
var Environment = require("../bin/Environment");
var errorClass = require("./common/error");
var request = require('request');
var OptimalApiClient = function(apiKey, apiPassword, environment, accountNumber) {
try {
var env = Environment[environment];
if (apiKey && apiPassword && environment && accountNumber && env) {
this._apiKey = apiKey;
this._apiPassword = apiPassword;
this._environment = Environment[environment];
this._accountNumber = accountNumber;
this.Card = require("./cardpayments/card");
this.AccordD = require("./cardpayments/accordD");
this.Authentication = require("./cardpayments/authentication");
this.Authorization = require("./cardpayments/authorization");
this.AuthorizationReversal = require("./cardpayments/authorizationreversal");
this.BillingDetails = require("./cardpayments/billingDetails");
this.CardExpiry = require("./cardpayments/cardExpiry");
this.MasterPass = require("./cardpayments/masterPass");
this.MerchantDescriptor = require("./cardpayments/merchantDescriptor");
this.Pagination = require("./cardpayments/pagination");
this.RecipientDateOfBirth = require("./cardpayments/recipientDateOfBirth");
this.Refund = require("./cardpayments/refund");
this.Settlements = require("./cardpayments/settlements");
this.ShippingDetails = require("./cardpayments/shippingDetails");
this.Verification = require("./cardpayments/verification");
this.VisaAdditionalAuthData = require("./cardpayments/visaAdditionalAuthData");
this.Address = require("./customervault/addresses");
this.Dateofbirth = require("./customervault/dateofbirth");
this.Profiles = require("./customervault/profiles");
this.ACHBankAccounts = require("./customervault/ACHBankAccounts");
this.BACSBankAccounts = require("./customervault/BACSBankAccounts");
this.EFTBankAccounts = require("./customervault/EFTBankAccounts");
this.SEPABankAccounts = require("./customervault/SEPABankAccounts");
this.Mandates = require("./customervault/mandates");
this.AddendumData = require("./hostedpayment/addendumData");
this.AssociatedTransactions = require("./hostedpayment/associatedTransactions");
this.ExtendedOptions = require("./hostedpayment/extendedOptions");
this.Order = require("./hostedpayment/order");
this.Transaction = require("./hostedpayment/transaction");
this.Redirect = require("./hostedpayment/redirect");
this.ShoppingCart = require("./hostedpayment/shoppingCart");
this.Navigation = require("./hostedpayment/navigation");
this.Purchases = require("./directdebit/purchases");
this.Standalonecredits = require("./directdebit/standalonecredits");
this.Enrollmentchecks = require("./threedsecure/enrollmentchecks");
this.authentication = require("./threedsecure/authentications");
this.error = function(code, message) {
return (new errorClass({
"code" : code,
"message" : message,
}));
};
} else if (!apiKey) {
throw "Please provide API key!";
} else if (!apiPassword) {
throw "Please provide API password!";
} else if (!environment) {
throw "Please provide Environment string i.e 'TEST' or 'LIVE'!";
} else if (!Environment[environment]) {
throw "Environment string must be 'TEST' or 'LIVE'!";
} else if (!accountNumber) {
throw "Please provide Merchant Account Number!";
}
} catch (error) {
console.error(error);
}
};
var serializeObject = function(obj) {
if (obj === null) {
return "";
} else {
return JSON.stringify(obj);
}
};
var deSerializeObject = function(obj) {
if (obj === null) {
return "";
} else {
return JSON.parse(obj);
}
};
var prepareApiCredential = function(apiKey, apiPassword) {
var apiCredential = apiKey + ":" + apiPassword;
var apiCredBuffer = new Buffer(apiCredential);
return apiCredBuffer.toString("Base64");
};
var prepareRequestParameter = function(requestObject) {
if (requestObject !== null) {
return serializeObject(requestObject);
} else {
return '';
}
};
var cardService;
OptimalApiClient.prototype.cardServiceHandler = function(optimalApiClient) {
if (!cardService) {
cardService = new cardServiceHandler(optimalApiClient);
}
return cardService;
};
var customerService;
OptimalApiClient.prototype.CustomerServiceHandler = function(optimalApiClient) {
if (!customerService) {
customerService = new CustomerServiceHandler(optimalApiClient);
}
return customerService;
};
var hostedPaymentService;
OptimalApiClient.prototype.HostedApiServiceHandler = function(optimalApiClient) {
if (!hostedPaymentService) {
hostedPaymentService = new HostedApiServiceHandler(optimalApiClient);
}
return hostedPaymentService;
};
var directDebitService;
OptimalApiClient.prototype.DirectDebitServiceHandler = function(optimalApiClient) {
if (!directDebitService) {
directDebitService = new DirectDebitServiceHandler(optimalApiClient);
}
return directDebitService;
};
var threeDsecureService;
OptimalApiClient.prototype.ThreeDsecureServiceHandler = function(optimalApiClient) {
if (!threeDsecureService) {
threeDsecureService = new ThreeDsecureServiceHandler(optimalApiClient);
}
return threeDsecureService;
};
OptimalApiClient.prototype.processRequest = function(optPayRequest,
requestObject, responseCallBack) {
var self = this;
var requestJson = prepareRequestParameter(requestObject);
var reqHeaders = {
'Content-Type' : 'application/json; charset=utf-8',
// 'Content-Length': requestJson.length,
'Authorization' : 'Basic '
+ prepareApiCredential(self._apiKey, self._apiPassword)
};
var strRegObject = serializeObject(requestObject);
var options = {
headers : reqHeaders,
uri : optPayRequest.buildUrl(self._environment._host),
method : optPayRequest._method,
body : strRegObject,
pool : {
maxSockets : self._environment.maxSockets
},
timeout : self._environment.timeout
};
//console.log(options);
request(options, function(error, response, body) {
//console.log(error);
//console.log("body request"+body);
if (!error && response.statusCode !== 503) {
// in case of delete method the response is empty string
if (body) {
body = typeof (body) === "string" ? deSerializeObject(body) : body;
responseCallBack(null, body);
} else {
var delResp = {
"status" : response.statusCode
};
responseCallBack(null, delResp);
}
} else {
if (error) {
responseCallBack(self.error(error.code,
"Connection error : No internet Connection available : "
+ error.syscall), null);
} else {
responseCallBack(self.error(response.statusCode, body), null);
}
}
});
};
OptimalApiClient.prototype.updateConfig = function(host, maxSockets, timeout) {
var self = this;
self._environment = Environment.createEnv(host, maxSockets, timeout);
};
module.exports = OptimalApiClient;
| mit |
isitecnologia/php-activerecord | sys/phpac/lib/Validations.php | 24341 | <?php
/**
* These two classes have been <i>heavily borrowed</i> from Ruby on Rails' ActiveRecord so much that
* this piece can be considered a straight port. The reason for this is that the vaildation process is
* tricky due to order of operations/events. The former combined with PHP's odd typecasting means
* that it was easier to formulate this piece base on the rails code.
*
* @package ActiveRecord
*/
namespace ActiveRecord;
use ActiveRecord\Model;
use IteratorAggregate;
use ArrayIterator;
/**
* Manages validations for a {@link Model}.
*
* This class isn't meant to be directly used. Instead you define
* validators thru static variables in your {@link Model}. Example:
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_length_of = array(
* array('name', 'within' => array(30,100),
* array('state', 'is' => 2)
* );
* }
*
* $person = new Person();
* $person->name = 'Tito';
* $person->state = 'this is not two characters';
*
* if (!$person->is_valid())
* print_r($person->errors);
* </code>
*
* @package ActiveRecord
* @see Errors
* @link http://www.phpactiverecord.org/guides/validations
*/
class Validations
{
private $model;
private $options = array();
private $validators = array();
private $record;
private static $VALIDATION_FUNCTIONS = array(
'validates_presence_of',
'validates_size_of',
'validates_length_of',
'validates_inclusion_of',
'validates_exclusion_of',
'validates_format_of',
'validates_numericality_of',
'validates_uniqueness_of'
);
private static $DEFAULT_VALIDATION_OPTIONS = array(
'on' => 'save',
'allow_null' => false,
'allow_blank' => false,
'message' => null,
);
private static $ALL_RANGE_OPTIONS = array(
'is' => null,
'within' => null,
'in' => null,
'minimum' => null,
'maximum' => null,
);
private static $ALL_NUMERICALITY_CHECKS = array(
'greater_than' => null,
'greater_than_or_equal_to' => null,
'equal_to' => null,
'less_than' => null,
'less_than_or_equal_to' => null,
'odd' => null,
'even' => null
);
/**
* Constructs a {@link Validations} object.
*
* @param Model $model The model to validate
* @return Validations
*/
public function __construct(Model $model)
{
$this->model = $model;
$this->record = new Errors($this->model);
$this->klass = Reflections::instance()->get(get_class($this->model));
$this->validators = array_intersect(array_keys($this->klass->getStaticProperties()), self::$VALIDATION_FUNCTIONS);
}
public function get_record()
{
return $this->record;
}
/**
* Returns validator data.
*
* @return array
*/
public function rules()
{
$data = array();
foreach ($this->validators as $validate)
{
$attrs = $this->klass->getStaticPropertyValue($validate);
foreach (wrap_strings_in_arrays($attrs) as $attr)
{
$field = $attr[0];
if (!isset($data[$field]) || !is_array($data[$field]))
$data[$field] = array();
$attr['validator'] = $validate;
unset($attr[0]);
array_push($data[$field],$attr);
}
}
return $data;
}
/**
* Runs the validators.
*
* @return Errors the validation errors if any
*/
public function validate()
{
foreach ($this->validators as $validate)
{
$definition = $this->klass->getStaticPropertyValue($validate);
$this->$validate(wrap_strings_in_arrays($definition));
}
$model_reflection = Reflections::instance()->get($this->model);
if ($model_reflection->hasMethod('validate') && $model_reflection->getMethod('validate')->isPublic())
$this->model->validate();
$this->record->clear_model();
return $this->record;
}
/**
* Validates a field is not null and not blank.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_presence_of = array(
* array('first_name'),
* array('last_name')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_presence_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['blank'], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$this->record->add_on_blank($options[0], $options['message']);
}
}
/**
* Validates that a value is included the specified array.
*
* <code>
* class Car extends ActiveRecord\Model {
* static $validates_inclusion_of = array(
* array('fuel_type', 'in' => array('hyrdogen', 'petroleum', 'electric')),
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_inclusion_of($attrs)
{
$this->validates_inclusion_or_exclusion_of('inclusion', $attrs);
}
/**
* This is the opposite of {@link validates_include_of}.
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
* @see validates_inclusion_of
*/
public function validates_exclusion_of($attrs)
{
$this->validates_inclusion_or_exclusion_of('exclusion', $attrs);
}
/**
* Validates that a value is in or out of a specified list of values.
*
* Available options:
*
* <ul>
* <li><b>in/within:</b> attribute should/shouldn't be a value within an array</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @see validates_inclusion_of
* @see validates_exclusion_of
* @param string $type Either inclusion or exclusion
* @param $attrs Validation definition
*/
public function validates_inclusion_or_exclusion_of($type, $attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES[$type], 'on' => 'save'));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
if (isset($options['in']))
$enum = $options['in'];
elseif (isset($options['within']))
$enum = $options['within'];
if (!is_array($enum))
array($enum);
$message = str_replace('%s', $var, $options['message']);
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if (('inclusion' == $type && !in_array($var, $enum)) || ('exclusion' == $type && in_array($var, $enum)))
$this->record->add($attribute, $message);
}
}
/**
* Validates that a value is numeric.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_numericality_of = array(
* array('salary', 'greater_than' => 19.99, 'less_than' => 99.99)
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>only_integer:</b> value must be an integer (e.g. not a float)</li>
* <li><b>even:</b> must be even</li>
* <li><b>odd:</b> must be odd"</li>
* <li><b>greater_than:</b> must be greater than specified number</li>
* <li><b>greater_than_or_equal_to:</b> must be greater than or equal to specified number</li>
* <li><b>equal_to:</b> ...</li>
* <li><b>less_than:</b> ...</li>
* <li><b>less_than_or_equal_to:</b> ...</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_numericality_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('only_integer' => false));
// Notice that for fixnum and float columns empty strings are converted to nil.
// Validates whether the value of the specified attribute is numeric by trying to convert it to a float with Kernel.Float
// (if only_integer is false) or applying it to the regular expression /\A[+\-]?\d+\Z/ (if only_integer is set to true).
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
$numericalityOptions = array_intersect_key(self::$ALL_NUMERICALITY_CHECKS, $options);
if ($this->is_null_with_option($var, $options))
continue;
$not_a_number_message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES['not_a_number']);
if (true === $options['only_integer'] && !is_integer($var))
{
if (!preg_match('/\A[+-]?\d+\Z/', (string)($var)))
{
$this->record->add($attribute, $not_a_number_message);
continue;
}
}
else
{
if (!is_numeric($var))
{
$this->record->add($attribute, $not_a_number_message);
continue;
}
$var = (float)$var;
}
foreach ($numericalityOptions as $option => $check)
{
$option_value = $options[$option];
$message = (isset($options['message']) ? $options['message'] : Errors::$DEFAULT_ERROR_MESSAGES[$option]);
if ('odd' != $option && 'even' != $option)
{
$option_value = (float)$options[$option];
if (!is_numeric($option_value))
throw new ValidationsArgumentError("$option must be a number");
$message = str_replace('%d', $option_value, $message);
if ('greater_than' == $option && !($var > $option_value))
$this->record->add($attribute, $message);
elseif ('greater_than_or_equal_to' == $option && !($var >= $option_value))
$this->record->add($attribute, $message);
elseif ('equal_to' == $option && !($var == $option_value))
$this->record->add($attribute, $message);
elseif ('less_than' == $option && !($var < $option_value))
$this->record->add($attribute, $message);
elseif ('less_than_or_equal_to' == $option && !($var <= $option_value))
$this->record->add($attribute, $message);
}
else
{
if (('odd' == $option && !Utils::is_odd($var)) || ('even' == $option && Utils::is_odd($var)))
$this->record->add($attribute, $message);
}
}
}
}
/**
* Alias of {@link validates_length_of}
*
* @param array $attrs Validation definition
*/
public function validates_size_of($attrs)
{
$this->validates_length_of($attrs);
}
/**
* Validates that a value is matches a regex.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_format_of = array(
* array('email', 'with' => '/^.*?@.*$/')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>with:</b> a regular expression</li>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_format_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array('message' => Errors::$DEFAULT_ERROR_MESSAGES['invalid'], 'on' => 'save', 'with' => null));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$attribute = $options[0];
$var = $this->model->$attribute;
if (is_null($options['with']) || !is_string($options['with']) || !is_string($options['with']))
throw new ValidationsArgumentError('A regular expression must be supplied as the [with] option of the configuration array.');
else
$expression = $options['with'];
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if (!@preg_match($expression, $var))
$this->record->add($attribute, $options['message']);
}
}
/**
* Validates the length of a value.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_length_of = array(
* array('name', 'within' => array(1,50))
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>is:</b> attribute should be exactly n characters long</li>
* <li><b>in/within:</b> attribute should be within an range array(min,max)</li>
* <li><b>maximum/minimum:</b> attribute should not be above/below respectively</li>
* <li><b>message:</b> custome error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings. (Even if this is set to false, a null string is always shorter than a maximum value.)</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_length_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
'too_long' => Errors::$DEFAULT_ERROR_MESSAGES['too_long'],
'too_short' => Errors::$DEFAULT_ERROR_MESSAGES['too_short'],
'wrong_length' => Errors::$DEFAULT_ERROR_MESSAGES['wrong_length']
));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$range_options = array_intersect(array_keys(self::$ALL_RANGE_OPTIONS), array_keys($attr));
sort($range_options);
switch (sizeof($range_options))
{
case 0:
throw new ValidationsArgumentError('Range unspecified. Specify the [within], [maximum], or [is] option.');
case 1:
break;
default:
throw new ValidationsArgumentError('Too many range options specified. Choose only one.');
}
$attribute = $options[0];
$var = $this->model->$attribute;
if ($this->is_null_with_option($var, $options) || $this->is_blank_with_option($var, $options))
continue;
if ($range_options[0] == 'within' || $range_options[0] == 'in')
{
$range = $options[$range_options[0]];
if (!(Utils::is_a('range', $range)))
throw new ValidationsArgumentError("$range_option must be an array composing a range of numbers with key [0] being less than key [1]");
$range_options = array('minimum', 'maximum');
$attr['minimum'] = $range[0];
$attr['maximum'] = $range[1];
}
foreach ($range_options as $range_option)
{
$option = $attr[$range_option];
if ((int)$option <= 0)
throw new ValidationsArgumentError("$range_option value cannot use a signed integer.");
if (is_float($option))
throw new ValidationsArgumentError("$range_option value cannot use a float for length.");
if (!($range_option == 'maximum' && is_null($this->model->$attribute)))
{
$messageOptions = array('is' => 'wrong_length', 'minimum' => 'too_short', 'maximum' => 'too_long');
if (isset($options['message']))
$message = $options['message'];
else
$message = $options[$messageOptions[$range_option]];
$message = str_replace('%d', $option, $message);
$attribute_value = $this->model->$attribute;
$len = strlen($attribute_value);
$value = (int)$attr[$range_option];
if ('maximum' == $range_option && $len > $value)
$this->record->add($attribute, $message);
if ('minimum' == $range_option && $len < $value)
$this->record->add($attribute, $message);
if ('is' == $range_option && $len !== $value)
$this->record->add($attribute, $message);
}
}
}
}
/**
* Validates the uniqueness of a value.
*
* <code>
* class Person extends ActiveRecord\Model {
* static $validates_uniqueness_of = array(
* array('name'),
* array(array('blah','bleh'), 'message' => 'blech')
* );
* }
* </code>
*
* Available options:
*
* <ul>
* <li><b>with:</b> a regular expression</li>
* <li><b>message:</b> custom error message</li>
* <li><b>allow_blank:</b> allow blank strings</li>
* <li><b>allow_null:</b> allow null strings</li>
* </ul>
*
* @param array $attrs Validation definition
*/
public function validates_uniqueness_of($attrs)
{
$configuration = array_merge(self::$DEFAULT_VALIDATION_OPTIONS, array(
'message' => Errors::$DEFAULT_ERROR_MESSAGES['unique']
));
foreach ($attrs as $attr)
{
$options = array_merge($configuration, $attr);
$pk = $this->model->get_primary_key();
$pk_value = $this->model->$pk[0];
if (is_array($options[0]))
{
$add_record = join("_and_", $options[0]);
$fields = $options[0];
}
else
{
$add_record = $options[0];
$fields = array($options[0]);
}
$sql = "";
$conditions = array("");
if ($pk_value === null)
$sql = "{$pk[0]} is not null";
else
{
$sql = "{$pk[0]}!=?";
array_push($conditions,$pk_value);
}
foreach ($fields as $field)
{
$field = $this->model->get_real_attribute_name($field);
$sql .= " and {$field}=?";
array_push($conditions,$this->model->$field);
}
$conditions[0] = $sql;
if ($this->model->exists(array('conditions' => $conditions)))
$this->record->add($add_record, $options['message']);
}
}
private function is_null_with_option($var, &$options)
{
return (is_null($var) && (isset($options['allow_null']) && $options['allow_null']));
}
private function is_blank_with_option($var, &$options)
{
return (Utils::is_blank($var) && (isset($options['allow_blank']) && $options['allow_blank']));
}
}
/**
* Class that holds {@link Validations} errors.
*
* @package ActiveRecord
*/
class Errors implements IteratorAggregate
{
private $model;
private $errors;
public static $DEFAULT_ERROR_MESSAGES = array(
'inclusion' => "is not included in the list",
'exclusion' => "is reserved",
'invalid' => "is invalid",
'confirmation' => "doesn't match confirmation",
'accepted' => "must be accepted",
'empty' => "can't be empty",
'blank' => "deve ser preenchido",
'too_long' => "is too long (maximum is %d characters)",
'too_short' => "is too short (minimum is %d characters)",
'wrong_length' => "is the wrong length (should be %d characters)",
'taken' => "has already been taken",
'not_a_number' => "is not a number",
'greater_than' => "must be greater than %d",
'equal_to' => "must be equal to %d",
'less_than' => "must be less than %d",
'odd' => "must be odd",
'even' => "must be even",
'unique' => "must be unique",
'less_than_or_equal_to' => "must be less than or equal to %d",
'greater_than_or_equal_to' => "must be greater than or equal to %d"
);
/**
* Constructs an {@link Errors} object.
*
* @param Model $model The model the error is for
* @return Errors
*/
public function __construct(Model $model)
{
$this->model = $model;
}
/**
* Nulls $model so we don't get pesky circular references. $model is only needed during the
* validation process and so can be safely cleared once that is done.
*/
public function clear_model()
{
$this->model = null;
}
/**
* Add an error message.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add($attribute, $msg)
{
if (is_null($msg))
$msg = self :: $DEFAULT_ERROR_MESSAGES['invalid'];
if (!isset($this->errors[$attribute]))
$this->errors[$attribute] = array($msg);
else
$this->errors[$attribute][] = $msg;
}
/**
* Adds an error message only if the attribute value is {@link http://www.php.net/empty empty}.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add_on_empty($attribute, $msg)
{
if (empty($msg))
$msg = self::$DEFAULT_ERROR_MESSAGES['empty'];
if (empty($this->model->$attribute))
$this->add($attribute, $msg);
}
/**
* Retrieve error messages for an attribute.
*
* @param string $attribute Name of an attribute on the model
* @return array or null if there is no error.
*/
public function __get($attribute)
{
if (!isset($this->errors[$attribute]))
return null;
return $this->errors[$attribute];
}
/**
* Adds the error message only if the attribute value was null or an empty string.
*
* @param string $attribute Name of an attribute on the model
* @param string $msg The error message
*/
public function add_on_blank($attribute, $msg)
{
if (!$msg)
$msg = self::$DEFAULT_ERROR_MESSAGES['blank'];
if (($value = $this->model->$attribute) === '' || $value === null)
$this->add($attribute, $msg);
}
/**
* Returns true if the specified attribute had any error messages.
*
* @param string $attribute Name of an attribute on the model
* @return boolean
*/
public function is_invalid($attribute)
{
return isset($this->errors[$attribute]);
}
/**
* Returns the error message(s) for the specified attribute or null if none.
*
* @param string $attribute Name of an attribute on the model
* @return string/array Array of strings if several error occured on this attribute.
*/
public function on($attribute)
{
$errors = $this->$attribute;
return $errors && count($errors) == 1 ? $errors[0] : $errors;
}
/**
* Returns the internal errors object.
*
* <code>
* $model->errors->get_raw_errors();
*
* # array(
* # "name" => array("can't be blank"),
* # "state" => array("is the wrong length (should be 2 chars)",
* # )
* </code>
*/
public function get_raw_errors()
{
return $this->errors;
}
/**
* Returns all the error messages as an array.
*
* <code>
* $model->errors->full_messages();
*
* # array(
* # "Name can't be blank",
* # "State is the wrong length (should be 2 chars)"
* # )
* </code>
*
* @return array
*/
public function full_messages()
{
$full_messages = array();
$this->to_array(function($attribute, $message) use (&$full_messages) {
$full_messages[] = $message;
});
return $full_messages;
}
/**
* Returns all the error messages as an array, including error key.
*
* <code>
* $model->errors->errors();
*
* # array(
* # "name" => array("Name can't be blank"),
* # "state" => array("State is the wrong length (should be 2 chars)")
* # )
* </code>
*
* @param array $closure Closure to fetch the errors in some other format (optional)
* This closure has the signature function($attribute, $message)
* and is called for each available error message.
* @return array
*/
public function to_array($closure=null)
{
$errors = array();
if ($this->errors)
{
foreach ($this->errors as $attribute => $messages)
{
foreach ($messages as $msg)
{
if (is_null($msg))
continue;
$errors[$attribute][] = ($message = Utils::human_attribute($attribute) . ' ' . $msg);
if ($closure)
$closure($attribute,$message);
}
}
}
return $errors;
}
/**
* Convert all error messages to a String.
* This function is called implicitely if the object is casted to a string:
*
* <code>
* echo $error;
*
* # "Name can't be blank\nState is the wrong length (should be 2 chars)"
* </code>
* @return string
*/
public function __toString()
{
return implode("^", $this->full_messages());
}
/**
* Returns true if there are no error messages.
* @return boolean
*/
public function is_empty()
{
return empty($this->errors);
}
/**
* Clears out all error messages.
*/
public function clear()
{
$this->errors = array();
}
/**
* Returns the number of error messages there are.
* @return int
*/
public function size()
{
if ($this->is_empty())
return 0;
$count = 0;
foreach ($this->errors as $attribute => $error)
$count += count($error);
return $count;
}
/**
* Returns an iterator to the error messages.
*
* This will allow you to iterate over the {@link Errors} object using foreach.
*
* <code>
* foreach ($model->errors as $msg)
* echo "$msg\n";
* </code>
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->full_messages());
}
};
?>
| mit |
KatsuYuzu/Citrus.Interactions | Citrus.Interactions/Sample/Sample.WindowsPhone/Properties/AssemblyInfo.cs | 1058 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sample.WindowsPhone")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample.WindowsPhone")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | mit |
mp2apps/pesetacoin-master | src/net.cpp | 57438 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "net.h"
#include "init.h"
#include "addrman.h"
#include "ui_interface.h"
#include "script.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
uint64 nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
static CNode* pnodeSync = NULL;
uint64 nLocalHostNonce = 0;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
boost::this_thread::interruption_point();
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = NULL;
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
//rampa
/**/
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
/**/
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
X(nSendBytes);
X(nRecvBytes);
X(nBlocksRequested);
stats.fSyncNode = (this == pnodeSync);
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
vRecv.resize(hdr.nMessageSize);
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (
pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "PesetaCoin " + FormatFullVersion();
try {
loop {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
MilliSleep(20*60*1000); // Refresh every 20 minutes
}
}
catch (boost::thread_interrupted)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strMainNetDNSSeed[][2] = {
{"pesetacoin.info", "dnsseed.pesetacoin.info"},
{NULL, NULL}
};
static const char *strTestNetDNSSeed[][2] = {
{"pesetacoin.info", "dnsseed-testnet.pesetacoin.info"},
{NULL, NULL}
};
void ThreadDNSAddressSeed()
{
static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed;
int found = 0;
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0xB9B24A4C, // 76.74.178.185
0x0F5ABB25, // 37.187.90.15
0x499BF1C0, // 192.241.155.73
0xC15EBB6A, // 106.187.94.193
0x28851955, // 85.25.133.40
0x5ED2EE5B, // 91.238.210.94
0x9D3B2A2E, // 46.42.59.157
0x3128FD17, // 23.253.40.49
0xD3F81155, // 85.17.248.211
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while(true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH(string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++)
{
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, lAddresses)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
CNode* pnode = ConnectNode(addrConnect, strDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
// for now, use a very simple selection metric: the node from which we received
// most recently
double static NodeSyncScore(const CNode *pnode) {
return -pnode->nLastRecv;
}
void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
double dBestScore = 0;
// fImporting and fReindex are accessed out of cs_main here, but only
// as an optimization - they are checked again in SendMessages.
if (fImporting || fReindex)
return;
// Iterate over all nodes
BOOST_FOREACH(CNode* pnode, vNodes) {
// check preconditions for allowing a sync
if (!pnode->fClient && !pnode->fOneShot &&
!pnode->fDisconnect && pnode->fSuccessfullyConnected &&
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
double dScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || dScore > dBestScore) {
pnodeNewSync = pnode;
dBestScore = dScore;
}
}
}
// if a new sync candidate was found, start sync!
if (pnodeNewSync) {
pnodeNewSync->fStartSync = true;
pnodeSync = pnodeNewSync;
}
}
void ThreadMessageHandler()
{
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true)
{
bool fHaveSyncNode = false;
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy) {
pnode->AddRef();
if (pnode == pnodeSync)
fHaveSyncNode = true;
}
}
if (!fHaveSyncNode)
StartSync(vNodesCopy);
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (!ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize())
{
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
{
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
MilliSleep(100);
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. PesetaCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(boost::thread_group& threadGroup)
{
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed));
#ifdef USE_UPNP
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", USE_UPNP));
#endif
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
}
bool StopNode()
{
printf("StopNode()\n");
GenerateBitcoins(false, NULL);
MapPort(false);
nTransactionsUpdated++;
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
// clean up some globals (to help leak detection)
BOOST_FOREACH(CNode *pnode, vNodes)
delete pnode;
BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter)
{
if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
| mit |
portchris/NaturalRemedyCompany | src/app/code/core/Mage/Customer/Model/Api2/Customer/Rest/Admin/V1.php | 2387 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Customer
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* API2 class for customer (admin)
*
* @category Mage
* @package Mage_Customer
* @author Magento Core Team <[email protected]>
*/
class Mage_Customer_Model_Api2_Customer_Rest_Admin_V1 extends Mage_Customer_Model_Api2_Customer_Rest
{
/**
* Retrieve information about customer
* Add last logged in datetime
*
* @throws Mage_Api2_Exception
* @return array
*/
protected function _retrieve()
{
/** @var $log Mage_Log_Model_Customer */
$log = Mage::getModel('log/customer');
$log->loadByCustomer($this->getRequest()->getParam('id'));
$data = parent::_retrieve();
$data['is_confirmed'] = (int) !(isset($data['confirmation']) && $data['confirmation']);
$lastLoginAt = $log->getLoginAt();
if (null !== $lastLoginAt) {
$data['last_logged_in'] = $lastLoginAt;
}
return $data;
}
/**
* Delete customer
*/
protected function _delete()
{
/** @var $customer Mage_Customer_Model_Customer */
$customer = parent::_loadCustomerById($this->getRequest()->getParam('id'));
try {
$customer->delete();
} catch (Mage_Core_Exception $e) {
$this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
} catch (Exception $e) {
$this->_critical(self::RESOURCE_INTERNAL_ERROR);
}
}
}
| mit |
mmartensson/creative-atrocities | lib/creative-atrocities/logstyle.js | 1490 | /* Based on https://github.com/einaros/tinycolor */
'use strict';
var stringStyles = {
'arg' : [
function() { return '\u001b[37m"\u001b[35m' + this + '\u001b[37m"\u001b[39m'; },
function() { return '"' + this + '"'; }
],
'ctx' : [
function() { return '\u001b[37m[\u001b[36m' + this + '\u001b[37m]\u001b[39m'; },
function() { return '"' + this + '"'; }
],
'err' : [
function() { return '\u001b[31m' + this + '\u001b[39m'; },
function() { return '"' + this + '"'; }
],
'info' : [
function() { return '\u001b[32m' + this + '\u001b[39m'; },
function() { return '"' + this + '"'; }
],
'warn' : [
function() { return '\u001b[33m' + this + '\u001b[39m'; },
function() { return '"' + this + '"'; }
]
};
var numberStyles = {
'arg' : [
function() { return '\u001b[35m' + this + '\u001b[39m'; },
function() { return '"' + this + '"'; }
]
};
exports.setup = function(color) {
Object.keys(stringStyles).forEach(function(style) {
Object.defineProperty(String.prototype, style, {
get: color ? stringStyles[style][0] : stringStyles[style][1],
enumerable: false
});
});
Object.keys(numberStyles).forEach(function(style) {
Object.defineProperty(Number.prototype, style, {
get: color ? numberStyles[style][0] : numberStyles[style][1],
enumerable: false
});
});
};
| mit |
jamieshepherd/tygr | resources/views/account/index.blade.php | 1240 | @extends('_layout.base')
@section('body')
<body>
@include('_layout.nav')
<div id="main">
<header>
@if(Auth::user())
<a class="signout action nofill green" href="/auth/logout"><i class="fa fa-sign-out"></i> Sign out</a>
<div class="crumbtrail">
<a href="/">Home</a>
<i class="fa fa-angle-right"></i>
<a href="/account">Account</a>
</div>
@endif
<h1>Account</h1>
</header>
<a class="action yellow" href="/account/edit"><i class="fa fa-edit"></i> Edit details</a>
<a class="action yellow" href="/account/edit"><i class="fa fa-lock"></i> Change password</a>
<h2>Full name</h2>
<p>{{ Auth::user()->name }}</p>
<h2>Email address</h2>
<p>{{ Auth::user()->email }}</p>
<h2>Organisation</h2>
<p>{{ Auth::user()->client->name }}</p>
@if(Auth::user()->rank != 3)
<h2>Groups</h2>
<ul class="standard">
@foreach(Auth::user()->groups()->get() as $group)
<li>{{{ $group->name }}}</li>
@endforeach
</ul>
@endif
</div>
@stop
| mit |
WoodyNaDobhar/interquest | tests/NpcRepositoryTest.php | 1857 | <?php
use App\Models\Npc;
use App\Repositories\NpcRepository;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class NpcRepositoryTest extends TestCase
{
use MakeNpcTrait, ApiTestTrait, DatabaseTransactions;
/**
* @var NpcRepository
*/
protected $npcRepo;
public function setUp()
{
parent::setUp();
$this->npcRepo = App::make(NpcRepository::class);
}
/**
* @test create
*/
public function testCreateNpc()
{
$npc = $this->fakeNpcData();
$createdNpc = $this->npcRepo->create($npc);
$createdNpc = $createdNpc->toArray();
$this->assertArrayHasKey('id', $createdNpc);
$this->assertNotNull($createdNpc['id'], 'Created Npc must have id specified');
$this->assertNotNull(Npc::find($createdNpc['id']), 'Npc with given id must be in DB');
$this->assertModelData($npc, $createdNpc);
}
/**
* @test read
*/
public function testReadNpc()
{
$npc = $this->makeNpc();
$dbNpc = $this->npcRepo->find($npc->id);
$dbNpc = $dbNpc->toArray();
$this->assertModelData($npc->toArray(), $dbNpc);
}
/**
* @test update
*/
public function testUpdateNpc()
{
$npc = $this->makeNpc();
$fakeNpc = $this->fakeNpcData();
$updatedNpc = $this->npcRepo->update($fakeNpc, $npc->id);
$this->assertModelData($fakeNpc, $updatedNpc->toArray());
$dbNpc = $this->npcRepo->find($npc->id);
$this->assertModelData($fakeNpc, $dbNpc->toArray());
}
/**
* @test delete
*/
public function testDeleteNpc()
{
$npc = $this->makeNpc();
$resp = $this->npcRepo->delete($npc->id);
$this->assertTrue($resp);
$this->assertNull(Npc::find($npc->id), 'Npc should not exist in DB');
}
}
| mit |
sserrot/champion_relationships | venv/Lib/site-packages/jupyter_client/jsonutil.py | 2920 | # coding: utf-8
"""Utilities to manipulate JSON objects."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from datetime import datetime
import re
import warnings
from dateutil.parser import parse as _dateutil_parse
from dateutil.tz import tzlocal
from ipython_genutils import py3compat
next_attr_name = '__next__' # Not sure what downstream library uses this, but left it to be safe
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
# timestamp formats
ISO8601 = "%Y-%m-%dT%H:%M:%S.%f"
ISO8601_PAT = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d{1,6})?(Z|([\+\-]\d{2}:?\d{2}))?$")
# holy crap, strptime is not threadsafe.
# Calling it once at import seems to help.
datetime.strptime("1", "%d")
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def _ensure_tzinfo(dt):
"""Ensure a datetime object has tzinfo
If no tzinfo is present, add tzlocal
"""
if not dt.tzinfo:
# No more naïve datetime objects!
warnings.warn(u"Interpreting naive datetime as local %s. Please add timezone info to timestamps." % dt,
DeprecationWarning,
stacklevel=4)
dt = dt.replace(tzinfo=tzlocal())
return dt
def parse_date(s):
"""parse an ISO8601 date string
If it is None or not a valid ISO8601 timestamp,
it will be returned unmodified.
Otherwise, it will return a datetime object.
"""
if s is None:
return s
m = ISO8601_PAT.match(s)
if m:
dt = _dateutil_parse(s)
return _ensure_tzinfo(dt)
return s
def extract_dates(obj):
"""extract ISO8601 dates from unpacked JSON"""
if isinstance(obj, dict):
new_obj = {} # don't clobber
for k,v in obj.items():
new_obj[k] = extract_dates(v)
obj = new_obj
elif isinstance(obj, (list, tuple)):
obj = [ extract_dates(o) for o in obj ]
elif isinstance(obj, str):
obj = parse_date(obj)
return obj
def squash_dates(obj):
"""squash datetime objects into ISO8601 strings"""
if isinstance(obj, dict):
obj = dict(obj) # don't clobber
for k,v in obj.items():
obj[k] = squash_dates(v)
elif isinstance(obj, (list, tuple)):
obj = [ squash_dates(o) for o in obj ]
elif isinstance(obj, datetime):
obj = obj.isoformat()
return obj
def date_default(obj):
"""default function for packing datetime objects in JSON."""
if isinstance(obj, datetime):
obj = _ensure_tzinfo(obj)
return obj.isoformat().replace('+00:00', 'Z')
else:
raise TypeError("%r is not JSON serializable" % obj)
| mit |
MrMilan/HL7Message | HL7Message/Properties/AssemblyInfo.cs | 1396 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HL7Message")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HL7Message")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b97569ac-963d-4fb4-b078-f5942161ca16")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
gnk-sato-hotto/nkdash | source/_isWindows.js | 117 | export default function _isWindows() {
const plt = navigator.platform.toLowerCase();
return /^win/.test(plt);
}
| mit |
FAForever/downlords-faf-client | src/test/java/com/faforever/client/coop/CoopControllerTest.java | 3745 | package com.faforever.client.coop;
import com.faforever.client.builders.FeaturedModBeanBuilder;
import com.faforever.client.domain.CoopMissionBean;
import com.faforever.client.fx.JavaFxUtil;
import com.faforever.client.fx.WebViewConfigurer;
import com.faforever.client.game.GameService;
import com.faforever.client.game.GamesTableController;
import com.faforever.client.game.NewGameInfo;
import com.faforever.client.i18n.I18n;
import com.faforever.client.mod.ModService;
import com.faforever.client.notification.NotificationService;
import com.faforever.client.replay.ReplayService;
import com.faforever.client.test.UITest;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.TimeService;
import javafx.collections.FXCollections;
import javafx.scene.layout.Pane;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.testfx.util.WaitForAsyncUtils;
import java.util.concurrent.CompletableFuture;
import static com.faforever.client.game.KnownFeaturedMod.COOP;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CoopControllerTest extends UITest {
@Mock
private CoopService coopService;
@Mock
private GameService gameService;
@Mock
private UiService uiService;
@Mock
private GamesTableController gamesTableController;
@Mock
private I18n i18n;
@Mock
private WebViewConfigurer webViewConfigurer;
@Mock
private ModService modService;
@Mock
private ReplayService replayService;
@Mock
private NotificationService notificationService;
@Mock
private TimeService timeService;
@InjectMocks
private CoopController instance;
@BeforeEach
public void setUp() throws Exception {
when(coopService.getLeaderboard(any(), anyInt())).thenReturn(CompletableFuture.completedFuture(emptyList()));
when(coopService.getMissions()).thenReturn(CompletableFuture.completedFuture(emptyList()));
when(modService.getFeaturedMod(COOP.getTechnicalName())).thenReturn(CompletableFuture.completedFuture(FeaturedModBeanBuilder.create().defaultValues().technicalName("coop").get()));
when(gameService.getGames()).thenReturn(FXCollections.emptyObservableList());
when(uiService.loadFxml("theme/play/games_table.fxml")).thenReturn(gamesTableController);
when(gamesTableController.getRoot()).thenReturn(new Pane());
loadFxml("theme/play/coop/coop.fxml", clazz -> instance);
verify(webViewConfigurer).configureWebView(instance.descriptionWebView);
}
@Test
public void onPlayButtonClicked() {
when(coopService.getMissions()).thenReturn(completedFuture(singletonList(new CoopMissionBean())));
JavaFxUtil.runLater(() -> instance.initialize());
WaitForAsyncUtils.waitForFxEvents();
instance.onPlayButtonClicked();
ArgumentCaptor<NewGameInfo> captor = ArgumentCaptor.forClass(NewGameInfo.class);
verify(gameService).hostGame(captor.capture());
NewGameInfo newGameInfo = captor.getValue();
assertThat(newGameInfo.getFeaturedMod().getTechnicalName(), is("coop"));
}
@Test
public void testGetRoot() throws Exception {
assertThat(instance.getRoot(), is(instance.coopRoot));
assertThat(instance.getRoot().getParent(), is(nullValue()));
}
}
| mit |
RideSurf/website | server/public/javascripts/init.js | 617 | (function ($) {
$(function () {
$('.button-collapse').sideNav();
$('.datepicker').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year
selectTime: true
});
$('.timepicker').pickatime({
interval: 30
});
$('.button-submit').submit(function(event){
event.preventDefault();
console.log("prevented default");
return false;
})
}); // end of document ready
})(jQuery); // end of jQuery name space
| mit |
eclipxe13/CfdiUtils | src/CfdiUtils/Validate/Cfdi33/RecepcionPagos/Pagos/BancoBeneficiarioRfcCorrecto.php | 957 | <?php
namespace CfdiUtils\Validate\Cfdi33\RecepcionPagos\Pagos;
use CfdiUtils\Nodes\NodeInterface;
use CfdiUtils\Utils\Rfc;
/**
* PAGO15: En un pago, cuando el RFC del banco emisor de la cuenta beneficiaria existe
* debe ser válido y diferente de "XAXX010101000"
*/
class BancoBeneficiarioRfcCorrecto extends AbstractPagoValidator
{
protected $code = 'PAGO15';
protected $title = 'En un pago, cuando el RFC del banco emisor de la cuenta beneficiaria existe'
. ' debe ser válido y diferente de "XAXX010101000"';
public function validatePago(NodeInterface $pago): bool
{
if ($pago->offsetExists('RfcEmisorCtaBen')) {
try {
Rfc::checkIsValid($pago['RfcEmisorCtaBen'], Rfc::DISALLOW_GENERIC);
} catch (\UnexpectedValueException $exception) {
throw new ValidatePagoException($exception->getMessage());
}
}
return true;
}
}
| mit |
Massnory/Mass | app/src/main/java/xyz/geminiwen/mass/model/ArticleModel.java | 2629 | package xyz.geminiwen.mass.model;
import android.os.Parcel;
import com.google.gson.annotations.SerializedName;
/**
* Created by geminiwen on 16/8/25.
*/
public class ArticleModel extends BaseModel {
private long id;
private String url;
private String title;
private String createdDate;
private String excerpt;
private String originalText;
private String parsedText;
private String currentStatus;
private int votes;
private int bookmarks;
private int comments;
@SerializedName("isLiked")
private boolean liked;
@SerializedName("isHated")
private boolean hated;
@SerializedName("isBookmarked")
private boolean bookmarked;
@SerializedName("isOffline")
private boolean offline;
public ArticleModel() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.url);
dest.writeString(this.title);
dest.writeString(this.createdDate);
dest.writeString(this.excerpt);
dest.writeString(this.originalText);
dest.writeString(this.parsedText);
dest.writeString(this.currentStatus);
dest.writeInt(this.votes);
dest.writeInt(this.bookmarks);
dest.writeInt(this.comments);
dest.writeByte(this.liked ? (byte) 1 : (byte) 0);
dest.writeByte(this.hated ? (byte) 1 : (byte) 0);
dest.writeByte(this.bookmarked ? (byte) 1 : (byte) 0);
dest.writeByte(this.offline ? (byte) 1 : (byte) 0);
}
protected ArticleModel(Parcel in) {
this.id = in.readLong();
this.url = in.readString();
this.title = in.readString();
this.createdDate = in.readString();
this.excerpt = in.readString();
this.originalText = in.readString();
this.parsedText = in.readString();
this.currentStatus = in.readString();
this.votes = in.readInt();
this.bookmarks = in.readInt();
this.comments = in.readInt();
this.liked = in.readByte() != 0;
this.hated = in.readByte() != 0;
this.bookmarked = in.readByte() != 0;
this.offline = in.readByte() != 0;
}
public static final Creator<ArticleModel> CREATOR = new Creator<ArticleModel>() {
@Override
public ArticleModel createFromParcel(Parcel source) {
return new ArticleModel(source);
}
@Override
public ArticleModel[] newArray(int size) {
return new ArticleModel[size];
}
};
}
| mit |
flopp/go-findfont | fontdirs_windows.go | 410 | // Copyright 2016 Florian Pigorsch. All rights reserved.
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package findfont
import (
"os"
"path/filepath"
)
func getFontDirectories() (paths []string) {
return []string{
filepath.Join(os.Getenv("windir"), "Fonts"),
filepath.Join(os.Getenv("localappdata"), "Microsoft", "Windows", "Fonts"),
}
}
| mit |
xuetu0606/lgzx | application/views/home/user/center.php | 4375 | <link rel="stylesheet" href="/static/css/tpls/lgb.css"/>
<link rel="stylesheet" href="/static/css/tpls/table.css"/>
<section>
<p class="title">
<span><?php echo $title; ?></span>
</p>
<div class="infor">
<div class="portrait">
<a href="/user/personalInfor">
<img src="<?php echo $user['img']; ?>" alt=""/>
</a>
</div>
<div class="logo">
<a href="#"><?php echo $user['username']; ?></a>
</div>
<div class="message">
<div class="detail">
<div>
<span><?php echo $user['is_co']==1?$user['coname']:$user['realname']; ?></span>
<?php if($user['vip_endtime']){?>
<span style="color:#FADA5E;">VIP</span>
<span class="hui"><?php echo date('Y-m-d',$user['vip_endtime'])."前有效"?></span>
<?php }else{?>
<span class="hui">VIP</span>
<a href="buyvip" class="right">购买会员></a>
<?php } ?>
</div>
</div>
<div class="detail">
<div>
<span>工号:</span>
<span><?php echo $user['no']; ?></span>
</div>
</div>
<div class="detail">
<div>
<span>零工币余额:</span>
<span><span class="stress"><?php echo $user['credit1']?$user['credit1']:'0'; ?></span>个</span>
<a href="recharge" class="right">充值></a>
</div>
</div>
<div class="detail">
<div>
<span>工分余额:</span>
<span class="stress"><?php echo $user['credit2']?$user['credit2']:'0'; ?></span>
<?php if($user['credit2']){?><a href="/pay/cash" class="right">提现></a><?php }?>
</div>
</div>
<div class="detail">
<div>
<span>实名认证:</span>
<?php echo $user['is_real']?'<span>已认证</span>':'<span class="hui">未认证</span><a href="identify" class="stress right">去认证></a>'?>
</div>
</div>
<div class="detail">
<div>
<span>信用等级:</span>
<span><img src="<?php echo $user['medal']; ?>" alt=""/></span>
</div>
</div>
</div>
</div>
<div class="mine">
<div class="list">
<p class="left">
<a href="<?php echo site_url('user/myinfo'); ?>">
<img src="/static/images/tpls/lgb/wdzl.png" alt="我的资料"/>
<span>我的资料</span>
</a>
</p>
<p class="right">
<a href="<?php echo site_url('pay/myaccount'); ?>">
<img src="/static/images/tpls/lgb/wdzh.png" alt="我的账户"/>
<span>我的账户</span>
</a>
</p>
</div>
<div class="list">
<p class="left">
<a href="mypublish">
<img src="/static/images/tpls/lgb/wdfb.png" alt="我的发布"/>
<span>我的发布</span>
</a>
</p>
<p class="right">
<a href="<?php echo site_url('home/contractads'); ?>">
<img src="/static/images/tpls/lgb/qytg.png" alt="签约推广"/>
<span>签约推广</span>
</a>
</p>
</div>
<div class="list">
<a href="<?php echo site_url('Lista/message'); ?>">
<p class="left">
<img src="/static/images/tpls/lgb/xxwj.png" alt="消息文件"/>
<span>消息文件</span>
</p>
</a>
<a href="<?php echo site_url('Lista/evaluate'); ?>">
<p class="right">
<img src="/static/images/tpls/lgb/wdpj.png" alt="我的评价"/>
<span>评价</span>
</p>
</a>
</div>
<div class="list">
<a href="logout"> <input type="button" value="退出"/></a>
</div>
</div>
</div>
</section> | mit |
butterbrother/alpha-versions | learn/java/Collections/HashSetDemo.java | 298 | package Collections;
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet<Character> hs = new HashSet<Character>();
hs.add('B');
hs.add('A');
hs.add('D');
hs.add('E');
hs.add('C');
hs.add('F');
System.out.println(hs);
}
}
| mit |
raskolnikova/infomaps | node_modules/devextreme/events/gesture/swipeable.js | 3028 | /**
* DevExtreme (events/gesture/swipeable.js)
* Version: 16.2.6
* Build date: Tue Mar 28 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
swipeEvents = require("../swipe"),
DOMComponent = require("../../core/dom_component"),
eventUtils = require("../utils"),
publicComponentUtils = require("../../core/utils/public_component");
var DX_SWIPEABLE = "dxSwipeable",
SWIPEABLE_CLASS = "dx-swipeable",
ACTION_TO_EVENT_MAP = {
onStart: swipeEvents.start,
onUpdated: swipeEvents.swipe,
onEnd: swipeEvents.end,
onCancel: "dxswipecancel"
};
var Swipeable = DOMComponent.inherit({
_getDefaultOptions: function() {
return $.extend(this.callBase(), {
elastic: true,
immediate: false,
direction: "horizontal",
itemSizeFunc: null,
onStart: null,
onUpdated: null,
onEnd: null,
onCancel: null
})
},
_render: function() {
this.callBase();
this.element().addClass(SWIPEABLE_CLASS);
this._attachEventHandlers()
},
_attachEventHandlers: function() {
this._detachEventHandlers();
if (this.option("disabled")) {
return
}
var NAME = this.NAME;
this._createEventData();
$.each(ACTION_TO_EVENT_MAP, $.proxy(function(actionName, eventName) {
var action = this._createActionByOption(actionName, {
context: this
});
eventName = eventUtils.addNamespace(eventName, NAME);
this.element().on(eventName, this._eventData, function(e) {
return action({
jQueryEvent: e
})
})
}, this))
},
_createEventData: function() {
this._eventData = {
elastic: this.option("elastic"),
itemSizeFunc: this.option("itemSizeFunc"),
direction: this.option("direction"),
immediate: this.option("immediate")
}
},
_detachEventHandlers: function() {
this.element().off("." + DX_SWIPEABLE)
},
_optionChanged: function(args) {
switch (args.name) {
case "disabled":
case "onStart":
case "onUpdated":
case "onEnd":
case "onCancel":
case "elastic":
case "immediate":
case "itemSizeFunc":
case "direction":
this._detachEventHandlers();
this._attachEventHandlers();
break;
case "rtlEnabled":
break;
default:
this.callBase(args)
}
}
});
publicComponentUtils.name(Swipeable, DX_SWIPEABLE);
module.exports = Swipeable;
| mit |
Sheco/cdda-itembrowser | src/app/views/world/constructionCategories.blade.php | 495 | @section('title')
Construction categories - Cataclysm: Dark Days Ahead
@endsection
<h1>Construction categories</h1>
<div class="row">
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked">
@foreach($categories as $category)
<li class="@if($category==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $category) }}">{{{$category}}}</a></li>
@endforeach
</ul>
</div>
<div class="col-md-9">
@include("world._constructionList", array("data"=>$data))
</div>
</div>
| mit |
shiro16/activerecord-jwt | spec/activerecord-jwt/decoder_spec.rb | 2332 | require 'spec_helper'
class User < ActiveRecord::Base
include ActiveRecord::Jwt::Decoder
end
describe ActiveRecord::Jwt::Decoder do
let(:secret_key) { 'secret_key' }
let(:algorithm) { 'HS256' }
let(:user) { User.create(nickname: "test") }
let(:payload) {
{
'sub' => user.nickname,
'iss' => 'issuer',
'aud' => 'audience',
'class' => User.name
}
}
let(:authenticate_jwt) { JWT.encode(payload, secret_key, algorithm) }
before do
ActiveRecord::Jwt::Decoder.configure do |config|
config.sub = :nickname
config.key = secret_key
config.algorithm = algorithm
config.class = true
end
end
after { User.destroy_all }
describe '.find_authenticated_jwt' do
context 'when authenticate jwt' do
subject { User.find_authenticated_jwt(authenticate_jwt) }
it { expect(subject.id).to eq user.id }
end
context 'when unauthenticate jwt' do
subject { User.find_authenticated_jwt("test") }
it { expect{ subject }.to raise_error(ActiveRecord::Jwt::InvalidError) }
end
context 'when find_by record not found' do
subject { User.find_authenticated_jwt(authenticate_jwt) }
before do
user.destroy
end
it { expect(subject).to be_nil }
end
end
describe '.decode_jwt' do
context 'when authenticate jwt' do
subject { User.decode_jwt(authenticate_jwt) }
it { expect(subject[:payload]).to eq payload }
it { expect(subject[:header]).to eq({'alg' => 'HS256', 'typ' => 'JWT'}) }
end
context 'when unauthenticate jwt' do
subject { User.decode_jwt('test') }
it { expect{ subject }.to raise_error(ActiveRecord::Jwt::InvalidError) }
end
end
describe '.payload_valid?' do
subject { User.send(:payload_valid?, payload) }
context 'when same class' do
it { expect(subject).to be_nil }
end
context 'when configuration class is false' do
before do
ActiveRecord::Jwt::Decoder.configuration.class = false
payload['class'] = 'test'
end
it { expect(subject).to be_nil }
end
context 'when not the some class' do
before do
payload['class'] = 'test'
end
it { expect{ subject }.to raise_error(ActiveRecord::Jwt::InvalidError) }
end
end
end
| mit |
kongkongmao/MCMagicEra-Reloaded | src/main/java/club/kongkongmao/magicera/Crafting/UpgradeFrameBrewingRecipe.java | 2064 | package club.kongkongmao.magicera.Crafting;
import club.kongkongmao.magicera.Blocks.MBlocks;
import club.kongkongmao.magicera.Items.MItems;
import club.kongkongmao.magicera.Utils.NBTBuilder;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.brewing.IBrewingRecipe;
public class UpgradeFrameBrewingRecipe implements IBrewingRecipe {
private final ItemStack emptyFrame;
private final ItemStack muffleFrame;
private final ItemStack concentrationFrame;
public UpgradeFrameBrewingRecipe() {
emptyFrame = new ItemStack(MItems.upgradeFrame);
emptyFrame.setTagCompound(new NBTBuilder().setString("Upgrade", "none").build());
muffleFrame = new ItemStack(MItems.upgradeFrame);
muffleFrame.setTagCompound(new NBTBuilder().setString("Upgrade", "muffle").build());
concentrationFrame = new ItemStack(MItems.upgradeFrame);
concentrationFrame.setTagCompound(new NBTBuilder().setString("Upgrade", "concentration").build());
}
@Override
public boolean isInput(ItemStack input) {
return ItemStack.areItemStacksEqual(input, emptyFrame) || (input.getItem() == Item.getItemFromBlock(MBlocks.upgradeFrame) && !input.hasTagCompound());
}
@Override
public boolean isIngredient(ItemStack ingredient) {
return ingredient.getItem() == Item.getItemFromBlock(Blocks.GLASS)
|| ingredient.getItem() == Item.getItemFromBlock(Blocks.WOOL);
}
private ItemStack cloneWithAmount(final ItemStack in, int count) {
ItemStack stack = in.copy();
stack.setCount(count);
return stack;
}
@Override
public ItemStack getOutput(ItemStack input, ItemStack ingredient) {
if (isInput(input) && isIngredient(ingredient)) {
if (ingredient.getItem() == Item.getItemFromBlock(Blocks.WOOL)) {
return cloneWithAmount(muffleFrame, input.getCount());
} else if (ingredient.getItem() == Item.getItemFromBlock(Blocks.GLASS)) {
return cloneWithAmount(concentrationFrame, input.getCount());
}
}
return ItemStack.EMPTY;
}
}
| mit |
FEUP-MIEIC/PROG | a01_Ficha1/p02_ExpressoesAritmeticas/2.02b.cpp | 650 | #include <iostream>
using namespace std;
int main() {
int n1, n2, n3;
// Leitura de n1
cout << "N1 ? ";
cin >> n1;
// Leitura de n2
cout << "N2 ? ";
cin >> n2;
// Leitura de n3
cout << "N3 ? ";
cin >> n3;
int nmax=n1, nmin=n1;
int nmed=n1;
if (n2 > nmax)
nmax = n2;
if (n3 > nmax)
nmax = n3;
if (n2 < nmin)
nmin = n2;
if (n3 < nmin)
nmin = n3;
if (n1 != nmax && n1 != nmin)
nmed = n1;
if (n2 != nmax && n2 != nmin)
nmed = n2;
if (n3 != nmax && n3 != nmin)
nmed = n3;
cout << nmax << " " << nmed << " " << nmin << "\n";
// Há uma maneira mais simples da fazer isto, mas já estou cansado. Dannyps
}
| mit |
dickeyxian/JavaLeetCode | src/leetcode/TrappingRainWater.java | 688 | package leetcode;
public class TrappingRainWater {
public static int trap(int[] A) {
int result = 0;
int len = A.length;
if (len <= 2) {
return 0;
}
int maxleft[] = new int[len];
int maxright[] = new int[len];
for (int i = 1; i < len; i++) {
maxleft[i] = Math.max(maxleft[i - 1], A[i - 1]);
maxright[len - i - 1] = Math.max(maxright[len - i], A[len - i]);
}
for (int i = 1; i < len; i++) {
int height = Math.min(maxleft[i], maxright[i]);
if (height > A[i]) {
result += height - A[i];
}
}
return result;
}
public static void main(String[] args) {
int num[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
System.out.println(trap(num));
}
}
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/SeriesVbpMarkerStatesNormal.scala | 1159 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<vbp>-marker-states-normal</code>
*/
@js.annotation.ScalaJSDefined
class SeriesVbpMarkerStatesNormal extends com.highcharts.HighchartsGenericObject {
/**
* <p>Animation when returning to normal state after hovering.</p>
* @since 6.0.0
*/
val animation: js.UndefOr[Boolean | js.Object] = js.undefined
}
object SeriesVbpMarkerStatesNormal {
/**
* @param animation <p>Animation when returning to normal state after hovering.</p>
*/
def apply(animation: js.UndefOr[Boolean | js.Object] = js.undefined): SeriesVbpMarkerStatesNormal = {
val animationOuter: js.UndefOr[Boolean | js.Object] = animation
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesVbpMarkerStatesNormal {
override val animation: js.UndefOr[Boolean | js.Object] = animationOuter
})
}
}
| mit |
bitcoin-s/bitcoin-s | core-test/.jvm/src/test/scala/org/bitcoins/core/p2p/InetAddressJVMTest.scala | 912 | package org.bitcoins.core.p2p
import org.bitcoins.testkitcore.gen.p2p.P2PGenerator
import org.bitcoins.testkitcore.util.BitcoinSUnitTest
import java.net.{InetAddress => JvmAddress}
class InetAddressJVMTest extends BitcoinSUnitTest {
implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
generatorDrivenConfigNewCode
behavior of "InetAddress"
it must "have serialization symmetry with java's InetAddress" in {
forAll(P2PGenerator.inetAddress) { inet =>
assert(
NetworkIpAddress.writeAddress(
JvmAddress.getByAddress(inet.getAddress).getAddress) == inet.bytes)
}
}
it must "have serialization symmetry with java's InetAddress with IPv4" in {
forAll(P2PGenerator.inetAddress) { inet =>
assert(
JvmAddress
.getByAddress(inet.ipv4Bytes.toArray)
.getAddress sameElements inet.ipv4Bytes.toArray)
}
}
}
| mit |
b263/tchart | src/services/event-bus.js | 407 | import Vue from 'vue';
import log from './log';
const v = new Vue();
export default {
logEvent(data) {
log('event', `${data[0]}: ${JSON.stringify(data[1]).substring(0, 80)}`);
},
$on(...args) {
v.$on.apply(v, args);
},
$emit(...args) {
this.logEvent(args);
v.$emit.apply(v, args);
},
$off(...args) {
v.$off.apply(v, args);
}
};
| mit |
CSCfi/antero | db/python/load.py | 3776 | #!/usr/bin/python
# vim: set fileencoding=UTF-8 :
"""
load
todo doc
"""
import sys,os,getopt
import urllib2, base64, httplib
import ijson.backends.yajl2_cffi as ijson
import json
from time import localtime, strftime
import dboperator
def show(message):
print(strftime("%Y-%m-%d %H:%M:%S", localtime())+" "+message)
def load(secure,hostname,url,schema,table,postdata,condition,verbose):
show("begin "+hostname+" "+url+" "+schema+" "+table+" "+(postdata or "")+" "+(condition or ""))
if secure:
address = "https://"+hostname+url
else:
address = "http://"+hostname+url
show("load from "+address)
reqheaders = {'Content-Type': 'application/json'}
reqheaders['Caller-Id'] = '1.2.246.562.10.2013112012294919827487.vipunen'
# api credentials from env vars
if os.getenv("API_USERNAME"):
show("using authentication")
apiuser = os.getenv("API_USERNAME")
apipass = os.getenv("API_PASSWORD")
reqheaders['Authorization'] = 'Basic %s' % base64.b64encode(apiuser+":"+apipass)
# automatic POST with (post)data
request = urllib2.Request(address, data=postdata, headers=reqheaders)
try:
response = urllib2.urlopen(request)
except httplib.IncompleteRead as e:
show('IncompleteRead exception.')
show('Received: %d'%(e.partial))
sys.exit(2)
except urllib2.HTTPError as e:
show('The server couldn\'t fulfill the request.')
show('Error code: %d'%(e.code))
sys.exit(2)
except urllib2.URLError as e:
show('We failed to reach a server.')
show('Reason: %s'%(e.reason))
sys.exit(2)
else:
# everything is fine
show("api call OK")
# remove data conditionally, otherwise empty
# merge operation could be considered here...
if condition:
show("remove from %s.%s with condition '%s'"%(schema,table,condition))
dboperator.execute("DELETE FROM %s.%s WHERE %s"%(schema,table,condition))
else:
show("empty %s.%s"%(schema,table))
dboperator.empty(schema,table)
show("insert data")
cnt=0
for row in ijson.items(response,'item'):
cnt+=1
# show some sign of being alive
if cnt%100 == 0:
sys.stdout.write('.')
sys.stdout.flush()
if cnt%1000 == 0:
show("-- %d" % (cnt))
if verbose: show("%d -- %s"%(cnt,row))
# find out which columns to use on insert
dboperator.resetcolumns(row)
# flatten arrays/lists
for col in row:
if type(row[col]) is list:
row[col] = ''.join(map(str,json.dumps(row[col])))
dboperator.insert(address,schema,table,row)
show("wrote %d"%(cnt))
show("ready")
def usage():
print("""
usage: load.py [-s|--secure] -H|--hostname <hostname> -u|--url <url> -e|--schema <schema> -t|--table <table> [-p|--postdata] [-c|--condition <condition>] [-v|--verbose]
""")
def main(argv):
# muuttujat jotka kerrotaan argumentein
secure=False
hostname,url,schema,table="","","",""
postdata=None
condition=None
verbose=False
try:
opts,args=getopt.getopt(argv,"sH:u:e:t:p:c:v",["secure","hostname=","url=","schema=","table=","postdata=","condition=","verbose"])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
for opt,arg in opts:
if opt in ("-s", "--secure"): secure=True
elif opt in ("-H", "--hostname"): hostname=arg
elif opt in ("-u", "--url"): url=arg
elif opt in ("-e", "--schema"): schema=arg
elif opt in ("-t", "--table"): table=arg
elif opt in ("-p", "--postdata"): postdata=arg
elif opt in ("-c", "--condition"): condition=arg
elif opt in ("-v", "--verbose"): verbose=True
if not hostname or not url or not schema or not table:
usage()
sys.exit(2)
load(secure,hostname,url,schema,table,postdata,condition,verbose)
dboperator.close()
if __name__ == "__main__":
main(sys.argv[1:])
| mit |
dries007/HoloInventory | src/main/java/net/dries007/holoInventory/network/request/RequestMessage.java | 1664 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 - 2017 Dries K. Aka Dries007
*
* 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 net.dries007.holoInventory.network.request;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
abstract class RequestMessage implements IMessage
{
int dim;
RequestMessage()
{
}
RequestMessage(int dim)
{
this.dim = dim;
}
@Override
public void fromBytes(ByteBuf buf)
{
dim = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf)
{
buf.writeInt(dim);
}
}
| mit |
ontohub/gitlab_git | lib/bringit/diff_collection.rb | 3048 | module Bringit
class DiffCollection
include Enumerable
DEFAULT_LIMITS = { max_files: 100, max_lines: 5000 }.freeze
def initialize(iterator, options = {})
@iterator = iterator
@max_files = options.fetch(:max_files, DEFAULT_LIMITS[:max_files])
@max_lines = options.fetch(:max_lines, DEFAULT_LIMITS[:max_lines])
@max_bytes = @max_files * 5120 # Average 5 KB per file
@safe_max_files = [@max_files, DEFAULT_LIMITS[:max_files]].min
@safe_max_lines = [@max_lines, DEFAULT_LIMITS[:max_lines]].min
@safe_max_bytes = @safe_max_files * 5120 # Average 5 KB per file
@all_diffs = !!options.fetch(:all_diffs, false)
@no_collapse = !!options.fetch(:no_collapse, true)
@deltas_only = !!options.fetch(:deltas_only, false)
@line_count = 0
@byte_count = 0
@overflow = false
@array = Array.new
end
def each(&block)
if @populated
# @iterator.each is slower than just iterating the array in place
@array.each(&block)
elsif @deltas_only
each_delta(&block)
else
each_patch(&block)
end
end
def empty?
[email protected]?
end
def overflow?
populate!
!!@overflow
end
def size
@size ||= count # forces a loop using each method
end
def real_size
populate!
if @overflow
"#{size}+"
else
size.to_s
end
end
def decorate!
collection = each_with_index do |element, i|
@array[i] = yield(element)
end
@populated = true
collection
end
private
def populate!
return if @populated
each { nil } # force a loop through all diffs
@populated = true
nil
end
def over_safe_limits?(files)
files >= @safe_max_files || @line_count > @safe_max_lines || @byte_count >= @safe_max_bytes
end
def each_delta
@iterator.each_delta.with_index do |delta, i|
diff = Bringit::Diff.new(delta)
yield @array[i] = diff
end
end
def each_patch
@iterator.each_with_index do |raw, i|
# First yield cached Diff instances from @array
if @array[i]
yield @array[i]
next
end
# We have exhausted @array, time to create new Diff instances or stop.
break if @overflow
if !@all_diffs && i >= @max_files
@overflow = true
break
end
collapse = !@all_diffs && !@no_collapse
diff = Bringit::Diff.new(raw, collapse: collapse)
if collapse && over_safe_limits?(i)
diff.prune_collapsed_diff!
end
@line_count += diff.line_count
@byte_count += diff.diff.bytesize
if !@all_diffs && (@line_count >= @max_lines || @byte_count >= @max_bytes)
# This last Diff instance pushes us over the lines limit. We stop and
# discard it.
@overflow = true
break
end
yield @array[i] = diff
end
end
end
end
| mit |
Mnemosyne-20/Mnemosyne-2.1 | Mnemosyne2Reborn/Commenting/UserLinks.cs | 5979 | using ArchiveApi.Interfaces;
using Mnemosyne2Reborn.UserData;
using RedditSharp;
using RedditSharp.Things;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Mnemosyne2Reborn.Commenting
{
/// <summary>
/// This class is used for archiving links in comments, not used for posts
/// </summary>
public class UserLinks
{
/// <summary>
/// Used for determining what the formatted links look like
/// </summary>
public enum UserLinkType
{
/// <summary>
/// Denotes that the passed through value is a "post"
/// </summary>
Post,
/// <summary>
/// Denotes that the passed through value is a "comment"
/// </summary>
Comment
}
private Thing Thing;
public UserLinkType UserLinksType { get; private set; }
/// <summary>
/// Username of the reddit user, used to build the archive listing comments later
/// </summary>
public string Name { get; private set; }
/// <summary>
/// This contains a list of original links, archived links, and their positions in the system
/// </summary>
public List<ArchiveLink> ArchiveLinks { get; private set; }
public static IArchiveService Service { get; private set; }
/// <summary>
/// Makes a Userlinks class from a comment, a list of regexes, and a Reddit
/// </summary>
/// <param name="comment">A <see cref="Comment"/> used to get the links and several other things</param>
/// <param name="regexes">A list of <see cref="Regex"/> used for excluding links</param>
/// <param name="reddit">A <see cref="Reddit"/> literally only used for getting a RedditUser</param>
public UserLinks(Comment comment, Regex[] regexes, Reddit reddit)
{
this.Thing = comment;
Name = comment.AuthorName;
UserLinksType = UserLinkType.Comment;
ArchiveLinks = Mnemosyne2Reborn.ArchiveLinks.ArchivePostLinks(RegularExpressions.FindLinks(comment.BodyHtml), regexes, reddit.GetUser(comment.AuthorName));
}
/// <summary>
/// Initializes the UserLinks class with Post items determining nessecary things
/// </summary>
/// <param name="post">A <see cref="Post"/> of which you give in</param>
/// <param name="regexes">A list of <see cref="Regex"/>es that you use for excluding links</param>
/// <param name="reddit">A <see cref="Reddit"/> used for parameter parity with <see cref="UserLinks(Comment, Regex[], Reddit)"/></param>
public UserLinks(Post post, Regex[] regexes, Reddit reddit)
{
this.Thing = post;
this.UserLinksType = UserLinkType.Post;
Name = post.AuthorName;
ArchiveLinks = Mnemosyne2Reborn.ArchiveLinks.ArchivePostLinks(RegularExpressions.FindLinks(post.SelfTextHtml), regexes, post.Author);
}
/// <summary>
/// Sets the internal <see cref="IArchiveService"/>
/// </summary>
/// <param name="service">An <see cref="IArchiveService"/> to use</param>
public static void SetArchiveService(IArchiveService service) => Service = service;
/// <summary>
/// Removes all links that match the given <seealso cref="Regex"/>
/// </summary>
/// <param name="r">A <seealso cref="Regex"/> to filter by</param>
public void RemoveOnRegex(Regex r) => RemoveOnRegex(new[] { r });
/// <summary>
/// A list of <see cref="Regex"/> to filter with
/// </summary>
/// <param name="r">A list of <see cref="Regex"/> that you use to filter with</param>
public void RemoveOnRegex(Regex[] r)
{
var stuff = from a in r.AsParallel() from b in ArchiveLinks where !a.IsMatch(b.OriginalLink) select b;
ArchiveLinks = stuff.ToList();
ArchiveLinks.Sort();
}
/// <summary>
/// Adds all original links to a <see cref="RedditUserProfileSqlite"/>
/// </summary>
/// <param name="r">A <see cref="Reddit"/> used for getting user information, cheifly the name of a user</param>
public void AddToProfile(Reddit r)
{
var profile = new RedditUserProfileSqlite(r.GetUser(Name));
foreach (var a in ArchiveLinks)
{
profile.AddUrlUsed(a.OriginalLink);
}
}
public string[] GetFormatedLinks(Configuration.ArchiveSubreddit sub)
{
throw new NotImplementedException();
#pragma warning disable
string[] temp = new string[ArchiveLinks.Count + (sub.ArchivePost ? 1 : 0)];
if (UserLinksType == UserLinkType.Post)
{
if (sub.ArchivePost)
{
temp[0] = $"* **Post:** {sub.SubredditArchiveService.Save(((Post)Thing).Url)}\n";
}
for (int i = (sub.ArchivePost ? 1 : 0); i < temp.Length; i++)
{
ArchiveLink link = ArchiveLinks[i];
if (ArchiveLinks.Count != 0)
{
if (link.IsExcluded)
continue;
temp[i] = $"* **Link: {link.Position}** ([{link.Hostname}]({link.OriginalLink})): {link.ArchivedLink}\n";
}
}
}
else
{
for (int i = 0; i < temp.Length; i++)
{
ArchiveLink link = ArchiveLinks[i];
if (ArchiveLinks.Count != 0)
{
if (link.IsExcluded)
continue;
}
}
}
return temp;
#pragma warning restore
}
}
} | mit |
zzareva/TelerikAcademy-2012-2013 | CSharpPartII/CS2Homework9Exams/SampleExamP05Liquid/Properties/AssemblyInfo.cs | 1414 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SampleExamP05Liquid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SampleExamP05Liquid")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bfacab3c-4351-402a-a89c-a712a6a68a41")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
JuanMantilla/saircoApp | src/main/java/co/utb/softeng/moviesapp/entities/Equipo.java | 2216 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.utb.softeng.moviesapp.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import co.utb.softeng.moviesapp.services.impl.EquipoServiceImpl;
import java.text.SimpleDateFormat;
/**
*
* @author Juan Mantilla
*/
@Entity
@Table(name = "EQUIPOS")
public class Equipo implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
private String ubicacion;
private String horario;
private String salon;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUbicacion() {
return ubicacion;
}
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
public String getSalon() {
return salon;
}
public void setSalon(String salon) {
this.salon = salon;
}
public String getHorario() {
return horario;
}
public void setHorario(String horario) {
this.horario = horario;
}
}
//String horario;
//
// EquipoServiceImpl equipos = new EquipoServiceImpl();
// SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
// for (Equipo equipo: equipos.getAllEquipos()) {
//
// String input = "2015-01-01";
// int hora = Integer.parseInt(input.substring(-5, 2));
// Date t;
// try {
// t = ft.parse(input);
// horario=t.toString();
// } catch (ParseException e) {
// System.out.println("Unparseable using " + ft);
// }
// } | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.