text:
/*
	A vector implementation by Charles Bailey
	Because sundays are boring.

	12/4/16
*/

#ifndef CHARLES_VECTOR_H
#define CHARLES_VECTOR_H

#include <stdexcept>
#include <initializer_list>
#include <iterator>

#include <iostream>

namespace Charles {

	/*
		This implementation corresponds closely to std::vector,
		except that Allocators are not present here. Also, I have
		added .each and .map, because sorta-functional programming
		is pretty cool.
	*/

	typedef unsigned int size_t;

	template <typename T>
	class Vector {

		typedef T value_type;
		typedef long difference_type;
		typedef value_type& reference;
		typedef const reference const_reference;
		typedef T* pointer;
		typedef const pointer const_pointer;

		T *stuff;
		size_t actual_size, num_elements;

		class _iterator : public std::iterator<std::random_access_iterator_tag, value_type, difference_type, pointer, reference> {
		  public:
			T* ptr;

			explicit _iterator(T* _ptr) : ptr(_ptr) {}

			_iterator& operator++() {
				++ptr;
				return *this;
			}
			_iterator operator++(int) {
				T* temp = ptr++;
				return _iterator(temp);
			}

			_iterator& operator--() {
				--ptr;
				return *this;
			}
			_iterator operator--(int) {
				T* temp = ptr--;
				return _iterator(temp);
			}

			_iterator operator+(difference_type s) const {
				return _iterator(ptr + s);
			}

			_iterator operator-(difference_type s) const {
				return _iterator(ptr - s);
			}

			difference_type operator-(_iterator& other) const {
				return this->ptr > other.ptr ? this->ptr - other.ptr : other.ptr - this->ptr;
			}

			bool operator==(const _iterator& other) const {
				return this->ptr == other.ptr;
			}
			bool operator!=(const _iterator& other) const {
				return this->ptr != other.ptr;
			}

			reference operator*() const {
				return *ptr;
			}
		};

		typedef _iterator iterator;
		typedef const iterator const_iterator;
		typedef std::reverse_iterator<iterator> reverse_iterator;
		typedef const reverse_iterator const_reverse_iterator;

	  public:
		Vector();
		Vector(size_t _size, T def = T());
		Vector(const Vector<T>& other);
		Vector(Vector<T>&& other);
		Vector(std::initializer_list<T> init);

		template <class InputIt>
		Vector(InputIt _begin, InputIt _end);

		Vector<T>& operator=(const Vector<T>& other);
		Vector<T>& operator=(Vector<T>&& other);
		Vector<T>& operator=(std::initializer_list<T> init);

		~Vector();

		T& operator[](size_t index);
		const T& operator[](size_t index) const;

		T& at(size_t index);
		const T& at(size_t index) const;

		T& front();
		const T& front() const;

		T& back();
		const T& back() const;

		iterator begin();
		iterator end();
		const_iterator cbegin() const;
		const_iterator cend() const;

		T* data();
		const T* data() const;

		bool empty() const;

		void push_back(const T& item);
 		T pop_back();

		void insert(int& index , T& item);

		/* TODO: */
		iterator insert(const_iterator pos, const T& item);
		iterator insert(const_iterator pos, T&& item);
		iterator insert(const_iterator pos, size_t count, const T& item);

		size_t size() const;
		size_t capacity() const;
		size_t max_size() const;

		void shrink_to_fit();
		void reserve(size_t new_size);

		void resize(size_t count);
		void resize(size_t count , const T& value);
		void assign(size_t count , const T& value);

		void clear();

		iterator erase(const_iterator pos);
		iterator erase(const_iterator first, const_iterator last);

		void swap(Vector<T>& other);

		bool operator==(const Vector<T>& other) const;
		bool operator!=(const Vector<T>& other) const;
		bool operator<=(const Vector<T>& other) const;
		bool operator>=(const Vector<T>& other) const;
		bool operator<(const Vector<T>& other) const;
		bool operator>(const Vector<T>& other) const;

		template <class Func>
		Vector<T> map(const Func& f);

		template <class Func>
		void each(const Func& f) const;

	  private:

		void _grow();
		void _resize(const size_t& new_size);
	};

	template <typename T>
	Vector<T>::Vector() : actual_size(10), num_elements(0) {
		stuff = new T[actual_size];
	}

	template <typename T>
	Vector<T>::Vector(size_t _size, T def) {
		actual_size = _size;
		stuff = new T[actual_size];

		num_elements = 0;
		while (num_elements < actual_size)
			stuff[num_elements++] = def;
	}

	template <typename T>
	Vector<T>::Vector(const Vector<T>& other) {
		*this = other;
	}

	template <typename T>
	Vector<T>::Vector(Vector<T>&& other) {
		*this = other;
	}

	template <typename T>
	Vector<T>::Vector(std::initializer_list<T> init) {
		*this = init;
	}

	template <typename T>
	template <class InputIt>
	Vector<T>::Vector(InputIt _begin, InputIt _end) {
		num_elements = actual_size = std::distance(_end, _begin);

		stuff = new T[actual_size];
		for (size_t i = 0; i < num_elements && _begin != _end; i++) {
			stuff[i] = *_begin++;
		}
	}

	template <typename T>
	Vector<T>& Vector<T>::operator=(const Vector<T>& other) {
		if (this == &other)
			return *this;

		actual_size = other.actual_size;
		stuff = new T[actual_size];

		num_elements = 0;
		while(num_elements < other.num_elements) {
			stuff[num_elements] = other.stuff[num_elements];
			num_elements++;
		}
		return *this;
	}

	template <typename T>
	Vector<T>& Vector<T>::operator=(Vector<T>&& other) {
		if (this == &other)
			return *this;

		actual_size = other.actual_size;
		num_elements = other.num_elements;

		stuff = other.stuff;
		other.stuff = nullptr;
		return *this;
	}

	template <typename T>
	Vector<T>& Vector<T>::operator=(std::initializer_list<T> init) {
		num_elements = actual_size = init.size();
		stuff = new T[actual_size];
		for (size_t i = 0; i < num_elements; i++) {
			stuff[i] = *(init.begin() + i);
		}
		return *this;
	}

	template <typename T>
	Vector<T>::~Vector() {
		if (stuff != nullptr)
			delete [] stuff;
	}

	template <typename T>
	T& Vector<T>::operator[](size_t index) {
		return stuff[index];
	}

	template <typename T>
	const T& Vector<T>::operator[](size_t index) const {
		return stuff[index];
	}

	template <typename T>
	T& Vector<T>::at(size_t index) {
		if (index >= num_elements)
			throw std::out_of_range("That index is out of range.");
		return stuff[index];
	}

	template <typename T>
	const T& Vector<T>::at(size_t index) const {
		if (index >= num_elements)
			throw std::out_of_range("That index is out of range.");
		return stuff[index];
	}

	template <typename T>
	T& Vector<T>::front() {
		return at(0);
	}

	template <typename T>
	const T& Vector<T>::front() const {
		return at(0);
	}

	template <typename T>
	T& Vector<T>::back() {
		return at(num_elements - 1);
	}

