text:
use std::error::Error;
use std::fmt;

use async_trait::async_trait;
use rusoto_core::credential::ProvideAwsCredentials;
use rusoto_core::region;
use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
use rusoto_core::{Client, RusotoError};

use rusoto_core::proto;
use rusoto_core::signature::SignedRequest;
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct CreateSavingsPlanRequest {
    ///
Unique, case-sensitive identifier that you provide to ensure the idempotency of the request.

    #[serde(rename = "clientToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_token: Option<String>,
    ///
The hourly commitment, in USD. This is a value between 0.001 and 1 million. You cannot specify more than three digits after the decimal point.

    #[serde(rename = "commitment")]
    pub commitment: String,
    ///
The time at which to purchase the Savings Plan, in UTC format (YYYY-MM-DDTHH:MM:SSZ).

    #[serde(rename = "purchaseTime")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purchase_time: Option<f64>,
    ///
The ID of the offering.

    #[serde(rename = "savingsPlanOfferingId")]
    pub savings_plan_offering_id: String,
    ///
One or more tags.

    #[serde(rename = "tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
    ///
The up-front payment amount. This is a whole number between 50 and 99 percent of the total value of the Savings Plan. This parameter is supported only if the payment option is Partial Upfront.

    #[serde(rename = "upfrontPaymentAmount")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upfront_payment_amount: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct CreateSavingsPlanResponse {
    ///
The ID of the Savings Plan.

    #[serde(rename = "savingsPlanId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_id: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DeleteQueuedSavingsPlanRequest {
    ///
The ID of the Savings Plan.

    #[serde(rename = "savingsPlanId")]
    pub savings_plan_id: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DeleteQueuedSavingsPlanResponse {}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DescribeSavingsPlanRatesRequest {
    ///
The filters.

    #[serde(rename = "filters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Vec<SavingsPlanRateFilter>>,
    ///
The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.

    #[serde(rename = "maxResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_results: Option<i64>,
    ///
The token for the next page of results.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
The ID of the Savings Plan.

    #[serde(rename = "savingsPlanId")]
    pub savings_plan_id: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DescribeSavingsPlanRatesResponse {
    ///
The token to use to retrieve the next page of results. This value is null when there are no more results to return.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
The ID of the Savings Plan.

    #[serde(rename = "savingsPlanId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_id: Option<String>,
    ///
Information about the Savings Plans rates.

    #[serde(rename = "searchResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_results: Option<Vec<SavingsPlanRate>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DescribeSavingsPlansOfferingRatesRequest {
    ///
The filters.

    #[serde(rename = "filters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Vec<SavingsPlanOfferingRateFilterElement>>,
    ///
The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.

    #[serde(rename = "maxResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_results: Option<i64>,
    ///
The token for the next page of results.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
The specific AWS operation for the line item in the billing report.

    #[serde(rename = "operations")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations: Option<Vec<String>>,
    ///
The AWS products.

    #[serde(rename = "products")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub products: Option<Vec<String>>,
    ///
The IDs of the offerings.

    #[serde(rename = "savingsPlanOfferingIds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_offering_ids: Option<Vec<String>>,
    ///
The payment options.

    #[serde(rename = "savingsPlanPaymentOptions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_payment_options: Option<Vec<String>>,
    ///
The plan types.

    #[serde(rename = "savingsPlanTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_types: Option<Vec<String>>,
    ///
The services.

    #[serde(rename = "serviceCodes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_codes: Option<Vec<String>>,
    ///
The usage details of the line item in the billing report.

    #[serde(rename = "usageTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_types: Option<Vec<String>>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DescribeSavingsPlansOfferingRatesResponse {
    ///
The token to use to retrieve the next page of results. This value is null when there are no more results to return.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
Information about the Savings Plans offering rates.

    #[serde(rename = "searchResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_results: Option<Vec<SavingsPlanOfferingRate>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DescribeSavingsPlansOfferingsRequest {
    ///
The currencies.

    #[serde(rename = "currencies")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currencies: Option<Vec<String>>,
    ///
The descriptions.

    #[serde(rename = "descriptions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub descriptions: Option<Vec<String>>,
    ///
The durations, in seconds.

    #[serde(rename = "durations")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub durations: Option<Vec<i64>>,
    ///
The filters.

    #[serde(rename = "filters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Vec<SavingsPlanOfferingFilterElement>>,
    ///
The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.

    #[serde(rename = "maxResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_results: Option<i64>,
    ///
The token for the next page of results.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
The IDs of the offerings.

    #[serde(rename = "offeringIds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offering_ids: Option<Vec<String>>,
    ///
The specific AWS operation for the line item in the billing report.

    #[serde(rename = "operations")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations: Option<Vec<String>>,
    ///
The payment options.

    #[serde(rename = "paymentOptions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_options: Option<Vec<String>>,
    ///
The plan type.

    #[serde(rename = "planTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_types: Option<Vec<String>>,
    ///
The product type.

    #[serde(rename = "productType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_type: Option<String>,
    ///
The services.

    #[serde(rename = "serviceCodes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_codes: Option<Vec<String>>,
    ///
The usage details of the line item in the billing report.

    #[serde(rename = "usageTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_types: Option<Vec<String>>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DescribeSavingsPlansOfferingsResponse {
    ///
The token to use to retrieve the next page of results. This value is null when there are no more results to return.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
Information about the Savings Plans offerings.

    #[serde(rename = "searchResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_results: Option<Vec<SavingsPlanOffering>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DescribeSavingsPlansRequest {
    ///
The filters.

    #[serde(rename = "filters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<Vec<SavingsPlanFilter>>,
    ///
The maximum number of results to return with a single call. To retrieve additional results, make another call with the returned token value.

    #[serde(rename = "maxResults")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_results: Option<i64>,
    ///
The token for the next page of results.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
The Amazon Resource Names (ARN) of the Savings Plans.

    #[serde(rename = "savingsPlanArns")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_arns: Option<Vec<String>>,
    ///
The IDs of the Savings Plans.

    #[serde(rename = "savingsPlanIds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_ids: Option<Vec<String>>,
    ///
The states.

    #[serde(rename = "states")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub states: Option<Vec<String>>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DescribeSavingsPlansResponse {
    ///
The token to use to retrieve the next page of results. This value is null when there are no more results to return.

    #[serde(rename = "nextToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
    ///
Information about the Savings Plans.

    #[serde(rename = "savingsPlans")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plans: Option<Vec<SavingsPlan>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct ListTagsForResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "resourceArn")]
    pub resource_arn: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct ListTagsForResourceResponse {
    ///
Information about the tags.

    #[serde(rename = "tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
}

///
Information about a Savings Plan offering.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct ParentSavingsPlanOffering {
    ///
The currency.

    #[serde(rename = "currency")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    ///
The duration, in seconds.

    #[serde(rename = "durationSeconds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_seconds: Option<i64>,
    ///
The ID of the offering.

    #[serde(rename = "offeringId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offering_id: Option<String>,
    ///
The payment option.

    #[serde(rename = "paymentOption")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_option: Option<String>,
    ///
The description.

    #[serde(rename = "planDescription")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_description: Option<String>,
    ///
The plan type.

    #[serde(rename = "planType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_type: Option<String>,
}

///
Information about a Savings Plan.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlan {
    ///
The hourly commitment, in USD.

    #[serde(rename = "commitment")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commitment: Option<String>,
    ///
The currency.

    #[serde(rename = "currency")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    ///
The description.

    #[serde(rename = "description")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    ///
The EC2 instance family.

    #[serde(rename = "ec2InstanceFamily")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ec_2_instance_family: Option<String>,
    ///
The end time.

    #[serde(rename = "end")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,
    ///
The ID of the offering.

    #[serde(rename = "offeringId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offering_id: Option<String>,
    ///
The payment option.

    #[serde(rename = "paymentOption")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_option: Option<String>,
    ///
The product types.

    #[serde(rename = "productTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_types: Option<Vec<String>>,
    ///
The recurring payment amount.

    #[serde(rename = "recurringPaymentAmount")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recurring_payment_amount: Option<String>,
    ///
The AWS Region.

    #[serde(rename = "region")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
    ///
The Amazon Resource Name (ARN) of the Savings Plan.

    #[serde(rename = "savingsPlanArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_arn: Option<String>,
    ///
The ID of the Savings Plan.

    #[serde(rename = "savingsPlanId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_id: Option<String>,
    ///
The plan type.

    #[serde(rename = "savingsPlanType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_type: Option<String>,
    ///
The start time.

    #[serde(rename = "start")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,
    ///
The state.

    #[serde(rename = "state")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    ///
One or more tags.

    #[serde(rename = "tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
    ///
The duration of the term, in seconds.

    #[serde(rename = "termDurationInSeconds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub term_duration_in_seconds: Option<i64>,
    ///
The up-front payment amount.

    #[serde(rename = "upfrontPaymentAmount")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upfront_payment_amount: Option<String>,
}

///
Information about a filter.

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct SavingsPlanFilter {
    ///
The filter name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The filter value.

    #[serde(rename = "values")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
}

///
Information about a Savings Plan offering.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanOffering {
    ///
The currency.

    #[serde(rename = "currency")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    ///
The description.

    #[serde(rename = "description")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    ///
The duration, in seconds.

    #[serde(rename = "durationSeconds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_seconds: Option<i64>,
    ///
The ID of the offering.

    #[serde(rename = "offeringId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offering_id: Option<String>,
    ///
The specific AWS operation for the line item in the billing report.

    #[serde(rename = "operation")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,
    ///
The payment option.

    #[serde(rename = "paymentOption")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_option: Option<String>,
    ///
The plan type.

    #[serde(rename = "planType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_type: Option<String>,
    ///
The product type.

    #[serde(rename = "productTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_types: Option<Vec<String>>,
    ///
The properties.

    #[serde(rename = "properties")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<SavingsPlanOfferingProperty>>,
    ///
The service.

    #[serde(rename = "serviceCode")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_code: Option<String>,
    ///
The usage details of the line item in the billing report.

    #[serde(rename = "usageType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_type: Option<String>,
}

///
Information about a filter.

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct SavingsPlanOfferingFilterElement {
    ///
The filter name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The filter values.

    #[serde(rename = "values")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
}

///
Information about a property.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanOfferingProperty {
    ///
The property name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The property value.

    #[serde(rename = "value")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
}

///
Information about a Savings Plan offering rate.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanOfferingRate {
    ///
The specific AWS operation for the line item in the billing report.

    #[serde(rename = "operation")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,
    ///
The product type.

    #[serde(rename = "productType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_type: Option<String>,
    ///
The properties.

    #[serde(rename = "properties")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<SavingsPlanOfferingRateProperty>>,
    ///
The Savings Plan rate.

    #[serde(rename = "rate")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate: Option<String>,
    ///
The Savings Plan offering.

    #[serde(rename = "savingsPlanOffering")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub savings_plan_offering: Option<ParentSavingsPlanOffering>,
    ///
The service.

    #[serde(rename = "serviceCode")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_code: Option<String>,
    ///
The unit.

    #[serde(rename = "unit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    ///
The usage details of the line item in the billing report.

    #[serde(rename = "usageType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_type: Option<String>,
}

///
Information about a filter.

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct SavingsPlanOfferingRateFilterElement {
    ///
The filter name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The filter values.

    #[serde(rename = "values")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
}

///
Information about a property.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanOfferingRateProperty {
    ///
The property name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The property value.

    #[serde(rename = "value")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
}

///
Information about a Savings Plan rate.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanRate {
    ///
The currency.

    #[serde(rename = "currency")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    ///
The specific AWS operation for the line item in the billing report.

    #[serde(rename = "operation")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,
    ///
The product type.

    #[serde(rename = "productType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_type: Option<String>,
    ///
The properties.

    #[serde(rename = "properties")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<SavingsPlanRateProperty>>,
    ///
The rate.

    #[serde(rename = "rate")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate: Option<String>,
    ///
The service.

    #[serde(rename = "serviceCode")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_code: Option<String>,
    ///
The unit.

    #[serde(rename = "unit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    ///
The usage details of the line item in the billing report.

    #[serde(rename = "usageType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_type: Option<String>,
}

///
Information about a filter.

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct SavingsPlanRateFilter {
    ///
The filter name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The filter values.

    #[serde(rename = "values")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<String>>,
}

///
Information about a property.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct SavingsPlanRateProperty {
    ///
The property name.

    #[serde(rename = "name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The property value.

    #[serde(rename = "value")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct TagResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "resourceArn")]
    pub resource_arn: String,
    ///
One or more tags. For example, { "tags": {"key1":"value1", "key2":"value2"} }.

    #[serde(rename = "tags")]
    pub tags: ::std::collections::HashMap<String, String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct TagResourceResponse {}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct UntagResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "resourceArn")]
    pub resource_arn: String,
    ///
The tag keys.

    #[serde(rename = "tagKeys")]
    pub tag_keys: Vec<String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct UntagResourceResponse {}

/// Errors returned by CreateSavingsPlan
#[derive(Debug, PartialEq)]
pub enum CreateSavingsPlanError {
    ///
An unexpected error occurred.

    InternalServer(String),
    ///
The specified resource was not found.

    ResourceNotFound(String),
    ///
A service quota has been exceeded.

    ServiceQuotaExceeded(String),
}

impl CreateSavingsPlanError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateSavingsPlanError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(CreateSavingsPlanError::InternalServer(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(CreateSavingsPlanError::ResourceNotFound(err.msg))
                }
                "ServiceQuotaExceededException" => {
                    return RusotoError::Service(CreateSavingsPlanError::ServiceQuotaExceeded(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for CreateSavingsPlanError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CreateSavingsPlanError::InternalServer(ref cause) => write!(f, "{}", cause),
            CreateSavingsPlanError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
            CreateSavingsPlanError::ServiceQuotaExceeded(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for CreateSavingsPlanError {}
/// Errors returned by DeleteQueuedSavingsPlan
#[derive(Debug, PartialEq)]
pub enum DeleteQueuedSavingsPlanError {
    ///
An unexpected error occurred.

    InternalServer(String),
    ///
The specified resource was not found.

    ResourceNotFound(String),
    ///
A service quota has been exceeded.

    ServiceQuotaExceeded(String),
}

impl DeleteQueuedSavingsPlanError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteQueuedSavingsPlanError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(DeleteQueuedSavingsPlanError::InternalServer(
                        err.msg,
                    ))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(DeleteQueuedSavingsPlanError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ServiceQuotaExceededException" => {
                    return RusotoError::Service(
                        DeleteQueuedSavingsPlanError::ServiceQuotaExceeded(err.msg),
                    )
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DeleteQueuedSavingsPlanError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DeleteQueuedSavingsPlanError::InternalServer(ref cause) => write!(f, "{}", cause),
            DeleteQueuedSavingsPlanError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
            DeleteQueuedSavingsPlanError::ServiceQuotaExceeded(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for DeleteQueuedSavingsPlanError {}
/// Errors returned by DescribeSavingsPlanRates
#[derive(Debug, PartialEq)]
pub enum DescribeSavingsPlanRatesError {
    ///
The specified resource was not found.

    ResourceNotFound(String),
}

impl DescribeSavingsPlanRatesError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DescribeSavingsPlanRatesError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "ResourceNotFoundException" => {
                    return RusotoError::Service(DescribeSavingsPlanRatesError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DescribeSavingsPlanRatesError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DescribeSavingsPlanRatesError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for DescribeSavingsPlanRatesError {}
/// Errors returned by DescribeSavingsPlans
#[derive(Debug, PartialEq)]
pub enum DescribeSavingsPlansError {
    ///
An unexpected error occurred.

    InternalServer(String),
}

impl DescribeSavingsPlansError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DescribeSavingsPlansError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(DescribeSavingsPlansError::InternalServer(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DescribeSavingsPlansError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DescribeSavingsPlansError::InternalServer(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for DescribeSavingsPlansError {}
/// Errors returned by DescribeSavingsPlansOfferingRates
#[derive(Debug, PartialEq)]
pub enum DescribeSavingsPlansOfferingRatesError {
    ///
An unexpected error occurred.

    InternalServer(String),
}

impl DescribeSavingsPlansOfferingRatesError {
    pub fn from_response(
        res: BufferedHttpResponse,
    ) -> RusotoError<DescribeSavingsPlansOfferingRatesError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(
                        DescribeSavingsPlansOfferingRatesError::InternalServer(err.msg),
                    )
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DescribeSavingsPlansOfferingRatesError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DescribeSavingsPlansOfferingRatesError::InternalServer(ref cause) => {
                write!(f, "{}", cause)
            }
        }
    }
}
impl Error for DescribeSavingsPlansOfferingRatesError {}
/// Errors returned by DescribeSavingsPlansOfferings
#[derive(Debug, PartialEq)]
pub enum DescribeSavingsPlansOfferingsError {
    ///
An unexpected error occurred.

    InternalServer(String),
}

impl DescribeSavingsPlansOfferingsError {
    pub fn from_response(
        res: BufferedHttpResponse,
    ) -> RusotoError<DescribeSavingsPlansOfferingsError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(
                        DescribeSavingsPlansOfferingsError::InternalServer(err.msg),
                    )
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DescribeSavingsPlansOfferingsError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DescribeSavingsPlansOfferingsError::InternalServer(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for DescribeSavingsPlansOfferingsError {}
/// Errors returned by ListTagsForResource
#[derive(Debug, PartialEq)]
pub enum ListTagsForResourceError {
    ///
An unexpected error occurred.

    InternalServer(String),
    ///
The specified resource was not found.

    ResourceNotFound(String),
}

impl ListTagsForResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListTagsForResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(ListTagsForResourceError::InternalServer(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(ListTagsForResourceError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for ListTagsForResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ListTagsForResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            ListTagsForResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for ListTagsForResourceError {}
/// Errors returned by TagResource
#[derive(Debug, PartialEq)]
pub enum TagResourceError {
    ///
An unexpected error occurred.

    InternalServer(String),
    ///
The specified resource was not found.

    ResourceNotFound(String),
    ///
A service quota has been exceeded.

    ServiceQuotaExceeded(String),
}

impl TagResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<TagResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(TagResourceError::InternalServer(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(TagResourceError::ResourceNotFound(err.msg))
                }
                "ServiceQuotaExceededException" => {
                    return RusotoError::Service(TagResourceError::ServiceQuotaExceeded(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for TagResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TagResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            TagResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
            TagResourceError::ServiceQuotaExceeded(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for TagResourceError {}
/// Errors returned by UntagResource
#[derive(Debug, PartialEq)]
pub enum UntagResourceError {
    ///
An unexpected error occurred.

    InternalServer(String),
    ///
The specified resource was not found.

    ResourceNotFound(String),
}

impl UntagResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UntagResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(UntagResourceError::InternalServer(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(UntagResourceError::ResourceNotFound(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for UntagResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UntagResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            UntagResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for UntagResourceError {}
/// Trait representing the capabilities of the AWSSavingsPlans API. AWSSavingsPlans clients implement this trait.
#[async_trait]
pub trait SavingsPlans {
    ///
Creates a Savings Plan.

    async fn create_savings_plan(
        &self,
        input: CreateSavingsPlanRequest,
    ) -> Result<CreateSavingsPlanResponse, RusotoError<CreateSavingsPlanError>>;

    ///
Deletes the queued purchase for the specified Savings Plan.

    async fn delete_queued_savings_plan(
        &self,
        input: DeleteQueuedSavingsPlanRequest,
    ) -> Result<DeleteQueuedSavingsPlanResponse, RusotoError<DeleteQueuedSavingsPlanError>>;

    ///
Describes the specified Savings Plans rates.

    async fn describe_savings_plan_rates(
        &self,
        input: DescribeSavingsPlanRatesRequest,
    ) -> Result<DescribeSavingsPlanRatesResponse, RusotoError<DescribeSavingsPlanRatesError>>;

    ///
Describes the specified Savings Plans.

    async fn describe_savings_plans(
        &self,
        input: DescribeSavingsPlansRequest,
    ) -> Result<DescribeSavingsPlansResponse, RusotoError<DescribeSavingsPlansError>>;

    ///
Describes the specified Savings Plans offering rates.

    async fn describe_savings_plans_offering_rates(
        &self,
        input: DescribeSavingsPlansOfferingRatesRequest,
    ) -> Result<
        DescribeSavingsPlansOfferingRatesResponse,
        RusotoError<DescribeSavingsPlansOfferingRatesError>,
    >;

    ///
Describes the specified Savings Plans offerings.

    async fn describe_savings_plans_offerings(
        &self,
        input: DescribeSavingsPlansOfferingsRequest,
    ) -> Result<
        DescribeSavingsPlansOfferingsResponse,
        RusotoError<DescribeSavingsPlansOfferingsError>,
    >;

    ///
Lists the tags for the specified resource.

    async fn list_tags_for_resource(
        &self,
        input: ListTagsForResourceRequest,
    ) -> Result<ListTagsForResourceResponse, RusotoError<ListTagsForResourceError>>;

    ///
Adds the specified tags to the specified resource.

    async fn tag_resource(
        &self,
        input: TagResourceRequest,
    ) -> Result<TagResourceResponse, RusotoError<TagResourceError>>;

    ///
Removes the specified tags from the specified resource.

    async fn untag_resource(
        &self,
        input: UntagResourceRequest,
    ) -> Result<UntagResourceResponse, RusotoError<UntagResourceError>>;
}
/// A client for the AWSSavingsPlans API.
#[derive(Clone)]
pub struct SavingsPlansClient {
    client: Client,
    region: region::Region,
}

impl SavingsPlansClient {
    /// Creates a client backed by the default tokio event loop.
    ///
    /// The client will use the default credentials provider and tls client.
    pub fn new(region: region::Region) -> SavingsPlansClient {
        SavingsPlansClient {
            client: Client::shared(),
            region,
        }
    }

    pub fn new_with
(
        request_dispatcher: D,
        credentials_provider: P,
        region: region::Region,
    ) -> SavingsPlansClient
    where
        P: ProvideAwsCredentials + Send + Sync + 'static,
        D: DispatchSignedRequest + Send + Sync + 'static,
    {
        SavingsPlansClient {
            client: Client::new_with(credentials_provider, request_dispatcher),
            region,
        }
    }

    pub fn new_with_client(client: Client, region: region::Region) -> SavingsPlansClient {
        SavingsPlansClient { client, region }
    }
}

#[async_trait]
impl SavingsPlans for SavingsPlansClient {
    ///
Creates a Savings Plan.

    #[allow(unused_mut)]
    async fn create_savings_plan(
        &self,
        input: CreateSavingsPlanRequest,
    ) -> Result<CreateSavingsPlanResponse, RusotoError<CreateSavingsPlanError>> {
        let request_uri = "/CreateSavingsPlan";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<CreateSavingsPlanResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(CreateSavingsPlanError::from_response(response))
        }
    }

    ///
Deletes the queued purchase for the specified Savings Plan.

    #[allow(unused_mut)]
    async fn delete_queued_savings_plan(
        &self,
        input: DeleteQueuedSavingsPlanRequest,
    ) -> Result<DeleteQueuedSavingsPlanResponse, RusotoError<DeleteQueuedSavingsPlanError>> {
        let request_uri = "/DeleteQueuedSavingsPlan";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DeleteQueuedSavingsPlanResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DeleteQueuedSavingsPlanError::from_response(response))
        }
    }

    ///
Describes the specified Savings Plans rates.

    #[allow(unused_mut)]
    async fn describe_savings_plan_rates(
        &self,
        input: DescribeSavingsPlanRatesRequest,
    ) -> Result<DescribeSavingsPlanRatesResponse, RusotoError<DescribeSavingsPlanRatesError>> {
        let request_uri = "/DescribeSavingsPlanRates";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DescribeSavingsPlanRatesResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DescribeSavingsPlanRatesError::from_response(response))
        }
    }

    ///
Describes the specified Savings Plans.

    #[allow(unused_mut)]
    async fn describe_savings_plans(
        &self,
        input: DescribeSavingsPlansRequest,
    ) -> Result<DescribeSavingsPlansResponse, RusotoError<DescribeSavingsPlansError>> {
        let request_uri = "/DescribeSavingsPlans";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DescribeSavingsPlansResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DescribeSavingsPlansError::from_response(response))
        }
    }

    ///
Describes the specified Savings Plans offering rates.

    #[allow(unused_mut)]
    async fn describe_savings_plans_offering_rates(
        &self,
        input: DescribeSavingsPlansOfferingRatesRequest,
    ) -> Result<
        DescribeSavingsPlansOfferingRatesResponse,
        RusotoError<DescribeSavingsPlansOfferingRatesError>,
    > {
        let request_uri = "/DescribeSavingsPlansOfferingRates";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DescribeSavingsPlansOfferingRatesResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DescribeSavingsPlansOfferingRatesError::from_response(
                response,
            ))
        }
    }

    ///
Describes the specified Savings Plans offerings.

    #[allow(unused_mut)]
    async fn describe_savings_plans_offerings(
        &self,
        input: DescribeSavingsPlansOfferingsRequest,
    ) -> Result<
        DescribeSavingsPlansOfferingsResponse,
        RusotoError<DescribeSavingsPlansOfferingsError>,
    > {
        let request_uri = "/DescribeSavingsPlansOfferings";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DescribeSavingsPlansOfferingsResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DescribeSavingsPlansOfferingsError::from_response(response))
        }
    }

    ///
Lists the tags for the specified resource.

    #[allow(unused_mut)]
    async fn list_tags_for_resource(
        &self,
        input: ListTagsForResourceRequest,
    ) -> Result<ListTagsForResourceResponse, RusotoError<ListTagsForResourceError>> {
        let request_uri = "/ListTagsForResource";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<ListTagsForResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(ListTagsForResourceError::from_response(response))
        }
    }

    ///
Adds the specified tags to the specified resource.

    #[allow(unused_mut)]
    async fn tag_resource(
        &self,
        input: TagResourceRequest,
    ) -> Result<TagResourceResponse, RusotoError<TagResourceError>> {
        let request_uri = "/TagResource";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<TagResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(TagResourceError::from_response(response))
        }
    }

    ///
Removes the specified tags from the specified resource.

    #[allow(unused_mut)]
    async fn untag_resource(
        &self,
        input: UntagResourceRequest,
    ) -> Result<UntagResourceResponse, RusotoError<UntagResourceError>> {
        let request_uri = "/UntagResource";

        let mut request = SignedRequest::new("POST", "savingsplans", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<UntagResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(UntagResourceError::from_response(response))
        }
    }
}


text:
package org.apache.lucene.util;

import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.tokenattributes.*;

import java.util.Iterator;

public class TestAttributeSource extends LuceneTestCase {

  public void testCaptureState() {
    // init a first instance
    AttributeSource src = new AttributeSource();
    TermAttribute termAtt = src.addAttribute(TermAttribute.class);
    TypeAttribute typeAtt = src.addAttribute(TypeAttribute.class);
    termAtt.setTermBuffer("TestTerm");
    typeAtt.setType("TestType");
    final int hashCode = src.hashCode();

    AttributeSource.State state = src.captureState();

    // modify the attributes
    termAtt.setTermBuffer("AnotherTestTerm");
    typeAtt.setType("AnotherTestType");
    assertTrue("Hash code should be different", hashCode != src.hashCode());

    src.restoreState(state);
    assertEquals("TestTerm", termAtt.term());
    assertEquals("TestType", typeAtt.type());
    assertEquals("Hash code should be equal after restore", hashCode, src.hashCode());

    // restore into an exact configured copy
    AttributeSource copy = new AttributeSource();
    copy.addAttribute(TermAttribute.class);
    copy.addAttribute(TypeAttribute.class);
    copy.restoreState(state);
    assertEquals("Both AttributeSources should have same hashCode after restore", src.hashCode(), copy.hashCode());
    assertEquals("Both AttributeSources should be equal after restore", src, copy);

    // init a second instance (with attributes in different order and one additional attribute)
    AttributeSource src2 = new AttributeSource();
    typeAtt = src2.addAttribute(TypeAttribute.class);
    FlagsAttribute flagsAtt = src2.addAttribute(FlagsAttribute.class);
    termAtt = src2.addAttribute(TermAttribute.class);
    flagsAtt.setFlags(12345);

    src2.restoreState(state);
    assertEquals("TestTerm", termAtt.term());
    assertEquals("TestType", typeAtt.type());
    assertEquals("FlagsAttribute should not be touched", 12345, flagsAtt.getFlags());

    // init a third instance missing one Attribute
    AttributeSource src3 = new AttributeSource();
    termAtt = src3.addAttribute(TermAttribute.class);
    try {
      src3.restoreState(state);
      fail("The third instance is missing the TypeAttribute, so restoreState() should throw IllegalArgumentException");
    } catch (IllegalArgumentException iae) {
      // pass
    }
  }

  public void testCloneAttributes() {
    final AttributeSource src = new AttributeSource();
    final TermAttribute termAtt = src.addAttribute(TermAttribute.class);
    final TypeAttribute typeAtt = src.addAttribute(TypeAttribute.class);
    termAtt.setTermBuffer("TestTerm");
    typeAtt.setType("TestType");

    final AttributeSource clone = src.cloneAttributes();
    final Iterator<Class<? extends Attribute>> it = clone.getAttributeClassesIterator();
    assertEquals("TermAttribute must be the first attribute", TermAttribute.class, it.next());
    assertEquals("TypeAttribute must be the second attribute", TypeAttribute.class, it.next());
    assertFalse("No more attributes", it.hasNext());

    final TermAttribute termAtt2 = clone.getAttribute(TermAttribute.class);
    final TypeAttribute typeAtt2 = clone.getAttribute(TypeAttribute.class);
    assertNotSame("TermAttribute of original and clone must be different instances", termAtt2, termAtt);
    assertNotSame("TypeAttribute of original and clone must be different instances", typeAtt2, typeAtt);
    assertEquals("TermAttribute of original and clone must be equal", termAtt2, termAtt);
    assertEquals("TypeAttribute of original and clone must be equal", typeAtt2, typeAtt);
  }

  public void testToStringAndMultiAttributeImplementations() {
    AttributeSource src = new AttributeSource();
    TermAttribute termAtt = src.addAttribute(TermAttribute.class);
    TypeAttribute typeAtt = src.addAttribute(TypeAttribute.class);
    termAtt.setTermBuffer("TestTerm");
    typeAtt.setType("TestType");
    assertEquals("Attributes should appear in original order", "("+termAtt.toString()+","+typeAtt.toString()+")", src.toString());
    Iterator<AttributeImpl> it = src.getAttributeImplsIterator();
    assertTrue("Iterator should have 2 attributes left", it.hasNext());
    assertSame("First AttributeImpl from iterator should be termAtt", termAtt, it.next());
    assertTrue("Iterator should have 1 attributes left", it.hasNext());
    assertSame("Second AttributeImpl from iterator should be typeAtt", typeAtt, it.next());
    assertFalse("Iterator should have 0 attributes left", it.hasNext());

    src = new AttributeSource();
    src.addAttributeImpl(new Token());
    // this should not add a new attribute as Token implements TermAttribute, too
    termAtt = src.addAttribute(TermAttribute.class);
    assertTrue("TermAttribute should be implemented by Token", termAtt instanceof Token);
    // get the Token attribute and check, that it is the only one
    it = src.getAttributeImplsIterator();
    Token tok = (Token) it.next();
    assertFalse("There should be only one attribute implementation instance", it.hasNext());

    termAtt.setTermBuffer("TestTerm");
    assertEquals("Token should only printed once", "("+tok.toString()+")", src.toString());
  }

  public void testDefaultAttributeFactory() throws Exception {
    AttributeSource src = new AttributeSource();

    assertTrue("TermAttribute is not implemented by TermAttributeImpl",
      src.addAttribute(TermAttribute.class) instanceof TermAttributeImpl);
    assertTrue("OffsetAttribute is not implemented by OffsetAttributeImpl",
      src.addAttribute(OffsetAttribute.class) instanceof OffsetAttributeImpl);
    assertTrue("FlagsAttribute is not implemented by FlagsAttributeImpl",
      src.addAttribute(FlagsAttribute.class) instanceof FlagsAttributeImpl);
    assertTrue("PayloadAttribute is not implemented by PayloadAttributeImpl",
      src.addAttribute(PayloadAttribute.class) instanceof PayloadAttributeImpl);
    assertTrue("PositionIncrementAttribute is not implemented by PositionIncrementAttributeImpl",
      src.addAttribute(PositionIncrementAttribute.class) instanceof PositionIncrementAttributeImpl);
    assertTrue("TypeAttribute is not implemented by TypeAttributeImpl",
      src.addAttribute(TypeAttribute.class) instanceof TypeAttributeImpl);
  }

  @SuppressWarnings("unchecked")
  public void testInvalidArguments() throws Exception {
    try {
      AttributeSource src = new AttributeSource();
      src.addAttribute(Token.class);
      fail("Should throw IllegalArgumentException");
    } catch (IllegalArgumentException iae) {}

    try {
      AttributeSource src = new AttributeSource(Token.TOKEN_ATTRIBUTE_FACTORY);
      src.addAttribute(Token.class);
      fail("Should throw IllegalArgumentException");
    } catch (IllegalArgumentException iae) {}

    try {
      AttributeSource src = new AttributeSource();
      // break this by unsafe cast
      src.addAttribute((Class) Iterator.class);
      fail("Should throw IllegalArgumentException");
    } catch (IllegalArgumentException iae) {}
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SimpleLifestream\Providers;

/**
 * A provider for deviantart.com
 */
class Deviantart extends Feed
{
    /** inline {@inheritdoc} */
    public function __construct(array $settings)
    {
        $settings = array_merge($settings, array(
            'service' => 'deviantart',
            'resource' => 'http://backend.deviantart.com/rss.xml?q=gallery%3A' . urlencode($settings['resource']) . '&type=deviation',
            'resource_name' => $settings['resource']
        ));

        parent::__construct($settings);
    }
}
?>


text:
function [ out ] = kernelCache( op, rowpos, row )

persistent cache cacheSize;

% clear functions (To clear the cache)
if(op == -1)
    cacheSize = 55933;
    cache     = cell(1, cacheSize);
    out = true;
    return
end

% Create cache if none
if isempty(cache) %
    cacheSize = 55933;
%    cacheSize = 26893;
    cache     = cell(1, cacheSize);
end

if(op == 1) % find
    out = find(rowpos, cache, cacheSize);
else % save
    [cache] = save(rowpos, row, cache, cacheSize);
    out = [];
end

end

% functions to control the cache
function [out] = find(rowpos, cache, cacheSize)
    pp = mod(rowpos, cacheSize)+1;
    out  = [];
    if(isfield(cache{pp}, 'pos') && (cache{pp}.pos == rowpos))
         out = cache{pp}.row;
    end
end

% Pure hash map. Improve with least used eviction or at least open hashing
% functions to control the cache
function [cache] =  save(rowpos, row, cache, cacheSize)
    pp = mod(rowpos, cacheSize)+1;
    cache{pp}.pos = rowpos;
    cache{pp}.row = row;
end


text:
package uk.nhs.hdn.dbs.response.practiceAndAddressData;

import org.jetbrains.annotations.NotNull;
import uk.nhs.hdn.common.serialisers.MapSerialiser;
import uk.nhs.hdn.common.unknown.AbstractIsUnknown;

public final class UnknownPracticeAndAddressData extends AbstractIsUnknown implements PracticeAndAddressData
{
	@NotNull
	public static final PracticeAndAddressData UnknownPracticeAndAddressDataInstance = new UnknownPracticeAndAddressData();

	private UnknownPracticeAndAddressData()
	{
		super(true);
	}

	@Override
	public void serialiseMap(@NotNull final MapSerialiser mapSerialiser)
	{
	}
}


text:
int mpae_init_lame(audio_encoder_t *encoder);

#endif


text:
/**
 * @file
 *
 * @brief Offload to the Kernel offload workqueue
 *
 * @defgroup kernel_critical_tests Critical Tests
 *
 * @ingroup all_tests
 *
 * This test verifies that the kernel offload workqueue operates as
 * expected.
 *
 * This test has two threads that increment a counter.  The routine that
 * increments the counter is invoked from workqueue due to the two threads
 * calling using it.  The final result of the counter is expected
 * to be the the number of times work item was called to increment
 * the counter.
 *
 * This is done with time slicing both disabled and enabled to ensure that the
 * result always matches the number of times the workqueue is called.
 *
 * @{
 * @}
 */
#include <zephyr.h>
#include <linker/sections.h>
#include <ztest.h>

#define NUM_MILLISECONDS        5000
#define TEST_TIMEOUT            20000

static u32_t critical_var;
static u32_t alt_thread_iterations;

static struct k_work_q offload_work_q;
static K_THREAD_STACK_DEFINE(offload_work_q_stack,
			     CONFIG_OFFLOAD_WORKQUEUE_STACK_SIZE);

#define STACK_SIZE (1024 + CONFIG_TEST_EXTRA_STACKSIZE)

static K_THREAD_STACK_DEFINE(stack1, STACK_SIZE);
static K_THREAD_STACK_DEFINE(stack2, STACK_SIZE);

static struct k_thread thread1;
static struct k_thread thread2;

K_SEM_DEFINE(ALT_SEM, 0, UINT_MAX);
K_SEM_DEFINE(REGRESS_SEM, 0, UINT_MAX);
K_SEM_DEFINE(TEST_SEM, 0, UINT_MAX);

/**
 *
 * @brief Routine to be called from a workqueue
 *
 * This routine increments the global variable @a critical_var.
 *
 * @return 0
 */

void critical_rtn(struct k_work *unused)
{
	volatile u32_t x;

	ARG_UNUSED(unused);

	x = critical_var;
	critical_var = x + 1;

}

/**
 *
 * @brief Common code for invoking offload work
 *
 * @param count number of critical section calls made thus far
 *
 * @return number of critical section calls made by a thread
 */

u32_t critical_loop(u32_t count)
{
	s64_t mseconds;

	mseconds = k_uptime_get();
	while (k_uptime_get() < mseconds + NUM_MILLISECONDS) {
		struct k_work work_item;

		k_work_init(&work_item, critical_rtn);
		k_work_submit_to_queue(&offload_work_q, &work_item);
		count++;
#if defined(CONFIG_ARCH_POSIX)
		k_busy_wait(50);
		/*
		 * For the POSIX arch this loop and critical_rtn would otherwise
		 * run in 0 time and therefore would never finish.
		 * => We purposely waste 50us per loop
		 */
#endif
	}

	return count;
}

/**
 *
 * @brief Alternate thread
 *
 * This routine invokes the workqueue many times.
 *
 * @return N/A
 */

void alternate_thread(void *arg1, void *arg2, void *arg3)
{
	ARG_UNUSED(arg1);
	ARG_UNUSED(arg2);
	ARG_UNUSED(arg3);

	k_sem_take(&ALT_SEM, K_FOREVER);        /* Wait to be activated */

	alt_thread_iterations = critical_loop(alt_thread_iterations);

	k_sem_give(&REGRESS_SEM);

	k_sem_take(&ALT_SEM, K_FOREVER);        /* Wait to be re-activated */

	alt_thread_iterations = critical_loop(alt_thread_iterations);

	k_sem_give(&REGRESS_SEM);
}

/**
 *
 * @brief Regression thread
 *
 * This routine calls invokes the workqueue many times. It also checks to
 * ensure that the number of times it is called matches the global variable
 * @a critical_var.
 *
 * @return N/A
 */

void regression_thread(void *arg1, void *arg2, void *arg3)
{
	u32_t ncalls = 0U;

	ARG_UNUSED(arg1);
	ARG_UNUSED(arg2);
	ARG_UNUSED(arg3);

	k_sem_give(&ALT_SEM);   /* Activate alternate_tast() */

	ncalls = critical_loop(ncalls);

	/* Wait for alternate_thread() to complete */
	zassert_true(k_sem_take(&REGRESS_SEM, TEST_TIMEOUT) == 0,
		     "Timed out waiting for REGRESS_SEM");

	zassert_equal(critical_var, ncalls + alt_thread_iterations,
		      "Unexpected value for <critical_var>");

	k_sched_time_slice_set(10, 10);

	k_sem_give(&ALT_SEM);   /* Re-activate alternate_thread() */

	ncalls = critical_loop(ncalls);

	/* Wait for alternate_thread() to finish */
	zassert_true(k_sem_take(&REGRESS_SEM, TEST_TIMEOUT) == 0,
		     "Timed out waiting for REGRESS_SEM");

	zassert_equal(critical_var, ncalls + alt_thread_iterations,
		      "Unexpected value for <critical_var>");

	k_sem_give(&TEST_SEM);

}

static void init_objects(void)
{
	critical_var = 0U;
	alt_thread_iterations = 0U;
	k_work_q_start(&offload_work_q,
		       offload_work_q_stack,
		       K_THREAD_STACK_SIZEOF(offload_work_q_stack),
		       CONFIG_OFFLOAD_WORKQUEUE_PRIORITY);
}

static void start_threads(void)
{
	k_thread_create(&thread1, stack1, STACK_SIZE,
			alternate_thread, NULL, NULL, NULL,
			K_PRIO_PREEMPT(12), 0, 0);

	k_thread_create(&thread2, stack2, STACK_SIZE,
			regression_thread, NULL, NULL, NULL,
			K_PRIO_PREEMPT(12), 0, 0);
}

/**
 * @brief Verify thread context
 *
 * @details Check whether variable value per-thread is saved
 * during context switch
 *
 * @ingroup kernel_critical_tests
 */
void test_critical(void)
{
	init_objects();
	start_threads();

	zassert_true(k_sem_take(&TEST_SEM, TEST_TIMEOUT * 2) == 0,
		     "Timed out waiting for TEST_SEM");
}

void test_main(void)
{
	ztest_test_suite(kernel_critical,
			 ztest_unit_test(test_critical)
			 );
	ztest_run_test_suite(kernel_critical);
}


text:
package org.helios.journal;

import org.helios.journal.util.AllocationMode;

import java.io.IOException;
import java.nio.ByteBuffer;

public interface Journalling extends AutoCloseable
{
    Journalling open(final AllocationMode allocationMode);

    Journalling ensure(final int dataSize) throws IOException;

    int pageSize();

    long position();

    long size() throws IOException;

    int nextJournalNumber();

    int read(final ByteBuffer data) throws IOException;

    int write(final ByteBuffer data) throws IOException;

    Journalling flush() throws IOException;

    Journalling depletionHandler(final JournalDepletionHandler handler);
}


text:
ENV['RACK_ENV'] ||= 'production'

require 'sinatra/base'
require 'sinatra/json'
require 'sinatra/config_file'
require 'sinatra/cross_origin'
require 'sinatra/reloader'
require 'sinatra/logger'

# Require the bundler gem and then call Bundler.require to load in all gems listed in Gemfile.
require 'bundler'
Bundler.require :default, ENV['RACK_ENV'].to_sym

['helpers', 'routes', 'models'].each do |dir|
  Dir[File.join(File.dirname(__FILE__), dir, '**', '*.rb')].each do |file|
    require file
  end
end

# Main class supporting the Gatekeeper's Service Management micro-service
class GtkFnct < Sinatra::Base
  register Sinatra::ConfigFile
  register Sinatra::CrossOrigin
  register Sinatra::Reloader
  register Sinatra::Logger
  set :logger_level, :debug # or :fatal, :error, :warn, :info

  helpers GtkFnctHelper

  set :root, File.dirname(__FILE__)
  set :public_folder, File.join(File.dirname(__FILE__), 'public')
  set :bind, '0.0.0.0'
  set :time_at_startup, Time.now.utc
  set :environments, %w(development test integration qualification demonstration)
  set :environment, ENV['RACK_ENV'] || :development
  config_file File.join( [root, 'config', 'services.yml.erb'] )

  use Rack::Session::Cookie, :key => 'rack.session', :domain => 'foo.com', :path => '/', :expire_after => 2592000, :secret => '$0nata'

  # Logging
  MODULE='GtkFnct'
	enable :logging
  FileUtils.mkdir(File.join(settings.root, 'log')) unless File.exists? File.join(settings.root, 'log')
  logfile = File.open(File.join('log', ENV['RACK_ENV'])+'.log', 'a+')
  logfile.sync = true
  set :logger, Logger.new(logfile)
  raise 'Can not proceed without a logger file' if settings.logger.nil?
  set :logger_level, (settings.logger_level ||= 'debug').to_sym # can be debug, fatal, error, warn, or info

  logger.info(MODULE) {"Started at #{settings.time_at_startup}"}
  logger.info(MODULE) {"Logger level at :#{settings.logger_level}"}
  enable :cross_origin

  if settings.catalogues
    set :functions_catalogue, VFunction.new(settings.catalogues+'/vnfs', logger)
  else
    puts '    >>>Catalogue url not defined, application being terminated!!'
    Process.kill('TERM', Process.pid)
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/AutoScalingDescribeAutoScalingNotificationTypesResponseUnmarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/AutoScalingDescribeAutoScalingNotificationTypesResponseUnmarshaller</TokenIdentifier>
			<Abstract type="html">Describe Auto Scaling Notification Types Result Unmarshaller</Abstract>
			<DeclaredIn>AutoScalingDescribeAutoScalingNotificationTypesResponseUnmarshaller.h</DeclaredIn>

			<NodeRef refid="80"/>
		</Token>

	</File>
</Tokens>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;
using DvachBrowser3.Engines;
using DvachBrowser3.Styles;
using DvachBrowser3.Views;
using Template10.Common;
using Template10.Mvvm;

namespace DvachBrowser3.ViewModels
{
    /// <summary>
    /// Обёртка для прогресса операции.
    /// </summary>
    /// <typeparam name="TResult">Результат.</typeparam>
    /// <typeparam name="TProgress">Тип прогресса.</typeparam>
    public abstract class EngineOperationWrapper<TResult, TProgress> : ViewModelBase, IOperationViewModel, IOperationProgressViewModel where TProgress : EventArgs
    {
        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="operationFactory">Фабрика операций.</param>
        protected EngineOperationWrapper(Func<object, IEngineOperationsWithProgress<TResult, TProgress>> operationFactory)
        {
            if (operationFactory == null) throw new ArgumentNullException(nameof(operationFactory));
            OperationFactory = operationFactory;
            Progress = 0;
            IsIndeterminate = true;
            IsError = false;
            IsCancelled = false;
            Error = null;
            Message = null;
            IsActive = false;
            UpdateCanStart();
        }

        /// <summary>
        /// Фабрика операций.
        /// </summary>
        protected Func<object, IEngineOperationsWithProgress<TResult, TProgress>> OperationFactory { get; private set; }

        private bool canStart;

        /// <summary>
        /// Можно начинать.
        /// </summary>
        public bool CanStart
        {
            get { return canStart; }
            private set
            {
                canStart = value;
                RaisePropertyChanged();
            }
        }

        private bool isDisabled;

        private void UpdateCanStart()
        {
            CanStart = !IsActive && !isDisabled;
        }

        private async Task DoOperation(IEngineOperationsWithProgress<TResult, TProgress> operation, object arg)
        {
            IsActive = true;
            UpdateCanStart();
            IsError = false;
            Error = null;
            Exception = null;
            Progress = 0;
            IsIndeterminate = true;
            Message = null;
            IsCancelled = false;
            IsWaiting = true;
            Argument = arg;
            operation.Progress += OperationOnProgress;
            OperationProgressFinishedEventArgs finishArgs = null;
            try
            {
                using (var tokenSource = new CancellationTokenSource())
                {
                    cancelAction = () => tokenSource.Cancel();
                    try
                    {
                        try
                        {
                            Started?.Invoke(this, EventArgs.Empty);

                            var tcs = new TaskCompletionSource<TResult>();
                            ThreadPool.RunAsync(async (obj) =>
                            {
                                try
                                {
                                    var r = await operation.Complete(tokenSource.Token);
                                    tcs.SetResult(r);
                                }
                                catch (Exception ex)
                                {
                                    tcs.SetException(ex);
                                }
                            });
                            var result = await tcs.Task;
                            //var result = await operation.Complete(tokenSource.Token);
                            finishArgs = new OperationProgressFinishedEventArgs(arg);
                            ResultGot?.Invoke(this, result);
                        }
                        catch (Exception ex)
                        {
                            if (!tokenSource.IsCancellationRequested)
                            {
                                IsError = true;
                                Error = ex.Message;
                                Exception = ex;
                                finishArgs = new OperationProgressFinishedEventArgs(arg, ex);
                            }
                        }
                    }
                    finally
                    {
                        cancelAction = null;
                    }
                    if (tokenSource.IsCancellationRequested)
                    {
                        IsCancelled = true;
                        finishArgs = new OperationProgressFinishedEventArgs(arg, null, true);
                    }
                }
            }
            finally
            {
                operation.Progress -= OperationOnProgress;
                IsActive = false;
                IsWaiting = false;
                UpdateCanStart();
                if (finishArgs != null)
                {
                    Finished?.Invoke(this, finishArgs);
                }
            }
        }

        /// <summary>
        /// Высокий приоритет.
        /// </summary>
        public bool HighPriority { get; set; }

        /// <summary>
        /// Начать.
        /// </summary>
        /// <param name="arg">Аргумент.</param>
        public void Start2(object arg)
        {
            AppHelpers.ActionOnUiThread(async () =>
            {
                if (HighPriority)
                {
                    await Start2Async(arg);
                }
                else
                {
                    await Task.Yield();
                    using (await OperationSemaphore.Lock())
                    {
                        await Start2Async(arg);
                    }
                }
            });
        }

        private static readonly AsyncConcurrencySemaphore OperationSemaphore = new AsyncConcurrencySemaphore(10);

        private async Task Start2Async(object arg)
        {
            if (!CanStart)
            {
                return;
            }
            var operation = OperationFactory(arg);
            if (operation == null)
            {
                return;
            }
            var cancelFlag = new InterlockedFlagContainer();
            cancelAction = () =>
            {
                cancelFlag.Flag = true;
            };
            Func<Task> action = async () =>
            {
                if (cancelFlag.Flag)
                {
                    return;
                }
                await DoOperation(operation, arg);
            };
            await action();
        }

        public void Start()
        {
            Start2(null);
        }

        private void OperationOnProgress(object sender, TProgress p)
        {
            AppHelpers.DispatchAction(() =>
            {
                var progressValue = GetProgress(p);
                var messageValue = GetMessage(p);
                if (progressValue == null)
                {
                    Progress = 0;
                    IsIndeterminate = true;
                }
                else
                {
                    Progress = progressValue.Value;
                    IsIndeterminate = false;
                }
                Message = messageValue;
                IsWaiting = GetIsWaiting(p);
                return Task.CompletedTask;
            }, false, 0);
        }

        /// <summary>
        /// Получить прогресс.
        /// </summary>
        /// <param name="progress">Объект прогресса.</param>
        /// <returns>Прогресс.</returns>
        protected abstract double? GetProgress(TProgress progress);

        /// <summary>
        /// Получить сообщение.
        /// </summary>
        /// <param name="progress">Объект прогресса.</param>
        /// <returns>Сообщение.</returns>
        protected abstract string GetMessage(TProgress progress);

        /// <summary>
        /// Получить статус ожидания.
        /// </summary>
        /// <param name="progress">Прогресс.</param>
        /// <returns>Статус ожидания.</returns>
        protected abstract bool GetIsWaiting(TProgress progress);

        private Action cancelAction;

        /// <summary>
        /// Отменить.
        /// </summary>
        public void Cancel()
        {
            cancelAction?.Invoke();
        }

        /// <summary>
        /// Прогресс.
        /// </summary>
        IOperationProgressViewModel IOperationViewModel.Progress => this;

        /// <summary>
        /// Запретить.
        /// </summary>
        public void Disable()
        {
            isDisabled = true;
            UpdateCanStart();
        }

        /// <summary>
        /// Разрешить.
        /// </summary>
        public void Enable()
        {
            isDisabled = false;
            UpdateCanStart();
        }

        /// <summary>
        /// Нужна диспетчеризация.
        /// </summary>
        public bool NeedDispatch { get; set; }

        private double progress;

        /// <summary>
        /// Прогресс.
        /// </summary>
        public double Progress
        {
            get { return progress; }
            private set
            {
                progress = value;
                RaisePropertyChanged();
            }
        }

        private bool isIndeterminate;

        /// <summary>
        /// Неявное положение.
        /// </summary>
        public bool IsIndeterminate
        {
            get { return isIndeterminate; }
            private set
            {
                isIndeterminate = value;
                RaisePropertyChanged();
            }
        }

        private string message;

        /// <summary>
        /// Сообщение.
        /// </summary>
        public string Message
        {
            get { return message; }
            private set
            {
                message = value;
                RaisePropertyChanged();
            }
        }

        private bool isActive;

        /// <summary>
        /// Активен.
        /// </summary>
        public bool IsActive
        {
            get { return isActive; }
            private set
            {
                isActive = value;
                RaisePropertyChanged();
            }
        }

        private string error;

        /// <summary>
        /// Ошибка.
        /// </summary>
        public string Error
        {
            get { return error; }
            private set
            {
                error = value;
                RaisePropertyChanged();
            }
        }

        private Exception exception;

        /// <summary>
        /// Полная ошибка.
        /// </summary>
        public Exception Exception
        {
            get { return exception; }
            private set
            {
                exception = value;
                RaisePropertyChanged();
            }
        }

        private bool isError;

        /// <summary>
        /// Ошибка.
        /// </summary>
        public bool IsError
        {
            get { return isError; }
            private set
            {
                isError = value;
                RaisePropertyChanged();
            }
        }

        private bool isCancelled;

        /// <summary>
        /// Отменено.
        /// </summary>
        public bool IsCancelled
        {
            get { return isCancelled; }
            private set
            {
                isCancelled = value;
                RaisePropertyChanged();
            }
        }

        private bool isWaiting;

        /// <summary>
        /// Ожидается.
        /// </summary>
        public bool IsWaiting
        {
            get { return isWaiting; }
            private set
            {
                isWaiting = value;
                RaisePropertyChanged();
            }
        }

        private object argument;

        /// <summary>
        /// Аргумент.
        /// </summary>
        public object Argument
        {
            get { return argument; }
            private set
            {
                argument = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// Запущено.
        /// </summary>
        public event EventHandler Started;

        /// <summary>
        /// Прогресс изменился.
        /// </summary>
        public event EventHandler ProgressChanged;

        /// <summary>
        /// Завершено.
        /// </summary>
        public event OperationProgressFinishedEventHandler Finished;

        /// <summary>
        /// Менеджер стилей.
        /// </summary>
        public IStyleManager StyleManager { get; } = StyleManagerFactory.Current.GetManager();

        /// <summary>
        /// Получен результат.
        /// </summary>
        public event EventHandler<TResult> ResultGot;
    }
}


text:
package com.datacraftcoords;
import net.minecraft.client.gui.GuiRepair;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerRepair;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;

import com.datacraftcoords.HUDUtil;

public class GuiRepairOverride extends GuiRepair
{
	private static final int maxRepairTimes = 6;

    public GuiRepairOverride(InventoryPlayer inventoryPlayer, World world)
    {
        super(inventoryPlayer, world);
    }

    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
    {
    	super.drawGuiContainerForegroundLayer(mouseX, mouseY);

        //GlStateManager.disableLighting();
        //GlStateManager.disableBlend();

		ContainerRepair anvil = HUDUtil.GetFieldByReflection(GuiRepair.class, (GuiRepair)this, "anvil", "field_147092_v");
    	IInventory inputSlots = HUDUtil.GetFieldByReflection(ContainerRepair.class, anvil, "inputSlots", "field_82853_g");

        ItemStack leftItemStack = inputSlots.getStackInSlot(0);
        ItemStack rightItemStack = inputSlots.getStackInSlot(1);
        ItemStack finalItemStack = inputSlots.getStackInSlot(2);

        if(leftItemStack != null)
        {
        	int timesRepaired = GetTimesRepaired(leftItemStack);
        	String leftItemRepairCost;

        	if(timesRepaired >= maxRepairTimes)
        		leftItemRepairCost = "" + EnumChatFormatting.DARK_RED + timesRepaired + EnumChatFormatting.DARK_GRAY + "/" + maxRepairTimes;
        	else
        		leftItemRepairCost = "" + EnumChatFormatting.DARK_GRAY + timesRepaired + "/" + maxRepairTimes;

            fontRendererObj.drawString(leftItemRepairCost, 26, 37, 0xffffff);
            //System.out.println(leftItemRepairCost);
        }
        if(rightItemStack != null)
        {
        	int timesRepaired = GetTimesRepaired(rightItemStack);
        	String rightItemRepairCost;

        	if(timesRepaired >= maxRepairTimes)
        		rightItemRepairCost = "" + EnumChatFormatting.DARK_RED + timesRepaired + EnumChatFormatting.DARK_GRAY + "/" + maxRepairTimes;
        	else
        		rightItemRepairCost = "" + EnumChatFormatting.DARK_GRAY + timesRepaired + "/" + maxRepairTimes;

            fontRendererObj.drawString(rightItemRepairCost, 76, 37, 0xffffff);
            //System.out.println(rightItemRepairCost);
        }
        if(leftItemStack != null && rightItemStack != null)
        {
        	int timesRepaired = GetTimesRepaired(leftItemStack) + GetTimesRepaired(rightItemStack) + 1;
        	String finalItemRepairCost = "" + EnumChatFormatting.DARK_GRAY + timesRepaired+"/" + maxRepairTimes;

        	if(timesRepaired <= maxRepairTimes)
        	{
                fontRendererObj.drawString(finalItemRepairCost, 133, 37, 0xffffff);
                //System.out.println(finalItemRepairCost);
        	}
        }

        //GlStateManager.enableLighting();
    }

    protected static int GetTimesRepaired(ItemStack itemStack)
    {
    	/*
    	equations: 2^n - 1, log2(n + 1)
    	times repair, repair cost, xp
    	0: 0, 2
    	1: 1, 3
    	2: 3, 5
    	3: 7, 9
    	4: 15, 17
    	5: 31, 33
    	6: 63, 65 (too expensive)
    	*/
    	return log(itemStack.getRepairCost() + 1, 2);
    }

    private static int log(int x, int base)
    {
        return (int)(Math.log(x) / Math.log(base));
    }
}


text:
<?php
require_once("post.php");
$postid = $_REQUEST['postid'];
$time = $_REQUEST['time'];
$post = new post();
$post->laporkan($postid,$time);
if(isset($_REQUEST['submit'])){
    @session_start();
    $user = $_SESSION['username'];
    $laporan = $_REQUEST['laporan'];
    $uploader = 'admin';
    $isi = "$user melaporkan
    foto dengan alasan $laporan";
    $post->add_notif($uploader,$postid,$isi,$user);
    header("Location:home.php");
}else if(isset($_REQUEST['peringatan'])){
    @session_start();
    $user = $_SESSION['username'];
    $uploader = $_REQUEST['user'];
    $isi = "$user menandai
    foto anda sebagai hal yang tidak pantas
    , Silahkan hapus atau anda akan diblokir, terima kasih";
    $post->add_notif($uploader,$postid,$isi,$user);
    header("Location:home.php");
}

 ?>


text:
(function() {
    'use strict';

    angular.module('app').
    directive('addUiux', function() {
        return {
            restrict: "E",
            replace: true,
            templateUrl: 'app/components/addCreativity/itemCards/adduiux.html',
            controller: function($scope, addItemService, $sce, allDataService, $rootScope) {
                //Define Variables
                $scope.url = '';
                $scope.fetchLoading = false;
                $scope.graphicsAdded = false;
                $scope.linkUrl = false;
                $scope.UiUxAdded = false;

                //End Defining variable

                $scope.checkPublishableUiUx = function() {
                    $scope.UiUxAdded = $scope.linkUrl || $scope.graphicsAdded;
                    $scope.$emit("publishable", $scope.UiUxAdded);
                }
                $scope.removeUiUxItem = function(index) {
                    $scope.creativity.items.splice(index, 1);
                    if ($scope.creativity.items.length == 1 || $scope.creativity.items[1].mediaType == 'image') {
                        $scope.linkUrl = false;
                        $scope.checkPublishableUiUx();
                    }
                }
                $rootScope.$on("ImagesAdded", function(event) {
                    console.log('uiux ;jasncals');
                    $scope.graphicsAdded = true;
                    $scope.drawingAdded = false; // On adding images this variable is set true in add drawing directive so we have to set it false here !
                    $scope.checkPublishableUiUx();
                });
                $scope.onTypeUiUx = function(url) {
                    if ($scope.validateUrl(url)) {
                        $scope.linkUrl = true;
                        $scope.checkPublishableUiUx();
                        $scope.error = '';
                        $scope.fetchLoading = true;
                        addItemService.iframely(url, "embed")
                            .then(function(response) {
                                $scope.fetchLoading = false;
                                $scope.inputActive = false;
                            }).catch(function(err) {
                                console.log("Retrying!");
                                addItemService.iframely(url, "embed")
                                    .then(function(response) {
                                        $scope.fetchLoading = false;
                                        $scope.inputActive = false;
                                    }).catch(function(err) {
                                        $scope.fetchLoading = false;
                                        $scope.error = err.message;
                                    });
                            });
                    } else {
                        $scope.fetchLoading = false;
                        $scope.linkUrl = false;
                        $scope.checkPublishableUiUx();
                        $scope.error = 'Invalid url!';
                    }
                }

                $scope.removeUiuxImage = function(index) {
                    $scope.creativity.items.splice(index, 1);
                    console.log($scope.creativity.items.length == 1 || $scope.creativity.items[1].mediaType == 'embed');
                    if ($scope.creativity.items.length == 1 || $scope.creativity.items[1].mediaType == 'embed') {
                        $scope.graphicsAdded = false;
                        $scope.drawingAdded = false; // On adding images this variable is set true in add drawing directive so we have to set it false here !
                        $scope.checkPublishableUiUx();
                    }
                }

            }
        };
    });

})();


text:
using TravelAgency.Data;

namespace TravelAgency.ReportGenerators.Contracts
{
    public interface IReportGenerator
    {
        void GenerateReport(ITravelAgencyDbContext travelAgencyDbContext);
    }
}


text:
<?php
namespace Skrz\Templating\Engine\AST;

/**
 * {$var -->|trim<--}
 *
 * @author Jakub Kulhan <jakub.kulhan@gmail.com>
 */
class ModifierNode extends AbstractNode
{

	/** @var string */
	private $name;

	/** @var PHPNode[] */
	private $arguments = array();

	/** @var string */
	private $fileName;

	/** @var int */
	private $row;

	/** @var int */
	private $column;

	public function __construct($name, array $arguments, $fileName, $row, $column)
	{
		$this->name = $name;
		$this->arguments = $arguments;
		$this->fileName = $fileName;
		$this->row = $row;
		$this->column = $column;
	}

	public function getName()
	{
		return $this->name;
	}

	public function getArguments()
	{
		return $this->arguments;
	}

	public function hasArgument($i)
	{
		return isset($this->arguments[$i]);
	}

	public function getArgument($i)
	{
		return $this->arguments[$i];
	}

	public function getFileName()
	{
		return $this->fileName;
	}

	public function getRow()
	{
		return $this->row;
	}

	public function getColumn()
	{
		return $this->column;
	}

}


text:
require 'spec_helper'

describe Servme::Service do
  def app
    Servme::Service
  end

  describe "default responses" do
    shared_examples_for "default responses" do
      Then { last_response.headers['Content-Type'].should == 'application/json' }
      Then { last_response.status.should == 404 }
      Then do
        last_response.body.should be_json({
          :error => "Servme doesn't know how to respond to this request",
          :request => {
            :method => method,
            :params => {
              :like => "dance"
            },
            :path => "/do/stuff"
          }
        })
      end
    end

    describe "#get" do
      it_behaves_like "default responses" do
        Given(:method) { "get" }
        When { get('/do/stuff?like=dance') }
      end
    end

    describe "#post" do
      it_behaves_like "default responses" do
        Given(:method) { "post" }
        When { post('/do/stuff', {:like => "dance"}) }
      end
    end

    describe "#put" do
      it_behaves_like "default responses" do
        Given(:method) { "put" }
        When { put('/do/stuff', { :like => "dance" }) }
      end
    end

    describe "#delete" do
      it_behaves_like "default responses" do
        Given(:method) { "delete" }
        When { delete('/do/stuff', { :like => "dance" }) }
      end
    end
  end

end