	template <typename T>
	const T& Vector<T>::back() const {
		return at(num_elements - 1);
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::begin() {
		return iterator(stuff);
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::end() {
		return iterator(stuff + num_elements);
	}

	template <typename T>
	typename Vector<T>::const_iterator Vector<T>::cbegin() const {
		return begin();
	}

	template <typename T>
	typename Vector<T>::const_iterator Vector<T>::cend() const {
		return end();
	}

	template <typename T>
	T* Vector<T>::data() {
		return stuff;
	}

	template <typename T>
	const T* Vector<T>::data() const {
		return (const T*)stuff;
	}

	template <typename T>
	bool Vector<T>::empty() const {
		return num_elements == 0;
	}

	template <typename T>
	void Vector<T>::push_back(const T& item) {
		if (num_elements >= actual_size)
			_grow();
		stuff[num_elements++] = item;
	}

	template <typename T>
	T Vector<T>::pop_back() {
		return stuff[--num_elements];
	}

	template <typename T>
	void Vector<T>::insert(int& index , T& item) {
		this->insert( begin() + index , 1 , item );
	}

	/* still working on this */
	template <typename T>
	typename Vector<T>::iterator Vector<T>::insert(const_iterator pos, const T& item) {
		return this->insert(pos, 1, item);
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::insert(const_iterator pos, T&& item) {
		return this->insert(pos, 1, item);
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::insert(const_iterator pos, size_t count, const T& item) {
		while (num_elements + count > actual_size)
			_grow();

		long curr = num_elements;
		long index = pos.ptr - stuff;

		while (--curr >= index ) {
			stuff[curr + count] = stuff[curr];
		}
		for (size_t i = 0; i < count; i++) {
			stuff[index++] = item;
		}
		num_elements += count;
		return pos;
	}

	template <typename T>
	size_t Vector<T>::size() const {
		return num_elements;
	}

	template <typename T>
	size_t Vector<T>::capacity() const {
		return actual_size;
	}

	template <typename T>
	size_t Vector<T>::max_size() const {
		size_t sz = 0;
		return (sz-1);
	}

	template <typename T>
	void Vector<T>::shrink_to_fit() {
		_resize(num_elements);
	}

	template <typename T>
	void Vector<T>::reserve(size_t new_size) {
		if (new_size > actual_size)
			_resize(new_size);
	}

	template <typename T>
	void Vector<T>::resize(size_t count) {
		_resize(count);
	}

	template <typename T>
	void Vector<T>::resize(size_t count , const T& value) {
		bool writein = count > actual_size;
		_resize(count);

		if (writein)
			while (num_elements < actual_size)
				stuff[num_elements++] = value;
	}

	template <typename T>
	void Vector<T>::assign(size_t count , const T& value) {
		num_elements = 0;
		resize(count, value);
	}

	template <typename T>
	void Vector<T>::clear() {
		for (size_t i = 0; i < num_elements; i++) {
			stuff[i] = T();
		}
		num_elements = 0;
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::erase(const_iterator pos) {
		return this->erase(pos, pos+1);
	}

	template <typename T>
	typename Vector<T>::iterator Vector<T>::erase(const_iterator first, const_iterator last) {
		for (iterator peek = last, hold = first; peek != this->end(); ++peek, ++hold) {
			*hold = std::move(*peek);
		}
		// amend size.
		num_elements -= std::distance(first, last); /* pretty sure the iterators meet RandomAccessIterator so this is constant time */
		return first;
	}

	template <typename T>
	void Vector<T>::swap(Vector<T>& other) {
		std::swap(this->num_elements , other.num_elements);
		std::swap(this->actual_size , other.actual_size);
		std::swap(this->stuff, other.stuff);
	}

	template <typename T>
	bool Vector<T>::operator==(const Vector<T>& other) const {
		if (other.num_elements != this->num_elements) return false;
		for (size_t i = 0; i < this->num_elements; i++) {
			if (other.stuff[i] != this->stuff[i])
				return false;
		}
		return true;
	}

	template <typename T>
	bool Vector<T>::operator!=(const Vector<T>& other) const {
		return !(*this == other);
	}

	template <typename T>
	bool Vector<T>::operator<=(const Vector<T>& other) const {
		/* check that *this <= other by factoring out a NOT */
		return !(*this > other);
	}

	template <typename T>
	bool Vector<T>::operator>=(const Vector<T>& other) const {
		return !(*this < other);
	}

	template <typename T>
	bool Vector<T>::operator<(const Vector<T>& other) const {
		size_t n = this->num_elements < other.num_elements ? this->num_elements : other.num_elements;
		for (size_t i = 0; i < n; i++) {
			if ( this->stuff[i] >= other.stuff[i] )
				return false;
		}
		/* A shorter list is "less than," but two list of equal size are
			ALSO "less than" because the elements of *this must all be less than
			the corresponding elements of other to have gotten this far. */
		return this->num_elements <= other.num_elements;
	}

	template <typename T>
	bool Vector<T>::operator>(const Vector<T>& other) const {
		size_t n = this->num_elements < other.num_elements ? this->num_elements : other.num_elements;
		for (size_t i = 0; i < n; i++) {
			if ( this->stuff[i] <= other.stuff[i] )
				return false;
		}
		/* same logic as < */
		return this->num_elements >= other.num_elements;
	}

	template <typename T>
	template <class Func>
	Vector<T> Vector<T>::map(const Func& f) {
		Vector<T> new_vec(*this);
		for (size_t i = 0; i < num_elements; i++)
			f(new_vec[i]);
		return new_vec;
	}

	template <typename T>
	template <class Func>
	void Vector<T>::each(const Func& f) const {
		T tmp;
		for (size_t i = 0; i < num_elements; i++) {
			tmp = stuff[i];
			f(tmp);
		}
	}

	template <typename T>
	void Vector<T>::_grow() {
		_resize(2 * actual_size + 1);
	}

	template <typename T>
	void Vector<T>::_resize(const size_t& new_size) {
		if (actual_size == new_size)
			return;

		actual_size = new_size;
		T *tmp = new T[actual_size];

		size_t n = actual_size < num_elements ? actual_size : num_elements;
		for (size_t i = 0; i < n; i++)
			tmp[i] = stuff[i];

		delete [] stuff;
		stuff = tmp;
	}

};

#endif // CHARLES_VECTOR_H


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v12/enums/user_list_number_rule_item_operator.proto

namespace Google\Ads\GoogleAds\V12\Enums\UserListNumberRuleItemOperatorEnum;

use UnexpectedValueException;

/**
 * Enum describing possible user list number rule item operators.
 *
 * Protobuf type google.ads.googleads.v12.enums.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator
 */
class UserListNumberRuleItemOperator
{
    /**
     * Not specified.
     *
     * Generated from protobuf enum UNSPECIFIED = 0;
     */
    const UNSPECIFIED = 0;
    /**
     * Used for return value only. Represents value unknown in this version.
     *
     * Generated from protobuf enum UNKNOWN = 1;
     */
    const UNKNOWN = 1;
    /**
     * Greater than.
     *
     * Generated from protobuf enum GREATER_THAN = 2;
     */
    const GREATER_THAN = 2;
    /**
     * Greater than or equal.
     *
     * Generated from protobuf enum GREATER_THAN_OR_EQUAL = 3;
     */
    const GREATER_THAN_OR_EQUAL = 3;
    /**
     * Equals.
     *
     * Generated from protobuf enum EQUALS = 4;
     */
    const EQUALS = 4;
    /**
     * Not equals.
     *
     * Generated from protobuf enum NOT_EQUALS = 5;
     */
    const NOT_EQUALS = 5;
    /**
     * Less than.
     *
     * Generated from protobuf enum LESS_THAN = 6;
     */
    const LESS_THAN = 6;
    /**
     * Less than or equal.
     *
     * Generated from protobuf enum LESS_THAN_OR_EQUAL = 7;
     */
    const LESS_THAN_OR_EQUAL = 7;

    private static $valueToName = [
        self::UNSPECIFIED => 'UNSPECIFIED',
        self::UNKNOWN => 'UNKNOWN',
        self::GREATER_THAN => 'GREATER_THAN',
        self::GREATER_THAN_OR_EQUAL => 'GREATER_THAN_OR_EQUAL',
        self::EQUALS => 'EQUALS',
        self::NOT_EQUALS => 'NOT_EQUALS',
        self::LESS_THAN => 'LESS_THAN',
        self::LESS_THAN_OR_EQUAL => 'LESS_THAN_OR_EQUAL',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(UserListNumberRuleItemOperator::class, \Google\Ads\GoogleAds\V12\Enums\UserListNumberRuleItemOperatorEnum_UserListNumberRuleItemOperator::class);

redpajama_set_name: RedPajamaGithub


text:
using ::testing::_;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::Truly;
using ::testing::NiceMock;

using blink::WebLocalFrame;
using blink::WebString;
using blink::WebURLError;
using blink::WebURLResponse;
using blink::WebView;

namespace media {

const char kHttpUrl[] = "http://test";
const char kHttpRedirect[] = "http://test/ing";

const int kDataSize = 1024;
const int kHttpOK = 200;
const int kHttpPartialContent = 206;

enum NetworkState { NONE, LOADED, LOADING };

// Predicate that tests that request disallows compressed data.
static bool CorrectAcceptEncoding(const blink::WebURLRequest& request) {
  std::string value =
      request.httpHeaderField(
                 WebString::fromUTF8(net::HttpRequestHeaders::kAcceptEncoding))
          .utf8();
  return (value.find("identity;q=1") != std::string::npos) &&
         (value.find("*;q=0") != std::string::npos);
}

class ResourceMultiBufferDataProviderTest : public testing::Test {
 public:
  ResourceMultiBufferDataProviderTest()
      : view_(WebView::create(nullptr)),
        frame_(WebLocalFrame::create(blink::WebTreeScopeType::Document,
                                     &client_)) {
    view_->setMainFrame(frame_);
    url_index_.reset(new UrlIndex(frame_, 0));

    for (int i = 0; i < kDataSize; ++i) {
      data_[i] = i;
    }
  }

  virtual ~ResourceMultiBufferDataProviderTest() {
    view_->close();
    frame_->close();
  }

  void Initialize(const char* url, int first_position) {
    gurl_ = GURL(url);
    url_data_ = url_index_->GetByUrl(gurl_, UrlData::CORS_UNSPECIFIED);
    DCHECK(url_data_);
    DCHECK(url_data_->frame());
    url_data_->OnRedirect(
        base::Bind(&ResourceMultiBufferDataProviderTest::RedirectCallback,
                   base::Unretained(this)));

    first_position_ = first_position;

    scoped_ptr<ResourceMultiBufferDataProvider> loader(
        new ResourceMultiBufferDataProvider(url_data_.get(), first_position_));
    loader_ = loader.get();
    url_data_->multibuffer()->AddProvider(std::move(loader));

    // |test_loader_| will be used when Start() is called.
    url_loader_ = new NiceMock<MockWebURLLoader>();
    loader_->test_loader_ = scoped_ptr<blink::WebURLLoader>(url_loader_);
  }

  void Start() {
    InSequence s;
    EXPECT_CALL(*url_loader_,
                loadAsynchronously(Truly(CorrectAcceptEncoding), loader_));

    loader_->Start();
  }

  void FullResponse(int64_t instance_size, bool ok = true) {
    WebURLResponse response(gurl_);
    response.setHTTPHeaderField(
        WebString::fromUTF8("Content-Length"),
        WebString::fromUTF8(base::StringPrintf("%" PRId64, instance_size)));
    response.setExpectedContentLength(instance_size);
    response.setHTTPStatusCode(kHttpOK);
    loader_->didReceiveResponse(url_loader_, response);

    if (ok) {
      EXPECT_EQ(instance_size, url_data_->length());
    }

    EXPECT_FALSE(url_data_->range_supported());
  }

  void PartialResponse(int64_t first_position,
                       int64_t last_position,
                       int64_t instance_size) {
    PartialResponse(first_position, last_position, instance_size, false, true);
  }

  void PartialResponse(int64_t first_position,
                       int64_t last_position,
                       int64_t instance_size,
                       bool chunked,
                       bool accept_ranges) {
    WebURLResponse response(gurl_);
    response.setHTTPHeaderField(
        WebString::fromUTF8("Content-Range"),
        WebString::fromUTF8(
            base::StringPrintf("bytes "
                               "%" PRId64 "-%" PRId64 "/%" PRId64,
                               first_position, last_position, instance_size)));

    // HTTP 1.1 doesn't permit Content-Length with Transfer-Encoding: chunked.
    int64_t content_length = -1;
    if (chunked) {
      response.setHTTPHeaderField(WebString::fromUTF8("Transfer-Encoding"),
                                  WebString::fromUTF8("chunked"));
    } else {
      content_length = last_position - first_position + 1;
    }
    response.setExpectedContentLength(content_length);

    // A server isn't required to return Accept-Ranges even though it might.
    if (accept_ranges) {
      response.setHTTPHeaderField(WebString::fromUTF8("Accept-Ranges"),
                                  WebString::fromUTF8("bytes"));
    }

    response.setHTTPStatusCode(kHttpPartialContent);
    loader_->didReceiveResponse(url_loader_, response);

    EXPECT_EQ(instance_size, url_data_->length());

    // A valid partial response should always result in this being true.
    EXPECT_TRUE(url_data_->range_supported());
  }

  void Redirect(const char* url) {
    GURL redirectUrl(url);
    blink::WebURLRequest newRequest(redirectUrl);
    blink::WebURLResponse redirectResponse(gurl_);

    EXPECT_CALL(*this, RedirectCallback(_))
        .WillOnce(
            Invoke(this, &ResourceMultiBufferDataProviderTest::SetUrlData));

    loader_->willFollowRedirect(url_loader_, newRequest, redirectResponse);

    base::MessageLoop::current()->RunUntilIdle();
  }

  void StopWhenLoad() {
    InSequence s;
    EXPECT_CALL(*url_loader_, cancel());
    loader_ = nullptr;
    url_data_ = nullptr;
  }

  // Helper method to write to |loader_| from |data_|.
  void WriteLoader(int position, int size) {
    loader_->didReceiveData(
        url_loader_, reinterpret_cast<char*>(data_ + position), size, size);
  }

  void WriteData(int size) {
    scoped_ptr<char[]> data(new char[size]);
    loader_->didReceiveData(url_loader_, data.get(), size, size);
  }

  // Verifies that data in buffer[0...size] is equal to data_[pos...pos+size].
  void VerifyBuffer(uint8_t* buffer, int pos, int size) {
    EXPECT_EQ(0, memcmp(buffer, data_ + pos, size));
  }

  bool HasActiveLoader() { return loader_->active_loader_ != nullptr; }
  MOCK_METHOD1(RedirectCallback, void(const scoped_refptr<UrlData>&));

  void SetUrlData(const scoped_refptr<UrlData>& new_url_data) {
    url_data_ = new_url_data;
  }

 protected:
  GURL gurl_;
  int64_t first_position_;

  scoped_ptr<UrlIndex> url_index_;
  scoped_refptr<UrlData> url_data_;
  scoped_refptr<UrlData> redirected_to_;
  // The loader is owned by the UrlData above.
  ResourceMultiBufferDataProvider* loader_;
  NiceMock<MockWebURLLoader>* url_loader_;

  MockWebFrameClient client_;
  WebView* view_;
  WebLocalFrame* frame_;

  base::MessageLoop message_loop_;

  uint8_t data_[kDataSize];

 private:
  DISALLOW_COPY_AND_ASSIGN(ResourceMultiBufferDataProviderTest);
};

TEST_F(ResourceMultiBufferDataProviderTest, StartStop) {
  Initialize(kHttpUrl, 0);
  Start();
  StopWhenLoad();
}

// Tests that a bad HTTP response is recived, e.g. file not found.
TEST_F(ResourceMultiBufferDataProviderTest, BadHttpResponse) {
  Initialize(kHttpUrl, 0);
  Start();

  EXPECT_CALL(*this, RedirectCallback(scoped_refptr<UrlData>(nullptr)));

  WebURLResponse response(gurl_);
  response.setHTTPStatusCode(404);
  response.setHTTPStatusText("Not Found\n");
  loader_->didReceiveResponse(url_loader_, response);
}

// Tests that partial content is requested but not fulfilled.
TEST_F(ResourceMultiBufferDataProviderTest, NotPartialResponse) {
  Initialize(kHttpUrl, 100);
  Start();
  FullResponse(1024, false);
}

// Tests that a 200 response is received.
TEST_F(ResourceMultiBufferDataProviderTest, FullResponse) {
  Initialize(kHttpUrl, 0);
  Start();
  FullResponse(1024);
  StopWhenLoad();
}

// Tests that a partial content response is received.
TEST_F(ResourceMultiBufferDataProviderTest, PartialResponse) {
  Initialize(kHttpUrl, 100);
  Start();
  PartialResponse(100, 200, 1024);
  StopWhenLoad();
}

TEST_F(ResourceMultiBufferDataProviderTest, PartialResponse_Chunked) {
  Initialize(kHttpUrl, 100);
  Start();
  PartialResponse(100, 200, 1024, true, true);
  StopWhenLoad();
}

TEST_F(ResourceMultiBufferDataProviderTest, PartialResponse_NoAcceptRanges) {
  Initialize(kHttpUrl, 100);
  Start();
  PartialResponse(100, 200, 1024, false, false);
  StopWhenLoad();
}

TEST_F(ResourceMultiBufferDataProviderTest,
       PartialResponse_ChunkedNoAcceptRanges) {
  Initialize(kHttpUrl, 100);
  Start();
  PartialResponse(100, 200, 1024, true, false);
  StopWhenLoad();
}

// Tests that an invalid partial response is received.
TEST_F(ResourceMultiBufferDataProviderTest, InvalidPartialResponse) {
  Initialize(kHttpUrl, 0);
  Start();

  EXPECT_CALL(*this, RedirectCallback(scoped_refptr<UrlData>(nullptr)));

  WebURLResponse response(gurl_);
  response.setHTTPHeaderField(
      WebString::fromUTF8("Content-Range"),
      WebString::fromUTF8(base::StringPrintf("bytes "
                                             "%d-%d/%d",
                                             1, 10, 1024)));
  response.setExpectedContentLength(10);
  response.setHTTPStatusCode(kHttpPartialContent);
  loader_->didReceiveResponse(url_loader_, response);
}

TEST_F(ResourceMultiBufferDataProviderTest, TestRedirects) {
  // Test redirect.
  Initialize(kHttpUrl, 0);
  Start();
  Redirect(kHttpRedirect);
  FullResponse(1024);
  StopWhenLoad();
}

}  // namespace media


text:
package org.apache.phoenix.compile;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;

import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.WritableUtils;
import org.apache.phoenix.compile.GroupByCompiler.GroupBy;
import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.expression.BaseTerminalExpression;
import org.apache.phoenix.expression.CoerceExpression;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.KeyValueColumnExpression;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.expression.ProjectedColumnExpression;
import org.apache.phoenix.expression.SingleCellColumnExpression;
import org.apache.phoenix.expression.function.ArrayIndexFunction;
import org.apache.phoenix.expression.visitor.ExpressionVisitor;
import org.apache.phoenix.expression.visitor.ProjectedColumnExpressionVisitor;
import org.apache.phoenix.expression.visitor.ReplaceArrayFunctionExpressionVisitor;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.parse.AliasedNode;
import org.apache.phoenix.parse.BindParseNode;
import org.apache.phoenix.parse.ColumnParseNode;
import org.apache.phoenix.parse.FamilyWildcardParseNode;
import org.apache.phoenix.parse.FunctionParseNode;
import org.apache.phoenix.parse.ParseNode;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.parse.SequenceValueParseNode;
import org.apache.phoenix.parse.TableName;
import org.apache.phoenix.parse.TableWildcardParseNode;
import org.apache.phoenix.parse.WildcardParseNode;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.schema.AmbiguousColumnException;
import org.apache.phoenix.schema.ArgumentTypeMismatchException;
import org.apache.phoenix.schema.ColumnFamilyNotFoundException;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.ColumnRef;
import org.apache.phoenix.schema.KeyValueSchema;
import org.apache.phoenix.schema.KeyValueSchema.KeyValueSchemaBuilder;
import org.apache.phoenix.schema.LocalIndexDataColumnRef;
import org.apache.phoenix.schema.PColumn;
import org.apache.phoenix.schema.PColumnFamily;
import org.apache.phoenix.schema.PDatum;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.PTable.ImmutableStorageScheme;
import org.apache.phoenix.schema.PTable.IndexType;
import org.apache.phoenix.schema.PTableKey;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.RowKeySchema;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.ValueBitSet;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.util.ByteUtil;
import org.apache.phoenix.util.IndexUtil;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.SizedUtil;

import com.google.common.collect.Lists;

/**
 *
 * Class that iterates through expressions in SELECT clause and adds projected
 * columns to scan.
 *
 *
 * @since 0.1
 */
public class ProjectionCompiler {
    private static final Expression NULL_EXPRESSION = LiteralExpression.newConstant(null);
    private ProjectionCompiler() {
    }

    private static void projectColumnFamily(PTable table, Scan scan, byte[] family) {
        // Will project all colmuns for given CF
        scan.addFamily(family);
    }

    public static RowProjector compile(StatementContext context, SelectStatement statement, GroupBy groupBy) throws SQLException  {
        return compile(context, statement, groupBy, Collections.<PColumn>emptyList(),
                NULL_EXPRESSION// Pass null expression because we don't want empty key value to be projected
                );
    }

    private static int getMinPKOffset(PTable table, PName tenantId) {
        // In SELECT *, don't include tenant column or index ID column for tenant connection
        int posOffset = table.getBucketNum() == null ? 0 : 1;
        if (table.isMultiTenant() && tenantId != null) {
            posOffset++;
        }
        if (table.getViewIndexId() != null) {
            posOffset++;
        }
        return posOffset;
    }

    private static void projectAllTableColumns(StatementContext context, TableRef tableRef, boolean resolveColumn, List<Expression> projectedExpressions, List<ExpressionProjector> projectedColumns, List<? extends PDatum> targetColumns) throws SQLException {
        ColumnResolver resolver = context.getResolver();
        PTable table = tableRef.getTable();
        int projectedOffset = projectedExpressions.size();
        int posOffset = table.getBucketNum() == null ? 0 : 1;
        int minPKOffset = getMinPKOffset(table, context.getConnection().getTenantId());
        for (int i = posOffset, j = posOffset; i < table.getColumns().size(); i++) {
            PColumn column = table.getColumns().get(i);
            // Skip tenant ID column (which may not be the first column, but is the first PK column)
            if (SchemaUtil.isPKColumn(column) && j++ < minPKOffset) {
                posOffset++;
                continue;
            }
            ColumnRef ref = new ColumnRef(tableRef,i);
            String colName = ref.getColumn().getName().getString();
            String tableAlias = tableRef.getTableAlias();
            if (resolveColumn) {
                try {
                    if (tableAlias != null) {
                        ref = resolver.resolveColumn(null, tableAlias, colName);
                    } else {
                        String schemaName = table.getSchemaName().getString();
                        ref = resolver.resolveColumn(schemaName.length() == 0 ? null : schemaName, table.getTableName().getString(), colName);
                    }
                } catch (AmbiguousColumnException e) {
                    if (column.getFamilyName() != null) {
                        ref = resolver.resolveColumn(tableAlias != null ? tableAlias : table.getTableName().getString(), column.getFamilyName().getString(), colName);
                    } else {
                        throw e;
                    }
                }
            }
            Expression expression = ref.newColumnExpression();
            expression = coerceIfNecessary(i-posOffset+projectedOffset, targetColumns, expression);
            ImmutableBytesWritable ptr = context.getTempPtr();
            if (IndexUtil.getViewConstantValue(column, ptr)) {
                expression = LiteralExpression.newConstant(column.getDataType().toObject(ptr), expression.getDataType());
            }
            projectedExpressions.add(expression);
            boolean isCaseSensitive = !SchemaUtil.normalizeIdentifier(colName).equals(colName);
            projectedColumns.add(new ExpressionProjector(colName, tableRef.getTableAlias() == null ? table.getName().getString() : tableRef.getTableAlias(), expression, isCaseSensitive));
        }
    }

    private static void projectAllIndexColumns(StatementContext context, TableRef tableRef, boolean resolveColumn, List<Expression> projectedExpressions, List<ExpressionProjector> projectedColumns, List<? extends PDatum> targetColumns) throws SQLException {
        ColumnResolver resolver = context.getResolver();
        PTable index = tableRef.getTable();
        int projectedOffset = projectedExpressions.size();
        PhoenixConnection conn = context.getConnection();
        PName tenantId = conn.getTenantId();
        String tableName = index.getParentName().getString();
        PTable dataTable = null;
        try {
        	dataTable = conn.getTable(new PTableKey(tenantId, tableName));
        } catch (TableNotFoundException e) {
            if (tenantId != null) {
                // Check with null tenantId
            	dataTable = conn.getTable(new PTableKey(null, tableName));
            }
            else {
            	throw e;
            }
        }
        int tableOffset = dataTable.getBucketNum() == null ? 0 : 1;
        int minTablePKOffset = getMinPKOffset(dataTable, tenantId);
        int minIndexPKOffset = getMinPKOffset(index, tenantId);
        if (index.getIndexType() != IndexType.LOCAL) {
            if (index.getColumns().size()-minIndexPKOffset != dataTable.getColumns().size()-minTablePKOffset) {
                // We'll end up not using this by the optimizer, so just throw
                String schemaNameStr = dataTable.getSchemaName()==null?null:dataTable.getSchemaName().getString();
                String tableNameStr = dataTable.getTableName()==null?null:dataTable.getTableName().getString();
                throw new ColumnNotFoundException(schemaNameStr, tableNameStr,null, WildcardParseNode.INSTANCE.toString());
            }
        }
        for (int i = tableOffset, j = tableOffset; i < dataTable.getColumns().size(); i++) {
            PColumn column = dataTable.getColumns().get(i);
            // Skip tenant ID column (which may not be the first column, but is the first PK column)
            if (SchemaUtil.isPKColumn(column) && j++ < minTablePKOffset) {
                tableOffset++;
                continue;
            }
            PColumn tableColumn = dataTable.getColumns().get(i);
            String indexColName = IndexUtil.getIndexColumnName(tableColumn);
            PColumn indexColumn = null;
            ColumnRef ref = null;
            try {
                indexColumn = index.getColumnForColumnName(indexColName);
                ref = new ColumnRef(tableRef, indexColumn.getPosition());
            } catch (ColumnNotFoundException e) {
                if (index.getIndexType() == IndexType.LOCAL) {
                    try {
                        ref = new LocalIndexDataColumnRef(context, indexColName);
                        indexColumn = ref.getColumn();
                    } catch (ColumnFamilyNotFoundException c) {
                        throw e;
                    }
                } else {
                    throw e;
                }
            }
            String colName = tableColumn.getName().getString();
            String tableAlias = tableRef.getTableAlias();
            if (resolveColumn) {
                try {
                    if (tableAlias != null) {
                        ref = resolver.resolveColumn(null, tableAlias, indexColName);
                    } else {
                        String schemaName = index.getSchemaName().getString();
                        ref = resolver.resolveColumn(schemaName.length() == 0 ? null : schemaName, index.getTableName().getString(), indexColName);
                    }
                } catch (AmbiguousColumnException e) {
                    if (indexColumn.getFamilyName() != null) {
                        ref = resolver.resolveColumn(tableAlias != null ? tableAlias : index.getTableName().getString(), indexColumn.getFamilyName().getString(), indexColName);
                    } else {
                        throw e;
                    }
                }
            }
            Expression expression = ref.newColumnExpression();
            expression = coerceIfNecessary(i-tableOffset+projectedOffset, targetColumns, expression);
            // We do not need to check if the column is a viewConstant, because view constants never
            // appear as a column in an index
            projectedExpressions.add(expression);
            boolean isCaseSensitive = !SchemaUtil.normalizeIdentifier(colName).equals(colName);
            ExpressionProjector projector = new ExpressionProjector(colName, tableRef.getTableAlias() == null ? dataTable.getName().getString() : tableRef.getTableAlias(), expression, isCaseSensitive);
            projectedColumns.add(projector);
        }
    }

    private static void projectTableColumnFamily(StatementContext context, String cfName, TableRef tableRef, boolean resolveColumn, List<Expression> projectedExpressions, List<ExpressionProjector> projectedColumns) throws SQLException {
        PTable table = tableRef.getTable();
        PColumnFamily pfamily = table.getColumnFamily(cfName);
        for (PColumn column : pfamily.getColumns()) {
            ColumnRef ref = new ColumnRef(tableRef, column.getPosition());
            if (resolveColumn) {
                ref = context.getResolver().resolveColumn(table.getTableName().getString(), cfName, column.getName().getString());
            }
            Expression expression = ref.newColumnExpression();
            projectedExpressions.add(expression);
            String colName = column.getName().toString();
            boolean isCaseSensitive = !SchemaUtil.normalizeIdentifier(colName).equals(colName);
            projectedColumns.add(new ExpressionProjector(colName, tableRef.getTableAlias() == null ?
                    table.getName().getString() : tableRef.getTableAlias(), expression, isCaseSensitive));
        }
    }

    private static void projectIndexColumnFamily(StatementContext context, String cfName, TableRef tableRef, boolean resolveColumn, List<Expression> projectedExpressions, List<ExpressionProjector> projectedColumns) throws SQLException {
        PTable index = tableRef.getTable();
        PhoenixConnection conn = context.getConnection();
        String tableName = index.getParentName().getString();
        PTable table = conn.getTable(new PTableKey(conn.getTenantId(), tableName));
        PColumnFamily pfamily = table.getColumnFamily(cfName);
        for (PColumn column : pfamily.getColumns()) {
            String indexColName = IndexUtil.getIndexColumnName(column);
            PColumn indexColumn = null;
            ColumnRef ref = null;
            String indexColumnFamily = null;
            try {
                indexColumn = index.getColumnForColumnName(indexColName);
                ref = new ColumnRef(tableRef, indexColumn.getPosition());
                indexColumnFamily = indexColumn.getFamilyName() == null ? null : indexColumn.getFamilyName().getString();
            } catch (ColumnNotFoundException e) {
                if (index.getIndexType() == IndexType.LOCAL) {
                    try {
                        ref = new LocalIndexDataColumnRef(context, indexColName);
                        indexColumn = ref.getColumn();
                        indexColumnFamily =
                                indexColumn.getFamilyName() == null ? null
                                        : (index.getIndexType() == IndexType.LOCAL ? IndexUtil
                                                .getLocalIndexColumnFamily(indexColumn
                                                        .getFamilyName().getString()) : indexColumn
                                                .getFamilyName().getString());
                    } catch (ColumnFamilyNotFoundException c) {
                        throw e;
                    }
                } else {
                    throw e;
                }
            }
            if (resolveColumn) {
                ref = context.getResolver().resolveColumn(index.getTableName().getString(), indexColumnFamily, indexColName);
            }
            Expression expression = ref.newColumnExpression();
            projectedExpressions.add(expression);
            String colName = column.getName().toString();
            boolean isCaseSensitive = !SchemaUtil.normalizeIdentifier(colName).equals(colName);
            projectedColumns.add(new ExpressionProjector(colName,
                    tableRef.getTableAlias() == null ? table.getName().getString() : tableRef.getTableAlias(), expression, isCaseSensitive));
        }
    }

    private static Expression coerceIfNecessary(int index, List<? extends PDatum> targetColumns, Expression expression) throws SQLException {
        if (index < targetColumns.size()) {
            PDatum targetColumn = targetColumns.get(index);
            if (targetColumn.getDataType() != expression.getDataType()) {
                PDataType targetType = targetColumn.getDataType();
                // Check if coerce allowed using more relaxed isCastableTo check, since we promote INTEGER to LONG
                // during expression evaluation and then convert back to INTEGER on UPSERT SELECT (and we don't have
                // (an actual value we can specifically check against).
                if (expression.getDataType() != null && !expression.getDataType().isCastableTo(targetType)) {
                    throw new ArgumentTypeMismatchException(targetType, expression.getDataType(), "column: " + targetColumn);
                }
                expression = CoerceExpression.create(expression, targetType, targetColumn.getSortOrder(), targetColumn.getMaxLength());
            }
        }
        return expression;
    }
    /**
     * Builds the projection for the scan
     * @param context query context kept between compilation of different query clauses
     * @param statement TODO
     * @param groupBy compiled GROUP BY clause
     * @param targetColumns list of columns, parallel to aliasedNodes, that are being set for an
     * UPSERT SELECT statement. Used to coerce expression types to the expected target type.
     * @return projector used to access row values during scan
     * @throws SQLException
     */
    public static RowProjector compile(StatementContext context, SelectStatement statement, GroupBy groupBy, List<? extends PDatum> targetColumns, Expression where) throws SQLException {
        List<KeyValueColumnExpression> arrayKVRefs = new ArrayList<KeyValueColumnExpression>();
        List<ProjectedColumnExpression> arrayProjectedColumnRefs = new ArrayList<ProjectedColumnExpression>();
        List<Expression> arrayKVFuncs = new ArrayList<Expression>();
        List<Expression> arrayOldFuncs = new ArrayList<Expression>();
        Map<Expression, Integer> arrayExpressionCounts = new HashMap<>();
        List<AliasedNode> aliasedNodes = statement.getSelect();
        // Setup projected columns in Scan
        SelectClauseVisitor selectVisitor = new SelectClauseVisitor(context, groupBy, arrayKVRefs, arrayKVFuncs, arrayExpressionCounts, arrayProjectedColumnRefs, arrayOldFuncs, statement);
        List<ExpressionProjector> projectedColumns = new ArrayList<ExpressionProjector>();
        ColumnResolver resolver = context.getResolver();
        TableRef tableRef = context.getCurrentTable();
        PTable table = tableRef.getTable();
        boolean resolveColumn = !tableRef.equals(resolver.getTables().get(0));
        boolean isWildcard = false;
        Scan scan = context.getScan();
        int index = 0;
        List<Expression> projectedExpressions = Lists.newArrayListWithExpectedSize(aliasedNodes.size());
        List<byte[]> projectedFamilies = Lists.newArrayListWithExpectedSize(aliasedNodes.size());
        for (AliasedNode aliasedNode : aliasedNodes) {
            ParseNode node = aliasedNode.getNode();
            // TODO: visitor?
            if (node instanceof WildcardParseNode) {
                if (statement.isAggregate()) {
                    ExpressionCompiler.throwNonAggExpressionInAggException(node.toString());
                }
                if (tableRef == TableRef.EMPTY_TABLE_REF) {
                    throw new SQLExceptionInfo.Builder(SQLExceptionCode.NO_TABLE_SPECIFIED_FOR_WILDCARD_SELECT).build().buildException();
                }
                isWildcard = true;
                if (tableRef.getTable().getType() == PTableType.INDEX && ((WildcardParseNode)node).isRewrite()) {
                	projectAllIndexColumns(context, tableRef, resolveColumn, projectedExpressions, projectedColumns, targetColumns);
                } else {
                    projectAllTableColumns(context, tableRef, resolveColumn, projectedExpressions, projectedColumns, targetColumns);
                }
            } else if (node instanceof TableWildcardParseNode) {
                TableName tName = ((TableWildcardParseNode) node).getTableName();
                TableRef tRef = resolver.resolveTable(tName.getSchemaName(), tName.getTableName());
                if (tRef.equals(tableRef)) {
                    isWildcard = true;
                }
                if (tRef.getTable().getType() == PTableType.INDEX && ((TableWildcardParseNode)node).isRewrite()) {
                    projectAllIndexColumns(context, tRef, true, projectedExpressions, projectedColumns, targetColumns);
                } else {
                    projectAllTableColumns(context, tRef, true, projectedExpressions, projectedColumns, targetColumns);
                }
            } else if (node instanceof  FamilyWildcardParseNode) {
                if (tableRef == TableRef.EMPTY_TABLE_REF) {
                    throw new SQLExceptionInfo.Builder(SQLExceptionCode.NO_TABLE_SPECIFIED_FOR_WILDCARD_SELECT).build().buildException();
                }
                // Project everything for SELECT cf.*
                String cfName = ((FamilyWildcardParseNode) node).getName();
                // Delay projecting to scan, as when any other column in the column family gets
                // added to the scan, it overwrites that we want to project the entire column
                // family. Instead, we do the projection at the end.
                // TODO: consider having a ScanUtil.addColumn and ScanUtil.addFamily to work
                // around this, as this code depends on this function being the last place where
                // columns are projected (which is currently true, but could change).
                projectedFamilies.add(Bytes.toBytes(cfName));
                if (tableRef.getTable().getType() == PTableType.INDEX && ((FamilyWildcardParseNode)node).isRewrite()) {
                    projectIndexColumnFamily(context, cfName, tableRef, resolveColumn, projectedExpressions, projectedColumns);
                } else {
                    projectTableColumnFamily(context, cfName, tableRef, resolveColumn, projectedExpressions, projectedColumns);
                }
            } else {
                Expression expression = node.accept(selectVisitor);
                projectedExpressions.add(expression);
                expression = coerceIfNecessary(index, targetColumns, expression);
                if (node instanceof BindParseNode) {
                    context.getBindManager().addParamMetaData((BindParseNode)node, expression);
                }
                if (!node.isStateless()) {
                    if (!selectVisitor.isAggregate() && statement.isAggregate()) {
                        ExpressionCompiler.throwNonAggExpressionInAggException(expression.toString());
                    }
                }
                String columnAlias = aliasedNode.getAlias() != null ? aliasedNode.getAlias() : SchemaUtil.normalizeIdentifier(aliasedNode.getNode().getAlias());
                boolean isCaseSensitive = aliasedNode.getAlias() != null ? aliasedNode.isCaseSensitve() : (columnAlias != null ? SchemaUtil.isCaseSensitive(aliasedNode.getNode().getAlias()) : selectVisitor.isCaseSensitive);
                String name = columnAlias == null ? expression.toString() : columnAlias;
                projectedColumns.add(new ExpressionProjector(name, tableRef.getTableAlias() == null ? (table.getName() == null ? "" : table.getName().getString()) : tableRef.getTableAlias(), expression, isCaseSensitive));
            }

            selectVisitor.reset();
            index++;
        }

        for (int i = arrayProjectedColumnRefs.size() - 1; i >= 0; i--) {
            Expression expression = arrayProjectedColumnRefs.get(i);
            Integer count = arrayExpressionCounts.get(expression);
            if (count != 0) {
                arrayKVRefs.remove(i);
                arrayKVFuncs.remove(i);
                arrayOldFuncs.remove(i);
            }
        }

        if (arrayKVFuncs.size() > 0 && arrayKVRefs.size() > 0) {
            serailizeArrayIndexInformationAndSetInScan(context, arrayKVFuncs, arrayKVRefs);
            KeyValueSchemaBuilder builder = new KeyValueSchemaBuilder(0);
            for (Expression expression : arrayKVRefs) {
                builder.addField(expression);
            }
            KeyValueSchema kvSchema = builder.build();
            ValueBitSet arrayIndexesBitSet = ValueBitSet.newInstance(kvSchema);
            builder = new KeyValueSchemaBuilder(0);
            for (Expression expression : arrayKVFuncs) {
                builder.addField(expression);
            }
            KeyValueSchema arrayIndexesSchema = builder.build();

            Map<Expression, Expression> replacementMap = new HashMap<>();
            for(int i = 0; i < arrayOldFuncs.size(); i++){
                Expression function =arrayKVFuncs.get(i);
                replacementMap.put(arrayOldFuncs.get(i), new ArrayIndexExpression(i, function.getDataType(), arrayIndexesBitSet, arrayIndexesSchema));
            }

            ReplaceArrayFunctionExpressionVisitor visitor = new ReplaceArrayFunctionExpressionVisitor(replacementMap);
            for (int i = 0; i < projectedColumns.size(); i++) {
                ExpressionProjector projector = projectedColumns.get(i);
                projectedColumns.set(i, new ExpressionProjector(projector.getName(), tableRef.getTableAlias() == null ? (table.getName() == null ? "" : table.getName().getString()) : tableRef.getTableAlias(), projector.getExpression().accept(visitor), projector.isCaseSensitive()));
            }
        }

        boolean isProjectEmptyKeyValue = false;
        if (isWildcard) {
            projectAllColumnFamilies(table, scan);
        } else {
            isProjectEmptyKeyValue = where == null || LiteralExpression.isTrue(where) || where.requiresFinalEvaluation();
            for (byte[] family : projectedFamilies) {
                projectColumnFamily(table, scan, family);
            }
        }

        // TODO make estimatedByteSize more accurate by counting the joined columns.
        int estimatedKeySize = table.getRowKeySchema().getEstimatedValueLength();
        int estimatedByteSize = 0;
        for (Map.Entry<byte[],NavigableSet<byte[]>> entry : scan.getFamilyMap().entrySet()) {
            try {
                PColumnFamily family = table.getColumnFamily(entry.getKey());
                if (entry.getValue() == null) {
                    for (PColumn column : family.getColumns()) {
                        Integer maxLength = column.getMaxLength();
                        int byteSize = column.getDataType().isFixedWidth() ? maxLength == null ? column.getDataType().getByteSize() : maxLength : RowKeySchema.ESTIMATED_VARIABLE_LENGTH_SIZE;
                        estimatedByteSize += SizedUtil.KEY_VALUE_SIZE + estimatedKeySize + byteSize;
                    }
                } else {
                    for (byte[] cq : entry.getValue()) {
                            PColumn column = family.getPColumnForColumnQualifier(cq);
                            Integer maxLength = column.getMaxLength();
                            int byteSize = column.getDataType().isFixedWidth() ? maxLength == null ? column.getDataType().getByteSize() : maxLength : RowKeySchema.ESTIMATED_VARIABLE_LENGTH_SIZE;
                            estimatedByteSize += SizedUtil.KEY_VALUE_SIZE + estimatedKeySize + byteSize;
                        }
                }
            } catch (ColumnFamilyNotFoundException e) {
                // Ignore as this can happen for local indexes when the data table has a column family, but there are no covered columns in the family
            }
        }
        return new RowProjector(projectedColumns, Math.max(estimatedKeySize, estimatedByteSize), isProjectEmptyKeyValue, resolver.hasUDFs(), isWildcard);
    }

    private static void projectAllColumnFamilies(PTable table, Scan scan) {
        // Will project all known/declared column families
        scan.getFamilyMap().clear();
        for (PColumnFamily family : table.getColumnFamilies()) {
            scan.addFamily(family.getName().getBytes());
        }
    }

    // A replaced ArrayIndex function that retrieves the exact array value retrieved from the server
    static class ArrayIndexExpression extends BaseTerminalExpression {
        private final int position;
        private final PDataType type;
        private final ValueBitSet arrayIndexesBitSet;
        private final KeyValueSchema arrayIndexesSchema;

        public ArrayIndexExpression(int position, PDataType type, ValueBitSet arrayIndexesBitSet, KeyValueSchema arrayIndexesSchema) {
            this.position = position;
            this.type =  type;
            this.arrayIndexesBitSet = arrayIndexesBitSet;
            this.arrayIndexesSchema = arrayIndexesSchema;
        }

        @Override
        public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
            if (!tuple.getValue(QueryConstants.ARRAY_VALUE_COLUMN_FAMILY, QueryConstants.ARRAY_VALUE_COLUMN_QUALIFIER,
                    ptr)) {
              return false;
            }
            int maxOffset = ptr.getOffset() + ptr.getLength();
            arrayIndexesBitSet.or(ptr);
            arrayIndexesSchema.iterator(ptr, position, arrayIndexesBitSet);
            Boolean hasValue = arrayIndexesSchema.next(ptr, position, maxOffset, arrayIndexesBitSet);
            arrayIndexesBitSet.clear();
            if (hasValue == null) {
                ptr.set(ByteUtil.EMPTY_BYTE_ARRAY);
            }
            return true;
        }

        @Override
        public PDataType getDataType() {
            return this.type;
        }

        @Override
        public <T> T accept(ExpressionVisitor<T> visitor) {
            // TODO Auto-generated method stub
            return null;
        }
    }
    private static void serailizeArrayIndexInformationAndSetInScan(StatementContext context, List<Expression> arrayKVFuncs,
            List<KeyValueColumnExpression> arrayKVRefs) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            DataOutputStream output = new DataOutputStream(stream);
            // Write the arrayKVRef size followed by the keyvalues that needs to be of type arrayindex function
            WritableUtils.writeVInt(output, arrayKVRefs.size());
            for (Expression expression : arrayKVRefs) {
                    expression.write(output);
            }
            // then write the number of arrayindex functions followeed by the expression itself
            WritableUtils.writeVInt(output, arrayKVFuncs.size());
            for (Expression expression : arrayKVFuncs) {
                    expression.write(output);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        context.getScan().setAttribute(BaseScannerRegionObserver.SPECIFIC_ARRAY_INDEX, stream.toByteArray());
    }

    private static class SelectClauseVisitor extends ExpressionCompiler {

        /**
         * Track whether or not the projection expression is case sensitive. We use this
         * information to determine whether or not we normalize the column name passed
         */
        private boolean isCaseSensitive;
        private int elementCount;
        private List<KeyValueColumnExpression> arrayKVRefs;
        private List<Expression> arrayKVFuncs;
        private List<Expression> arrayOldFuncs;
        private List<ProjectedColumnExpression> arrayProjectedColumnRefs;
        private Map<Expression, Integer> arrayExpressionCounts;
        private SelectStatement statement;

        private SelectClauseVisitor(StatementContext context, GroupBy groupBy,
                List<KeyValueColumnExpression> arrayKVRefs, List<Expression> arrayKVFuncs, Map<Expression, Integer> arrayExpressionCounts, List<ProjectedColumnExpression> arrayProjectedColumnRefs, List<Expression> arrayOldFuncs, SelectStatement statement) {
            super(context, groupBy);
            this.arrayKVRefs = arrayKVRefs;
            this.arrayKVFuncs = arrayKVFuncs;
            this.arrayOldFuncs = arrayOldFuncs;
            this.arrayExpressionCounts = arrayExpressionCounts;
            this.arrayProjectedColumnRefs = arrayProjectedColumnRefs;
            this.statement = statement;
            reset();
        }

        @Override
        public void reset() {
            super.reset();
            elementCount = 0;
            isCaseSensitive = true;
        }

        @Override
        protected ColumnRef resolveColumn(ColumnParseNode node) throws SQLException {
            ColumnRef ref = super.resolveColumn(node);
            isCaseSensitive = isCaseSensitive && node.isCaseSensitive();
            return ref;
        }

        @Override
        public Expression visit(ColumnParseNode node) throws SQLException {
            Expression expression = super.visit(node);
            if (expression.getDataType().isArrayType()) {
                Integer count = arrayExpressionCounts.get(expression);
                arrayExpressionCounts.put(expression, count != null ? (count + 1) : 1);
            }
            return expression;
        }

        @Override
        public void addElement(List<Expression> l, Expression element) {
            elementCount++;
            isCaseSensitive &= elementCount == 1;
            super.addElement(l, element);
        }

        @Override
        public Expression visit(SequenceValueParseNode node) throws SQLException {
            if (aggregateFunction != null) {
                throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_USE_OF_NEXT_VALUE_FOR)
                .setSchemaName(node.getTableName().getSchemaName())
                .setTableName(node.getTableName().getTableName()).build().buildException();
            }
            return context.getSequenceManager().newSequenceReference(node);
        }

        @Override
        public Expression visitLeave(FunctionParseNode node, final List<Expression> children) throws SQLException {

            // this need not be done for group by clause with array. Hence the below check
            if (!statement.isAggregate() && ArrayIndexFunction.NAME.equals(node.getName()) && children.get(0) instanceof ProjectedColumnExpression) {
                 final List<KeyValueColumnExpression> indexKVs = Lists.newArrayList();
                 final List<ProjectedColumnExpression> indexProjectedColumns = Lists.newArrayList();
                 final List<Expression> copyOfChildren = new ArrayList<>(children);
                 // Create anon visitor to find reference to array in a generic way
                 children.get(0).accept(new ProjectedColumnExpressionVisitor() {
                     @Override
                     public Void visit(ProjectedColumnExpression expression) {
                         if (expression.getDataType().isArrayType()) {
                             indexProjectedColumns.add(expression);
                             PColumn col = expression.getColumn();
                             PTable table = context.getCurrentTable().getTable();
                             KeyValueColumnExpression keyValueColumnExpression;
                             if (table.getImmutableStorageScheme() != ImmutableStorageScheme.ONE_CELL_PER_COLUMN) {
                                keyValueColumnExpression =
                                        new SingleCellColumnExpression(col,
                                                col.getName().getString(),
                                                table.getEncodingScheme(),
                                                table.getImmutableStorageScheme());
                             } else {
                                 keyValueColumnExpression = new KeyValueColumnExpression(col);
                             }
                             indexKVs.add(keyValueColumnExpression);
                             copyOfChildren.set(0, keyValueColumnExpression);
                             Integer count = arrayExpressionCounts.get(expression);
                             arrayExpressionCounts.put(expression, count != null ? (count - 1) : -1);
                         }
                         return null;
                     }
                 });

                 Expression func = super.visitLeave(node,children);
                 // Add the keyvalues which is of type array
                 if (!indexKVs.isEmpty()) {
                    arrayKVRefs.addAll(indexKVs);
                    arrayProjectedColumnRefs.addAll(indexProjectedColumns);
                    Expression funcModified = super.visitLeave(node, copyOfChildren);
                    // Track the array index function also
                    arrayKVFuncs.add(funcModified);
                    arrayOldFuncs.add(func);
                }
                return func;
            } else {
                return super.visitLeave(node,children);
            }
        }
    }
}


text:
<?php
return [
    'plugin' => [
        'name'          => 'Cancellare la Cache',
        'description'   => 'Widget di Dashboard',
        'cache'         => 'File di cache',
        'clear'         => 'Cancellare la cache',
        'success'       => 'La Cache è stato svuotato!',
        'nochart'       => 'Nascondi grafica',
        'radius'        => 'Tabella di grafica',
        'delthumbs'     => 'Cancella l\'anteprima?',
        'delthumbspath' => 'Via di accesso l\'anteprima archivio',
        'thumbs_regex'  => 'L\'espressione regolare per i nomi di file di anteprima',
    ],
];


text:
package com.navercorp.pinpoint.collector.receiver.grpc.service;

import com.google.protobuf.Empty;
import com.google.protobuf.GeneratedMessageV3;
import com.navercorp.pinpoint.collector.receiver.DispatchHandler;
import com.navercorp.pinpoint.grpc.MessageFormatUtils;
import com.navercorp.pinpoint.grpc.StatusError;
import com.navercorp.pinpoint.grpc.StatusErrors;
import com.navercorp.pinpoint.grpc.trace.PSpan;
import com.navercorp.pinpoint.grpc.trace.PSpanChunk;
import com.navercorp.pinpoint.grpc.trace.PSpanMessage;
import com.navercorp.pinpoint.grpc.trace.SpanGrpc;
import com.navercorp.pinpoint.io.header.Header;
import com.navercorp.pinpoint.io.header.HeaderEntity;
import com.navercorp.pinpoint.io.header.v2.HeaderV2;
import com.navercorp.pinpoint.io.request.DefaultMessage;
import com.navercorp.pinpoint.io.request.Message;
import com.navercorp.pinpoint.io.request.ServerRequest;
import com.navercorp.pinpoint.thrift.io.DefaultTBaseLocator;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author jaehong.kim
 */
public class SpanService extends SpanGrpc.SpanImplBase {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();
    private final DispatchHandler dispatchHandler;
    private final ServerRequestFactory serverRequestFactory = new ServerRequestFactory();

    public SpanService(DispatchHandler dispatchHandler) {
        this.dispatchHandler = Objects.requireNonNull(dispatchHandler, "dispatchHandler");
    }

    @Override
    public StreamObserver<PSpanMessage> sendSpan(final StreamObserver<Empty> responseObserver) {
        StreamObserver<PSpanMessage> observer = new StreamObserver<PSpanMessage>() {
            @Override
            public void onNext(PSpanMessage spanMessage) {
                if (isDebug) {
                    logger.debug("Send PSpan={}", MessageFormatUtils.debugLog(spanMessage));
                }

                if (spanMessage.hasSpan()) {
                    final Message<PSpan> message = newMessage(spanMessage.getSpan(), DefaultTBaseLocator.SPAN);
                    send(message, responseObserver);
                } else if (spanMessage.hasSpanChunk()) {
                    final Message<PSpanChunk> message = newMessage(spanMessage.getSpanChunk(), DefaultTBaseLocator.SPANCHUNK);
                    send(message, responseObserver);
                } else {
                    if (isDebug) {
                        logger.debug("Found empty span message {}", MessageFormatUtils.debugLog(spanMessage));
                    }
                }
            }

            @Override
            public void onError(Throwable throwable) {
                final StatusError statusError = StatusErrors.throwable(throwable);
                if (statusError.isSimpleError()) {
                    logger.info("Failed to span stream, cause={}", statusError.getMessage());
                } else {
                    logger.warn("Failed to span stream, cause={}", statusError.getMessage(), statusError.getThrowable());
                }
            }

            @Override
            public void onCompleted() {
                Empty empty = Empty.newBuilder().build();
                responseObserver.onNext(empty);
                responseObserver.onCompleted();
            }
        };
        return observer;
    }

    private <T> Message<T> newMessage(T requestData, short serviceType) {
        final Header header = new HeaderV2(Header.SIGNATURE, HeaderV2.VERSION, serviceType);
        final HeaderEntity headerEntity = new HeaderEntity(new HashMap<>());
        return new DefaultMessage<>(header, headerEntity, requestData);
    }

    private void send(final Message<? extends GeneratedMessageV3> message, StreamObserver<Empty> responseObserver) {
        try {
            ServerRequest<? extends GeneratedMessageV3> request = serverRequestFactory.newServerRequest(message);
            this.dispatchHandler.dispatchSendMessage(request);
        } catch (Exception e) {
            logger.warn("Failed to request. message={}", message, e);
            if (e instanceof StatusException || e instanceof StatusRuntimeException) {
                responseObserver.onError(e);
            } else {
                // Avoid detailed exception
                responseObserver.onError(Status.INTERNAL.withDescription("Bad Request").asException());
            }
        }
    }

}


text:
stratanalyzer -- Strategy analyzers
===================================

Strategy analyzers provide an extensible way to attach different calculations to strategy executions.

.. automodule:: pyalgotrade.stratanalyzer
    :members: StrategyAnalyzer
    :show-inheritance:

Returns
-------
.. automodule:: pyalgotrade.stratanalyzer.returns
    :members: Returns
    :show-inheritance:

Sharpe Ratio
------------
.. automodule:: pyalgotrade.stratanalyzer.sharpe
    :members: SharpeRatio
    :show-inheritance:

DrawDown
--------
.. automodule:: pyalgotrade.stratanalyzer.drawdown
    :members: DrawDown
    :show-inheritance:

Trades
------
.. automodule:: pyalgotrade.stratanalyzer.trades
    :members: Trades
    :member-order: bysource
    :show-inheritance:

Example
-------
Save this code as sma_crossover.py:

.. literalinclude:: ../samples/sma_crossover.py

and save this code in a different file:

.. literalinclude:: ../samples/sample-strategy-analyzer.py

The output should look like this:

.. literalinclude:: ../samples/sample-strategy-analyzer.output


text:
<?php

class CollectionNestedPropertyHasOneValueConstraint extends PHPUnit_Framework_Constraint
{
    /**
     * @var mixed
     */
    protected $expected;

    public function __construct($expected, $mainProperty, $secondaryProperty)
    {
        parent::__construct();

        $this->expected = is_array($expected) ? $expected : [$expected];
        $this->mainProperty = $mainProperty;
        $this->secondaryProperty = $secondaryProperty;
    }

    public function matches($input)
    {
        foreach ($input as $row) {
            if (! in_array($row->{$this->mainProperty}->{$this->secondaryProperty}, $this->expected)) {
                return false;
            }
        }

        return true;
    }

    public function toString()
    {
        return sprintf('%s.%s does not have the value %s', $this->mainProperty, $this->secondaryProperty, json_encode($this->expected));
    }
}


text:
package cherry.foundation.type.db.query;

import static com.mysema.query.types.PathMetadataFactory.*;

import com.mysema.query.types.path.*;

import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;

import com.mysema.query.sql.ColumnMetadata;
import java.sql.Types;

/**
 * QConversionTest is a Querydsl query type for BConversionTest
 */
@Generated("com.mysema.query.sql.codegen.MetaDataSerializer")
public class QConversionTest extends com.mysema.query.sql.RelationalPathBase<BConversionTest> {

    private static final long serialVersionUID = 480845314;

    public static final QConversionTest conversionTest = new QConversionTest("CONVERSION_TEST");

    public final NumberPath<Integer> deletedFlg = createNumber("deletedFlg", Integer.class);

    public final NumberPath<Integer> flagCode = createNumber("flagCode", Integer.class);

    public final NumberPath<Integer> id = createNumber("id", Integer.class);

    public final DatePath<org.joda.time.LocalDate> jodaDate = createDate("jodaDate", org.joda.time.LocalDate.class);

    public final DateTimePath<org.joda.time.LocalDateTime> jodaDatetime = createDateTime("jodaDatetime", org.joda.time.LocalDateTime.class);

    public final TimePath<org.joda.time.LocalTime> jodaTime = createTime("jodaTime", org.joda.time.LocalTime.class);

    public final StringPath secBigdec = createString("secBigdec");

    public final StringPath secBigint = createString("secBigint");

    public final StringPath secInt = createString("secInt");

    public final StringPath secLong = createString("secLong");

    public final StringPath secStr = createString("secStr");

    public QConversionTest(String variable) {
        super(BConversionTest.class, forVariable(variable), "PUBLIC", "CONVERSION_TEST");
        addMetadata();
    }

    public QConversionTest(String variable, String schema, String table) {
        super(BConversionTest.class, forVariable(variable), schema, table);
        addMetadata();
    }

    public QConversionTest(Path<? extends BConversionTest> path) {
        super(path.getType(), path.getMetadata(), "PUBLIC", "CONVERSION_TEST");
        addMetadata();
    }

    public QConversionTest(PathMetadata<?> metadata) {
        super(BConversionTest.class, metadata, "PUBLIC", "CONVERSION_TEST");
        addMetadata();
    }

    public void addMetadata() {
        addMetadata(deletedFlg, ColumnMetadata.named("DELETED_FLG").withIndex(11).ofType(Types.INTEGER).withSize(10));
        addMetadata(flagCode, ColumnMetadata.named("FLAG_CODE").withIndex(10).ofType(Types.INTEGER).withSize(10));
        addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.INTEGER).withSize(10).notNull());
        addMetadata(jodaDate, ColumnMetadata.named("JODA_DATE").withIndex(2).ofType(Types.DATE).withSize(8));
        addMetadata(jodaDatetime, ColumnMetadata.named("JODA_DATETIME").withIndex(4).ofType(Types.TIMESTAMP).withSize(23).withDigits(10));
        addMetadata(jodaTime, ColumnMetadata.named("JODA_TIME").withIndex(3).ofType(Types.TIME).withSize(6));
        addMetadata(secBigdec, ColumnMetadata.named("SEC_BIGDEC").withIndex(9).ofType(Types.VARCHAR).withSize(104));
        addMetadata(secBigint, ColumnMetadata.named("SEC_BIGINT").withIndex(8).ofType(Types.VARCHAR).withSize(104));
        addMetadata(secInt, ColumnMetadata.named("SEC_INT").withIndex(6).ofType(Types.VARCHAR).withSize(40));
        addMetadata(secLong, ColumnMetadata.named("SEC_LONG").withIndex(7).ofType(Types.VARCHAR).withSize(40));
        addMetadata(secStr, ColumnMetadata.named("SEC_STR").withIndex(5).ofType(Types.VARCHAR).withSize(104));
    }

}


text:
import argparse
import base64
import io

import googleapiclient.discovery

# [START kms_create_keyring]
def create_key_ring(project_id, location_id, key_ring_id):
    """Creates a KeyRing in the given location (e.g. global)."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the location associated with the KeyRing.
    parent = 'projects/{}/locations/{}'.format(project_id, location_id)

    # Create KeyRing
    request = kms_client.projects().locations().keyRings().create(
        parent=parent, body={}, keyRingId=key_ring_id)
    response = request.execute()

    print('Created KeyRing {}.'.format(response['name']))
# [END kms_create_keyring]

# [START kms_create_cryptokey]
def create_crypto_key(project_id, location_id, key_ring_id, crypto_key_id):
    """Creates a CryptoKey within a KeyRing in the given location."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the KeyRing associated with the CryptoKey.
    parent = 'projects/{}/locations/{}/keyRings/{}'.format(
        project_id, location_id, key_ring_id)

    # Create a CryptoKey for the given KeyRing.
    request = kms_client.projects().locations().keyRings().cryptoKeys().create(
        parent=parent, body={'purpose': 'ENCRYPT_DECRYPT'},
        cryptoKeyId=crypto_key_id)
    response = request.execute()

    print('Created CryptoKey {}.'.format(response['name']))
# [END kms_create_cryptokey]

# [START kms_encrypt]
def encrypt(project_id, location_id, key_ring_id, crypto_key_id,
            plaintext_file_name, ciphertext_file_name):
    """Encrypts data from plaintext_file_name using the provided CryptoKey and
    saves it to ciphertext_file_name so it can only be recovered with a call to
    decrypt.
    """

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Read data from the input file.
    with io.open(plaintext_file_name, 'rb') as plaintext_file:
        plaintext = plaintext_file.read()

    # Use the KMS API to encrypt the data.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.encrypt(
        name=name,
        body={'plaintext': base64.b64encode(plaintext).decode('ascii')})
    response = request.execute()
    ciphertext = base64.b64decode(response['ciphertext'].encode('ascii'))

    # Write the encrypted data to a file.
    with io.open(ciphertext_file_name, 'wb') as ciphertext_file:
        ciphertext_file.write(ciphertext)

    print('Saved ciphertext to {}.'.format(ciphertext_file_name))
# [END kms_encrypt]

# [START kms_decrypt]
def decrypt(project_id, location_id, key_ring_id, crypto_key_id,
            ciphertext_file_name, plaintext_file_name):
    """Decrypts data from ciphertext_file_name that was previously encrypted
    using the provided CryptoKey and saves it to plaintext_file_name."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Read encrypted data from the input file.
    with io.open(ciphertext_file_name, 'rb') as ciphertext_file:
        ciphertext = ciphertext_file.read()

    # Use the KMS API to decrypt the data.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.decrypt(
        name=name,
        body={'ciphertext': base64.b64encode(ciphertext).decode('ascii')})
    response = request.execute()
    plaintext = base64.b64decode(response['plaintext'].encode('ascii'))

    # Write the decrypted data to a file.
    with io.open(plaintext_file_name, 'wb') as plaintext_file:
        plaintext_file.write(plaintext)

    print('Saved plaintext to {}.'.format(plaintext_file_name))
# [END kms_decrypt]

# [START kms_disable_cryptokey_version]
def disable_crypto_key_version(project_id, location_id, key_ring_id,
                               crypto_key_id, version_id):
    """Disables a CryptoKeyVersion associated with a given CryptoKey and
    KeyRing."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # Construct the resource name of the CryptoKeyVersion.
    name = (
        'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/'
        'cryptoKeyVersions/{}'
        .format(
            project_id, location_id, key_ring_id, crypto_key_id, version_id))

    # Use the KMS API to disable the CryptoKeyVersion.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().patch(
        name=name, body={'state': 'DISABLED'}, updateMask='state')
    response = request.execute()

    print('CryptoKeyVersion {}\'s state has been set to {}.'.format(
        name, response['state']))
# [END kms_disable_cryptokey_version]

# [START kms_destroy_cryptokey_version]
def destroy_crypto_key_version(
        project_id, location_id, key_ring_id, crypto_key_id, version_id):
    """Schedules a CryptoKeyVersion associated with a given CryptoKey and
    KeyRing for destruction 24 hours in the future."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # Construct the resource name of the CryptoKeyVersion.
    name = (
        'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/'
        'cryptoKeyVersions/{}'
        .format(
            project_id, location_id, key_ring_id, crypto_key_id, version_id))

    # Use the KMS API to schedule the CryptoKeyVersion for destruction.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.cryptoKeyVersions().destroy(name=name, body={})
    response = request.execute()

    print('CryptoKeyVersion {}\'s state has been set to {}.'.format(
        name, response['state']))
# [END kms_destroy_cryptokey_version]

# [START kms_add_member_to_cryptokey_policy]
def add_member_to_crypto_key_policy(
        project_id, location_id, key_ring_id, crypto_key_id, member, role):
    """Adds a member with a given role to the Identity and Access Management
    (IAM) policy for a given CryptoKey associated with a KeyRing."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    parent = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Get the current IAM policy and add the new member to it.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    policy_request = crypto_keys.getIamPolicy(resource=parent)
    policy_response = policy_request.execute()
    bindings = []
    if 'bindings' in policy_response.keys():
        bindings = policy_response['bindings']
    members = []
    members.append(member)
    new_binding = dict()
    new_binding['role'] = role
    new_binding['members'] = members
    bindings.append(new_binding)
    policy_response['bindings'] = bindings

    # Set the new IAM Policy.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.setIamPolicy(
        resource=parent, body={'policy': policy_response})
    request.execute()

    print_msg = (
        'Member {} added with role {} to policy for CryptoKey {} in KeyRing {}'
        .format(member, role, crypto_key_id, key_ring_id))
    print(print_msg)
# [END kms_add_member_to_cryptokey_policy]

# [START kms_get_keyring_policy]
def get_key_ring_policy(project_id, location_id, key_ring_id):
    """Gets the Identity and Access Management (IAM) policy for a given KeyRing
    and prints out roles and the members assigned to those roles."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the KeyRing.
    parent = 'projects/{}/locations/{}/keyRings/{}'.format(
        project_id, location_id, key_ring_id)

    # Get the current IAM policy.
    request = kms_client.projects().locations().keyRings().getIamPolicy(
        resource=parent)
    response = request.execute()

    if 'bindings' in response.keys():
        print('Printing IAM policy for resource {}:'.format(parent))
        for binding in response['bindings']:
            print('')
            print('Role: {}'.format(binding['role']))
            print('Members:')
            for member in binding['members']:
                print(member)
        print('')
    else:
        print('No roles found for resource {}.'.format(parent))
# [END kms_get_keyring_policy]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    subparsers = parser.add_subparsers(dest='command')

    create_key_ring_parser = subparsers.add_parser('create_key_ring')
    create_key_ring_parser.add_argument('project')
    create_key_ring_parser.add_argument('location')
    create_key_ring_parser.add_argument('key_ring')

    create_crypto_key_parser = subparsers.add_parser('create_crypto_key')
    create_crypto_key_parser.add_argument('project')
    create_crypto_key_parser.add_argument('location')
    create_crypto_key_parser.add_argument('key_ring')
    create_crypto_key_parser.add_argument('crypto_key')

    encrypt_parser = subparsers.add_parser('encrypt')
    encrypt_parser.add_argument('project')
    encrypt_parser.add_argument('location')
    encrypt_parser.add_argument('key_ring')
    encrypt_parser.add_argument('crypto_key')
    encrypt_parser.add_argument('infile')
    encrypt_parser.add_argument('outfile')

    decrypt_parser = subparsers.add_parser('decrypt')
    decrypt_parser.add_argument('project')
    decrypt_parser.add_argument('location')
    decrypt_parser.add_argument('key_ring')
    decrypt_parser.add_argument('crypto_key')
    decrypt_parser.add_argument('infile')
    decrypt_parser.add_argument('outfile')

    disable_crypto_key_version_parser = subparsers.add_parser(
        'disable_crypto_key_version')
    disable_crypto_key_version_parser.add_argument('project')
    disable_crypto_key_version_parser.add_argument('location')
    disable_crypto_key_version_parser.add_argument('key_ring')
    disable_crypto_key_version_parser.add_argument('crypto_key')
    disable_crypto_key_version_parser.add_argument('version')

    destroy_crypto_key_version_parser = subparsers.add_parser(
        'destroy_crypto_key_version')
    destroy_crypto_key_version_parser.add_argument('project')
    destroy_crypto_key_version_parser.add_argument('location')
    destroy_crypto_key_version_parser.add_argument('key_ring')
    destroy_crypto_key_version_parser.add_argument('crypto_key')
    destroy_crypto_key_version_parser.add_argument('version')

    add_member_to_crypto_key_policy_parser = subparsers.add_parser(
        'add_member_to_crypto_key_policy')
    add_member_to_crypto_key_policy_parser.add_argument('project')
    add_member_to_crypto_key_policy_parser.add_argument('location')
    add_member_to_crypto_key_policy_parser.add_argument('key_ring')
    add_member_to_crypto_key_policy_parser.add_argument('crypto_key')
    add_member_to_crypto_key_policy_parser.add_argument('member')
    add_member_to_crypto_key_policy_parser.add_argument('role')

    get_key_ring_policy_parser = subparsers.add_parser('get_key_ring_policy')
    get_key_ring_policy_parser.add_argument('project')
    get_key_ring_policy_parser.add_argument('location')
    get_key_ring_policy_parser.add_argument('key_ring')

    args = parser.parse_args()

    if args.command == 'create_key_ring':
        create_key_ring(
            args.project,
            args.location,
            args.key_ring)
    elif args.command == 'create_crypto_key':
        create_crypto_key(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key)
    elif args.command == 'encrypt':
        encrypt(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key,
            args.infile,
            args.outfile)
    elif args.command == 'decrypt':
        decrypt(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key,
            args.infile,
            args.outfile)
    elif args.command == 'disable_crypto_key_version':
        disable_crypto_key_version(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key,
            args.version)
    elif args.command == 'destroy_crypto_key_version':
        destroy_crypto_key_version(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key,
            args.version)
    elif args.command == 'add_member_to_crypto_key_policy':
        add_member_to_crypto_key_policy(
            args.project,
            args.location,
            args.key_ring,
            args.crypto_key,
            args.member,
            args.role)
    elif args.command == 'get_key_ring_policy':
        get_key_ring_policy(
            args.project,
            args.location,
            args.key_ring)


text:
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;

namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
    [TestFixture]
    public class ConditionIsAlwaysTrueOrFalseTests : CSharpDiagnosticTestBase
    {
        [Test]
        public void TestComparsionWithNull()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
class Test
{
	void Foo(int i)
	{
		if ($i == null$) {
		}
	}
}
", @"
class Test
{
	void Foo(int i)
	{
		if (false) {
		}
	}
}
");
        }

        [Test]
        public void TestComparsionWithNullCase2()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
enum Bar { A, B }
class Test
{
	void Foo(Bar i)
	{
		if ($i != null$) {
		}
	}
}
", @"
enum Bar { A, B }
class Test
{
	void Foo(Bar i)
	{
		if (true) {
		}
	}
}
");
        }

        [Test]
        public void TestComparison()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
class Test
{
	void Foo(int i)
	{
		if ($1 > 2$) {
		}
	}
}
", @"
class Test
{
	void Foo(int i)
	{
		if (false) {
		}
	}
}
");
        }

        [Test]
        public void TestUnary()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
class Test
{
	void Foo(int i)
	{
		if ($!true$) {
		}
	}
}
", @"
class Test
{
	void Foo(int i)
	{
		if (false) {
		}
	}
}
");
        }

        [Test]
        public void TestDisable()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
class Test
{
	void Foo(int i)
	{
#pragma warning disable " + CSharpDiagnosticIDs.ConditionIsAlwaysTrueOrFalseAnalyzerID + @"
		if (i == null) {
		}
	}
}
");
        }

        [Test]
        public void CompareWithNullable()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
class Bar
{
	public void Test(int? a)
	{
		if (a != null) {

		}
	}
}
");
        }

        [Test]
        public void UserDefinedOperatorsNoReferences()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
struct Foo
{
	public static bool operator ==(Foo value, Foo o)
	{
		return false;
	}

	public static bool operator !=(Foo value, Foo o)
	{
		return false;
	}
}

class Bar
{
	public void Test(Foo a)
	{
		if ($a != null$) {

		}
	}
}
");
        }

        [Test]
        public void UserDefinedOperators()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
struct Foo
{
	public static bool operator ==(Foo value, object o)
	{
		return false;
	}

	public static bool operator !=(Foo value, object o)
	{
		return false;
	}
}

class Bar
{
	public void Test(Foo a)
	{
		if (a != null) {

		}
	}
}
");
        }

        /// <summary>
        /// Bug 15099 - Wrong always true context
        /// </summary>
        [Test]
        public void TestBug15099()
        {
            Analyze<ConditionIsAlwaysTrueOrFalseAnalyzer>(@"
struct Foo
{
	string name;

	public Foo (string name)
	{
		this.name = name;
	}

	public static bool operator ==(Foo value, Foo o)
	{
		return value.name == o.name;
	}

	public static bool operator !=(Foo value, Foo o)
	{
		return !(value == o);
	}

	public static implicit operator Foo (string name)
	{
		return new Foo (name);
	}
}

class Bar
{
	public static void Main (string[] args)
	{
		var foo = new Foo (null);
		System.Console.WriteLine (foo == null);
	}
}");
        }

    }
}


text:
"""
Dynamically extend Gate classes with functions required for the Hoare
optimizer, namely triviality-conditions and post-conditions.
If `_trivial_if` returns `True` and the qubit is in a classical state
then the gate is trivial.
If a gate has no `_trivial_if`, then is assumed to be non-trivial.
If a gate has no `_postconditions`, then is assumed to have unknown post-conditions.
"""
from qiskit.circuit.library.standard_gates import IGate, XGate, YGate, ZGate
from qiskit.circuit.library.standard_gates import CXGate, CCXGate, CYGate, CZGate
from qiskit.circuit.library.standard_gates import TGate, TdgGate, SGate, SdgGate, RZGate, U1Gate
from qiskit.circuit.library.standard_gates import SwapGate, CSwapGate, CRZGate, CU1Gate, MCU1Gate
from qiskit.utils import optionals as _optionals

if _optionals.HAS_Z3:
    import z3  # pylint: disable=import-error

    # FLIP GATES #
    # XGate
    XGate._postconditions = lambda self, x1, y1: y1 == z3.Not(x1)
    CXGate._postconditions = lambda self, x1, y1: y1 == z3.Not(x1)
    CCXGate._postconditions = lambda self, x1, y1: y1 == z3.Not(x1)

    # YGate
    YGate._postconditions = lambda self, x1, y1: y1 == z3.Not(x1)
    CYGate._postconditions = lambda self, x1, y1: y1 == z3.Not(x1)

    # PHASE GATES #
    # IdGate
    IGate._postconditions = lambda self, x1, y1: y1 == x1

    # ZGate
    ZGate._trivial_if = lambda self, x1: True
    ZGate._postconditions = lambda self, x1, y1: y1 == x1
    CZGate._trivial_if = lambda self, x1: True
    CZGate._postconditions = lambda self, x1, y1: y1 == x1

    # SGate
    SGate._trivial_if = lambda self, x1: True
    SGate._postconditions = lambda self, x1, y1: y1 == x1
    SdgGate._trivial_if = lambda self, x1: True
    SdgGate._postconditions = lambda self, x1, y1: y1 == x1

    # TGate
    TGate._trivial_if = lambda self, x1: True
    TGate._postconditions = lambda self, x1, y1: y1 == x1
    TdgGate._trivial_if = lambda self, x1: True
    TdgGate._postconditions = lambda self, x1, y1: y1 == x1

    # RzGate
    RZGate._trivial_if = lambda self, x1: True
    RZGate._postconditions = lambda self, x1, y1: y1 == x1
    CRZGate._postconditions = lambda self, x1, y1: y1 == x1

    #  U1Gate
    U1Gate._trivial_if = lambda self, x1: True
    U1Gate._postconditions = lambda self, x1, y1: y1 == x1
    CU1Gate._trivial_if = lambda self, x1: True
    CU1Gate._postconditions = lambda self, x1, y1: y1 == x1
    MCU1Gate._trivial_if = lambda self, x1: True
    MCU1Gate._postconditions = lambda self, x1, y1: y1 == x1

    # MULTI-QUBIT GATES #
    # SwapGate
    SwapGate._trivial_if = lambda self, x1, x2: x1 == x2
    SwapGate._postconditions = lambda self, x1, x2, y1, y2: z3.And(x1 == y2, x2 == y1)
    CSwapGate._trivial_if = lambda self, x1, x2: x1 == x2
    CSwapGate._postconditions = lambda self, x1, x2, y1, y2: z3.And(x1 == y2, x2 == y1)


text:
name             'casperjs'
maintainer       'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license          'All rights reserved'
description      'Installs/Configures casperjs'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
module.exports = (req, res, next) => {
  const started = new Date();
  next();
  req.app.log.info(`${new Date() - started}ms ${req.method} ${req.url}`);
};


text:
local _, Engine = ...
local Handler = Engine:NewHandler("Shine")

-- Lua API
local _G = _G

-- WoW API
local CreateFrame = _G.CreateFrame
local GetTime = _G.GetTime

-- Client constants
local ENGINE_LEGION = Engine:IsBuild("Legion")

-- Shine defaults
local MAXALPHA = .5
local SCALE = 5
local DURATION = .75
local TEXTURE = [[Interface\Cooldown\star4]]

local New = function(frameType, parentClass)
	local class = CreateFrame(frameType)
	class.mt = { __index = class }
	if parentClass then
		class = setmetatable(class, { __index = parentClass })
		class.super = function(self, method, ...) parentClass[method](self, ...) end
	end
	class.Bind = function(self, obj) return setmetatable(obj, self.mt) end
	return class
end

local Shine = New("Frame")

Shine.New = function(self, parent, maxAlpha, duration, scale)
	local f = self:Bind(CreateFrame("Frame", nil, parent))
	f:Hide()
	f:SetScript("OnHide", Shine.OnHide)
	f:SetAllPoints(parent)
	f:SetToplevel(true)

	local t = f:CreateTexture(nil, "OVERLAY")
	t:SetPoint("CENTER")
	t:SetBlendMode("ADD")
	t:SetAllPoints(f)
	t:SetTexture(TEXTURE)

	f.animation = f:CreateShineAnimation(maxAlpha, duration, scale)
	f.lastPlayed = GetTime()
	f.throttle = 500
	return f
end

Shine.OnFinished = function(self)
	local parent = self:GetParent()
	if parent:IsShown() then
		parent:Hide()
	end
end

Shine.CreateShineAnimation = ENGINE_LEGION and function(self, maxAlpha, duration, scale)
	local MAXALPHA = maxAlpha or MAXALPHA
	local SCALE = scale or SCALE
	local DURATION = duration or DURATION

	local g = self:CreateAnimationGroup()
	g:SetLooping("NONE")
	g:SetScript("OnFinished", Shine.OnFinished)

	local a1 = g:CreateAnimation("Alpha")
	a1:SetToAlpha(0)
	a1:SetDuration(0)
	a1:SetOrder(0)

	local a2 = g:CreateAnimation("Scale")
	a2:SetOrigin("CENTER", 0, 0)
	a2:SetScale(SCALE, SCALE)
	a2:SetDuration(DURATION/2)
	a2:SetOrder(1)

	local a3 = g:CreateAnimation("Alpha")
	a3:SetToAlpha(MAXALPHA)
	a3:SetDuration(DURATION/2)
	a3:SetOrder(1)

	local a4 = g:CreateAnimation("Scale")
	a4:SetOrigin("CENTER", 0, 0)
	a4:SetScale(-SCALE, -SCALE)
	a4:SetDuration(DURATION/2)
	a4:SetOrder(2)

    local a5 = g:CreateAnimation("Alpha")
    a5:SetToAlpha(0)
    a5:SetDuration(DURATION/2)
    a5:SetOrder(2)

	return g

end or function(self, maxAlpha, duration, scale)
	local MAXALPHA = maxAlpha or MAXALPHA
	local SCALE = scale or SCALE
	local DURATION = duration or DURATION

	local g = self:CreateAnimationGroup()
	g:SetLooping("NONE")
	g:SetScript("OnFinished", Shine.OnFinished)

	local a1 = g:CreateAnimation("Alpha")
	a1:SetChange(-1)
	a1:SetDuration(0)
	a1:SetOrder(0)

	local a2 = g:CreateAnimation("Scale")
	a2:SetOrigin("CENTER", 0, 0)
	a2:SetScale(SCALE, SCALE)
	a2:SetDuration(DURATION/2)
	a2:SetOrder(1)

	local a3 = g:CreateAnimation("Alpha")
	a3:SetChange(MAXALPHA)
	a3:SetDuration(DURATION/2)
	a3:SetOrder(1)

	local a4 = g:CreateAnimation("Scale")
	a4:SetOrigin("CENTER", 0, 0)
	a4:SetScale(-SCALE, -SCALE)
	a4:SetDuration(DURATION/2)
	a4:SetOrder(2)

	local a5 = g:CreateAnimation("Alpha")
	a5:SetChange(-MAXALPHA)
	a5:SetDuration(DURATION/2)
	a5:SetOrder(2)

	return g
end

Shine.OnHide = function(self)
	if self.animation:IsPlaying() then
		self.animation:Finish()
	end
	self:Hide()
end

Shine.SetThrottle = function(self, ms)
	self.throttle = ms
end

Shine.Start = function(self)
	if (GetTime() - self.lastPlayed) < self.throttle then
		if self.animation:IsPlaying() then
			self.animation:Finish()
		end
		self:Show()
		self.animation:Play()
	end
	self.lastPlayed = GetTime()
end

-- usage:
-- 	local shine = Handler:ApplyShine(frame, maxAlpha, duration, scale)
-- 	shine:Start() -- start
--	shine:Hide() -- finish
Handler.ApplyShine = function(self, frame, maxAlpha, duration, scale)
	return Shine:New(frame, maxAlpha, duration, scale)
end

Handler.OnEnable = function(self)
end

Handler.OnDisable = function(self)
end


text:
<?php

if (get_magic_quotes_gpc()) {

if (!function_exists('stripslashes_arraysafe')) {
	/**
	 * A recursive implementation of stripslashes.
	 *
	 * This acts identically to its respective function, with the exception that
	 * it can be passed an array as well as a string. Arrays are passed by value
	 * so there is no risk of modification of the original array.
	 *
	 * @param mixed $val Data to strip slashes from
	 * @return mixed
	 */
	function stripslashes_arraysafe($val) {
		if (!is_array($val))
		{
			return stripslashes(trim($val));
		} else {
			foreach ($val as $k => $v) {
				$val[$k] = stripslashes_arraysafe($v);
			}
			return $val;
		}
	}
}

$_REQUEST = stripslashes_arraysafe($_REQUEST);
}

?>


text:
express-route-tester
====================

Attempts to give you an idea of what urls will be accepted by an express route (please fork and extend it).

To build, run:

```
npm install
npm run build
```


text:
#include <stdarg.h>
#include <stdio.h>

#include "wine/winbase16.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(rundll);

/**************************************************************************
 *  RUNDLL entry point
 */
WORD WINAPI WinMain16( HINSTANCE16 inst, HINSTANCE16 prev, LPSTR cmdline, WORD show )
{
    int len = GetSystemDirectoryA( NULL, 0 ) + sizeof("\\rundll32.exe ") + strlen(cmdline);
    char *buffer = HeapAlloc( GetProcessHeap(), 0, len );

    GetSystemDirectoryA( buffer, len );
    strcat( buffer, "\\rundll32.exe " );
    strcat( buffer, cmdline );

    WINE_TRACE( "starting %s\n", wine_dbgstr_a(buffer) );

    WinExec16( buffer, show );

    HeapFree( GetProcessHeap(), 0, buffer );
    ExitThread( 0 );
}