text:
#ifndef _GLUTEXTURE_HPP
#define _GLUTEXTURE_HPP
/*!
 * \file
 * \brief Texture classes.
 *//*--------------------------------------------------------------------*/

#include "gluDefs.hpp"
#include "tcuTexture.hpp"
#include "tcuCompressedTexture.hpp"
#include "tcuResource.hpp"
#include "gluRenderContext.hpp"
#include "gluContextInfo.hpp"
#include "deArrayBuffer.hpp"

#include <vector>
#include <string>

namespace glu
{

/*--------------------------------------------------------------------*//*!
 * \brief 1D Texture only supported on OpenGL
 *//*--------------------------------------------------------------------*/
class Texture1D
{
public:
							Texture1D				(const RenderContext& context, deUint32 format, deUint32 dataType, int width);
							Texture1D				(const RenderContext& context, deUint32 internalFormat, int width);
							~Texture1D				(void);

	tcu::Texture1D&			getRefTexture			(void)			{ return m_refTexture;	}
	const tcu::Texture1D&	getRefTexture			(void) const	{ return m_refTexture;	}
	deUint32				getGLTexture			(void) const	{ return m_glTexture;	}

	void					upload					(void);

private:
							Texture1D				(const Texture1D& other); // Not allowed!
	Texture1D&				operator=				(const Texture1D& other); // Not allowed!

	const RenderContext&	m_context;
	deUint32				m_format;				//!< Internal format.
	tcu::Texture1D			m_refTexture;
	deUint32				m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief 2D Texture
 *//*--------------------------------------------------------------------*/
class Texture2D
{
public:
							Texture2D				(const RenderContext& context, const ContextInfo& contextInfo, int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams = tcu::TexDecompressionParams());
							Texture2D				(const RenderContext& context, deUint32 format, deUint32 dataType, int width, int height);
							Texture2D				(const RenderContext& context, deUint32 internalFormat, int width, int height);
	virtual					~Texture2D				(void);

	virtual void			upload					(void); // Not supported on compressed textures.

	tcu::Texture2D&			getRefTexture			(void)			{ return m_refTexture;	}
	const tcu::Texture2D&	getRefTexture			(void) const	{ return m_refTexture;	}
	deUint32				getGLTexture			(void) const	{ return m_glTexture;	}

	static Texture2D*		create					(const RenderContext& context, const ContextInfo& contextInfo, const tcu::Archive& archive, int numLevels, const std::vector<std::string>& filenames);
	static Texture2D*		create					(const RenderContext& context, const ContextInfo& contextInfo, const tcu::Archive& archive, int numLevels, const char* const* filenames);
	static Texture2D*		create					(const RenderContext& context, const ContextInfo& contextInfo, const tcu::Archive& archive, const char* filename) { return create(context, contextInfo, archive, 1, &filename); }

protected:
	const RenderContext&	m_context;

	bool					m_isCompressed;
	deUint32				m_format;               //!< Internal format.
	tcu::Texture2D			m_refTexture;

	deUint32				m_glTexture;

private:
							Texture2D				(const Texture2D& other); // Not allowed!
	Texture2D&				operator=				(const Texture2D& other); // Not allowed!

	void					loadCompressed			(int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams);
} DE_WARN_UNUSED_TYPE;

class ImmutableTexture2D : public Texture2D
{
public:
							ImmutableTexture2D		(const RenderContext& context, deUint32 internalFormat, int width, int height);

	void					upload					(void); // Not supported on compressed textures.

private:
							ImmutableTexture2D		(const ImmutableTexture2D& other); // Not allowed!
	ImmutableTexture2D&		operator=				(const ImmutableTexture2D& other); // Not allowed!
};

/*--------------------------------------------------------------------*//*!
 * \brief Cube Map Texture
 *//*--------------------------------------------------------------------*/
class TextureCube
{
public:
	// For compressed cubemap constructor and create() function input level pointers / filenames are expected
	// to laid out to array in following order:
	//   { l0_neg_x, l0_pos_x, l0_neg_y, l0_pos_y, l0_neg_z, l0_pos_z, l1_neg_x, l1_pos_x, ... }

							TextureCube				(const RenderContext& context, const ContextInfo& contextInfo, int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams = tcu::TexDecompressionParams());
							TextureCube				(const RenderContext& context, deUint32 format, deUint32 dataType, int size);
							TextureCube				(const RenderContext& context, deUint32 internalFormat, int size);
							~TextureCube			(void);

	void					upload					(void); // Not supported on compressed textures.

	tcu::TextureCube&		getRefTexture			(void)			{ return m_refTexture;	}
	const tcu::TextureCube&	getRefTexture			(void) const	{ return m_refTexture;	}
	deUint32				getGLTexture			(void) const	{ return m_glTexture;	}

	static TextureCube*		create					(const RenderContext& context, const ContextInfo& contextInfo, const tcu::Archive& archive, int numLevels, const std::vector<std::string>& filenames);
	static TextureCube*		create					(const RenderContext& context, const ContextInfo& contextInfo, const tcu::Archive& archive, int numLevels, const char* const* filenames);

private:
							TextureCube				(const TextureCube& other); // Not allowed!
	TextureCube&			operator=				(const TextureCube& other); // Not allowed!

	void					loadCompressed			(int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams);

	const RenderContext&	m_context;

	bool					m_isCompressed;
	deUint32				m_format;				//!< Internal format.

	tcu::TextureCube		m_refTexture;
	deUint32				m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief 2D Array Texture
 * \note Not supported on OpenGL ES 2
 *//*--------------------------------------------------------------------*/
class Texture2DArray
{
public:
								Texture2DArray			(const RenderContext& context, deUint32 format, deUint32 dataType, int width, int height, int numLayers);
								Texture2DArray			(const RenderContext& context, deUint32 internalFormat, int width, int height, int numLayers);
								Texture2DArray			(const RenderContext& context, const ContextInfo& contextInfo, int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams = tcu::TexDecompressionParams());
								~Texture2DArray			(void);

	void						upload					(void);

	tcu::Texture2DArray&		getRefTexture			(void)			{ return m_refTexture;	}
	const tcu::Texture2DArray&	getRefTexture			(void) const	{ return m_refTexture;	}
	deUint32					getGLTexture			(void) const	{ return m_glTexture;	}

private:
								Texture2DArray			(const Texture2DArray& other); // Not allowed!
	Texture2DArray&				operator=				(const Texture2DArray& other); // Not allowed!

	void						loadCompressed			(int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams);

	const RenderContext&		m_context;

	bool						m_isCompressed;
	deUint32					m_format;				//!< Internal format.

	tcu::Texture2DArray			m_refTexture;
	deUint32					m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief 1D Array Texture
 * \note Only supported on OpenGL
 *//*--------------------------------------------------------------------*/
class Texture1DArray
{
public:
								Texture1DArray			(const RenderContext& context, deUint32 format, deUint32 dataType, int width, int numLayers);
								Texture1DArray			(const RenderContext& context, deUint32 internalFormat, int width, int numLayers);
								~Texture1DArray			(void);

	void						upload					(void);

	tcu::Texture1DArray&		getRefTexture			(void)			{ return m_refTexture;	}
	const tcu::Texture1DArray&	getRefTexture			(void) const	{ return m_refTexture;	}
	deUint32					getGLTexture			(void) const	{ return m_glTexture;	}

private:
								Texture1DArray			(const Texture1DArray& other); // Not allowed!
	Texture1DArray&				operator=				(const Texture1DArray& other); // Not allowed!

	const RenderContext&		m_context;

	deUint32					m_format;				//!< Internal format.

	tcu::Texture1DArray			m_refTexture;
	deUint32					m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief 3D Texture
 * \note Not supported on OpenGL ES 2
 *//*--------------------------------------------------------------------*/
class Texture3D
{
public:
								Texture3D			(const RenderContext& context, deUint32 format, deUint32 dataType, int width, int height, int depth);
								Texture3D			(const RenderContext& context, deUint32 internalFormat, int width, int height, int depth);
								Texture3D			(const RenderContext& context, const ContextInfo& contextInfo, int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams = tcu::TexDecompressionParams());
								~Texture3D			(void);

	void						upload				(void);

	tcu::Texture3D&				getRefTexture		(void)			{ return m_refTexture;	}
	const tcu::Texture3D&		getRefTexture		(void) const	{ return m_refTexture;	}
	deUint32					getGLTexture		(void) const	{ return m_glTexture;	}

private:
								Texture3D			(const Texture3D& other); // Not allowed!
	Texture3D&					operator=			(const Texture3D& other); // Not allowed!

	void						loadCompressed		(int numLevels, const tcu::CompressedTexture* levels, const tcu::TexDecompressionParams& decompressionParams);

	const RenderContext&		m_context;

	bool						m_isCompressed;
	deUint32					m_format;			//!< Internal format.

	tcu::Texture3D				m_refTexture;
	deUint32					m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief Cube Map Array Texture
 * \note Not supported on OpenGL ES 3.0 or lower
 *//*--------------------------------------------------------------------*/
class TextureCubeArray
{
public:
									TextureCubeArray	(const RenderContext& context, deUint32 format, deUint32 dataType, int size, int numLayers);
									TextureCubeArray	(const RenderContext& context, deUint32 internalFormat, int size, int numLayers);

									~TextureCubeArray	(void);

	void							upload				(void);

	tcu::TextureCubeArray&			getRefTexture		(void)			{ return m_refTexture;	}
	const tcu::TextureCubeArray&	getRefTexture		(void) const	{ return m_refTexture;	}
	deUint32						getGLTexture		(void) const	{ return m_glTexture;	}

private:
									TextureCubeArray	(const TextureCubeArray& other); // Not allowed!
	TextureCubeArray&				operator=			(const TextureCubeArray& other); // Not allowed!

	const RenderContext&			m_context;

	bool							m_isCompressed;
	deUint32						m_format;			//!< Internal format.

	tcu::TextureCubeArray			m_refTexture;
	deUint32						m_glTexture;
} DE_WARN_UNUSED_TYPE;

/*--------------------------------------------------------------------*//*!
 * \brief 1D Texture Buffer only supported on OpenGL
 *//*--------------------------------------------------------------------*/
class TextureBuffer
{
public:
										TextureBuffer		(const RenderContext& context, deUint32 internalFormat, size_t bufferSize);
										TextureBuffer		(const RenderContext& context, deUint32 internalFormat, size_t bufferSize, size_t offset, size_t size, const void* data = DE_NULL);

										~TextureBuffer		(void);

	// \note Effective pixel buffer access must be limited to w <= GL_MAX_TEXTURE_BUFFER_SIZE
	const tcu::PixelBufferAccess		getFullRefTexture	(void);
	const tcu::ConstPixelBufferAccess	getFullRefTexture	(void) const;

	// \note mutating buffer storage will invalidate existing pixel buffer accesses
	de::ArrayBuffer<deUint8>&			getRefBuffer		(void)			{ return m_refBuffer;			}
	const de::ArrayBuffer<deUint8>&		getRefBuffer		(void) const	{ return m_refBuffer;			}

	size_t								getSize				(void) const	{ return m_size;				}
	size_t								getOffset			(void) const	{ return m_offset;				}
	size_t								getBufferSize		(void) const	{ return m_refBuffer.size();	}

	deUint32							getGLTexture		(void) const	{ return m_glTexture;			}
	deUint32							getGLBuffer			(void) const	{ return m_glBuffer;			}

	void								upload				(void);

private:
	void								init				(deUint32 internalFormat, size_t bufferSize, size_t offset, size_t size, const void* data);
										TextureBuffer		(const TextureBuffer& other); // Not allowed!
	TextureBuffer&						operator=			(const TextureBuffer& other); // Not allowed!

	const RenderContext&				m_context;
	deUint32							m_format;		//!< Internal format.
	de::ArrayBuffer<deUint8>			m_refBuffer;
	size_t								m_offset;
	size_t								m_size;

	deUint32							m_glTexture;
	deUint32							m_glBuffer;
} DE_WARN_UNUSED_TYPE;

} // glu

#endif // _GLUTEXTURE_HPP


text:
require 'rufus/decision'
require 'ruote/participant'

module Rufus::Decision

  #
  # Decision participants were named 'CSV participants' prior to ruote 2.1.
  #
  # Make sure you have the gem "rufus-decision" installed in order to
  # use this decision participant.
  #
  #
  # == blog post
  #
  # This Rufus::Decision::Participant was introduced in the "ruote and
  # decision tables" blog post :
  #
  # http://jmettraux.wordpress.com/2010/02/17/ruote-and-decision-tables/
  #
  #
  # == example
  #
  # In this example, a participant named 'decide_team_member' is bound in the
  # ruote engine and, depending on the value of the workitem fields 'topic'
  # and region, sets the value of the field named 'team_member' :
  #
  #   require 'rufus/decision/participant'
  #
  #   engine.register_participant(
  #     :decide_team_member
  #     Rufus::Decision::Participant, :table => %{
  #       in:topic,in:region,out:team_member
  #       sports,europe,Alice
  #       sports,,Bob
  #       finance,america,Charly
  #       finance,europe,Donald
  #       finance,,Ernest
  #       politics,asia,Fujio
  #       politics,america,Gilbert
  #       politics,,Henry
  #       ,,Zach
  #     })
  #
  #   pdef = Ruote.process_definition :name => 'dec-test', :revision => '1' do
  #     sequence do
  #       decide_team_member
  #       participant :ref => '${team_member}'
  #     end
  #   end
  #
  # A process instance about the election results in Venezuela :
  #
  #   engine.launch(
  #     pdef,
  #     'topic' => 'politics',
  #     'region' => 'america',
  #     'line' => 'election results in Venezuela')
  #
  # would thus get routed to Gilbert.
  #
  # To learn more about decision tables :
  #
  # http://github.com/jmettraux/rufus-decision
  #
  #
  # == pointing to a table via a URI
  #
  # Note that you can reference the table by its URI :
  #
  #   engine.register_participant(
  #     :decide_team_member
  #     Rufus::Decision::Participant,
  #     :table => 'http://decisions.example.com/journalists.csv')
  #
  # If the table were a Google Spreadsheet, it would look like (note the
  # trailing &output=csv) :
  #
  #   engine.register_participant(
  #     :decide_team_member
  #     Rufus::Decision::Participant,
  #     :table => 'http://spreadsheets.google.com/pub?key=pCZNVR1TQ&output=csv')
  #
  class Participant
    include Ruote::LocalParticipant

    def initialize(opts={})

      @options = opts
    end

    def consume(workitem)

      table = @options['table']
      raise(ArgumentError.new("'table' option is missing")) unless table

      table = Rufus::Decision::Table.new(table, @options)

      workitem.fields = table.run(workitem.fields)

      reply_to_engine(workitem)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#define PRG_BEG \
switch(state) { \
case 0:;

#define PRG_END \
case -1:; \
default: { return false; } }

#define YIELD() \
do { state = __LINE__; return true; case __LINE__:; } while(0)

#define RETURN() \
do { state = -1; return false; } while(0)

#define YIELD_ALL(iter,output) while(iter->next(output)) YIELD();

using namespace std;

template<typename T>
class Generator : public std::enable_shared_from_this<Generator<T>> {
public:
    int state;
    Generator() : state(0) {}
    virtual bool next(T& output) = 0;
    bool operator()(T& output) {
        return next(output);
    }
    shared_ptr<Generator<T>> getPtr() { return this->shared_from_this(); }
};

template<typename T>
class IteratorHelper : public std::enable_shared_from_this<IteratorHelper<T>> {
public:
    shared_ptr<Generator<T>> gen;
    T output;
    bool pending;
    IteratorHelper(Generator<T> &_gen) : gen(_gen.getPtr()),  pending(false) {}
    IteratorHelper(shared_ptr<Generator<T>> _gen) : gen(_gen),  pending(false) {}
    T next() {
        if(!pending) hasNext();
        if(pending) {
            pending = false;
        } else {
            // Error, Iterator is done.
        }
        return output;
    }
    bool hasNext() {
        if(pending) return pending;
        return pending = gen->next(output);
    }
    shared_ptr<IteratorHelper<T>> getPtr() { return this->shared_from_this(); }
};

class Helper : public Generator<int> {
public:
    TreeNode * root;
    shared_ptr<Helper> iter;
    Helper(TreeNode * _root) : root(_root) {}
    bool next(int &output) {
        PRG_BEG
        if(root == NULL) RETURN();
        if(root->left == NULL && root->right == NULL) {
            output = root->val;
            YIELD();
            RETURN();
        }
        iter = make_shared<Helper>(root->left);
        YIELD_ALL(iter,output);
        output = root->val;
        YIELD();
        iter = make_shared<Helper>(root->right);
        YIELD_ALL(iter,output);
        PRG_END
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
public:
    IteratorHelper<int> iter;
    BSTIterator(TreeNode* root) : iter(make_shared<Helper>(root)) {

    }

    /** @return the next smallest number */
    int next() {
        return iter.next();
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return iter.hasNext();
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */


text:
var Select = {

    selectedNodes: null,
    options: null,

    coloring: {
        "label" : "Selection",
        "selection": true,
        "colors" : [
            { color: "yellow", label: "Selected nodes"},
            { color: "lightgreen", label: "Equivalent to selected"},
            { color: "tomato", label: "Implied by all the selected nodes"},
            { color: "cornflowerblue", label: "Implies all the selected nodes"},
            { color: "violet", label: "Compares to all the selected nodes"},
            { color: "lightgrey", label: "Other nodes"}
        ],
        "coloring" : null
    },

    create: function(options) {
        if(!options.keepSelection) {
            this.selectedNodes = {};
        }
        else {
            if(options.selection) {
                this.selectedNodes = {};
                for(var i=0; i<options.selection.length; i++) {
                    var key = options.selection[i];
                    this.selectedNodes[key] = Graph.nodes[key];
                }
            }
            for(var key in this.selectedNodes) {
                if(!Graph.nodes[key]) {
                    delete this.selectedNodes[key];
                }
            }
        }
        this.coloring.coloring = this.colorNode;
        this.options = $.extend({
            change: function() {}
        }, options);
        this.updateColoringFunction();

    },

    unselectAll: function() {
        this.selectedNodes = {};
        //Select.options.unselect.call(this);
        Select.updateColoringFunction();
    },

    unselect: function(data) {
        delete this.selectedNodes[data.key];
        //this.options.unselect.call(this);
        this.updateColoringFunction();
    },

    select: function(data) {
        this.selectedNodes[data.key] = data;
        //this.options.select.call(this, data);
        this.updateColoringFunction();
    },

    getSelectionList: function() {
        var sel = [];
        for(var key in this.selectedNodes) {
            sel.push(this.selectedNodes[key]);
        }
        return sel;
    },

    hasSelectedNodes: function() {
        for(var k in this.selectedNodes)
            return true;
        return false;
    },

    colorNode: function(node, context) {
        if(Select.selectedNodes[node.key]) {
            return 'yellow';
        }

        var belowAll = true;
        var aboveAll = true;
        var comparesAll = true;
        var compatibleBelowAll = true;
        var compatibleAboveAll = true;
        var compatibleComparesAll = true;

        for(var id in Select.selectedNodes) {
            if(!Graph.implications[id] || !Graph.implications[id][node.key]) {
                belowAll = false;
                break;
            }
        }
        for(var id in Select.selectedNodes) {
            if(!Graph.implications[node.key] || !Graph.implications[node.key][id]) {
                aboveAll = false;
                break;
            }
        }
        for(var id in Select.selectedNodes) {
            if((!Graph.implications[node.key] || !Graph.implications[node.key][id])
                 && (!Graph.implications[id] || !Graph.implications[id][node.key])) {
                comparesAll = false;
                break;
            }
        }
        for(var id in Select.selectedNodes) {
            if(Graph.nonImplications[id] && Graph.nonImplications[id][node.key]) {
                compatibleBelowAll = false;
                break;
            }
        }
        for(var id in Select.selectedNodes) {
            if(Graph.nonImplications[node.key] && Graph.nonImplications[node.key][id]) {
                compatibleAboveAll = false;
                break;
            }
        }
        for(var id in Select.selectedNodes) {
            if((Graph.nonImplications[node.key] && Graph.nonImplications[node.key][id])
               && (Graph.nonImplications[id] && Graph.nonImplications[id][node.key])) {
                compatibleComparesAll = false;
                break;
            }
        }
        if(aboveAll && belowAll) return 'lightgreen';
        if(belowAll) return 'tomato';
        if(aboveAll) return 'cornflowerblue';
        if(comparesAll) return 'violet';
        if(compatibleAboveAll && compatibleBelowAll) return 'lightgreen:lightgray';
        if(compatibleBelowAll) return 'tomato:lightgray';
        if(compatibleAboveAll) return 'cornflowerblue:lightgray';
        if(compatibleComparesAll) return 'violet:lightgray';
        return 'lightgray';
    },

        // If there are selected nodes, use a custom selection coloring function
        // Otherwise, revert to the previous coloring function
    updateColoringFunction: function() {
        var coloringNode = $('#coloring_function select');
        if(this.hasSelectedNodes()){
            if(!coloringNode.attr('disabled')) {
                var val = coloringNode.children().length;
                coloringNode.data('previousValue', coloringNode.val());
                coloringNode.append('<option value="' + val + '">' + this.coloring.label + '</option>');
                coloringNode.val(val);
                coloringNode.attr('disabled', 'disabled');
                coloringNode.trigger('change');
            }
        }
        else {
            if(coloringNode.attr('disabled')) {
                coloringNode.removeAttr('disabled', 'disabled');
                coloringNode.val(coloringNode.data('previousValue'));
                coloringNode.find('option:last').remove();
                coloringNode.trigger('change');

            }
        }

        // Save selection list to URL
        var urlData = Tools.getUrlData();
        var sels = [];
        for(var key in this.selectedNodes) {
            sels.push(key);
        }
        urlData.select = {
            keepSelection : true,
            selection : sels
        };
        Tools.setUrlData(urlData);

        this.options.change.call(this);
        Graph.colorNodes();
    },

    resetPanel: function() {
        var coloringNode = $('#coloring_function select');
    },

    processNode: function(node) {

        var ellipse = $('ellipse',node);

        // Define a visual effect on mouse over
        $(node).attr('style','cursor:hand');
        ellipse.attr('style', 'stroke-width:1;stroke:lightgray');
        $(node).hover(function(){
                      ellipse.attr('style','stroke-width:1;stroke:rgb(0,0,0)');
                      },function(){
                      ellipse.attr('style', 'stroke-width:1;stroke:lightgray');
                      });

        // Select or unselect
        $(node).click(function(){
          var data = $(this).data('data');
          if(Select.selectedNodes[data.key]) {
          Select.unselect(data);
          }
          else {
          Select.select(data);
          }

        });
    }

};


text:
<?php

namespace SaintSystems\OData;

class Option
{
    public function __construct(string $name, string $value)
    {
        $this->name = $name;
        $this->value = $value;
    }

    public $name;

    public $value;
}


text:
using System;

using ASC.Web.Studio.UserControls;

namespace ASC.Web.Studio
{
    public partial class DeepLink : MainPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Master.DisabledSidePanel = true;
            Master.TopStudioPanel.DisableUserInfo = true;
            Master.TopStudioPanel.DisableProductNavigation = true;
            Master.TopStudioPanel.DisableSearch = true;
            Master.TopStudioPanel.DisableSettings = true;
            Master.TopStudioPanel.DisableTariff = true;
            Master.TopStudioPanel.DisableLoginPersonal = true;
            Master.TopStudioPanel.DisableGift = true;

            var deepLinkingControl = (DeepLinking)LoadControl(DeepLinking.Location);
            DeepLinkingHolder.Controls.Add(deepLinkingControl);
        }
    }

}


text:
"""
Run regression on apartment data.
"""
from __future__ import print_function
import argparse
import pandas as pd
import numpy as np
import itertools
import matplotlib.pyplot as plt
import getpass

def parse_args(*argument_array):
    parser = argparse.ArgumentParser()
    parser.set_defaults(function=main)
    parser.add_argument('--user', default=getpass.getuser(),
                        help='Override system username with something else to '
                             'be include in the output file.')
    subs = parser.add_subparsers()
    test_parser = subs.add_parser('test')
    test_parser.set_defaults(function=test_function_signatures)
    parser.add_argument('--csv', default='yerevan_april_9.csv.gz',
                        help='CSV file with the apartment data.')
    args = parser.parse_args(*argument_array)
    return args

def featurize(apartment):
    """
    :param apartment: Apartment DataFrame row (a dictionary like object)
    :return: (x, y) tuple, where x is a numpy vector, and y is a number
    """
    return [1], apartment['price']

def poly_featurize(apartment, degree=2):
    """
    :param apartment: Apartment DataFrame row (a dictionary like object)
    :return: (x, y) tuple, where x is a numpy vector, and y is a number
    """
    x, y = featurize(apartment)
    poly_x = x
    return poly_x, y

def fit_ridge_regression(X, Y, l=0.1):
    """
    :param X: A numpy matrix, where each row is a data element (X)
    :param Y: A numpy vector of responses for each of the rows (y)
    :param l: ridge variable
    :return: A vector containing the hyperplane equation (beta)
    """
    D = X.shape[1]  # dimension + 1
    beta = np.zeros(D)  # FIXME: ridge regression formula.
    return beta

def cross_validate(X, Y, fitter, folds=5):
    """
    :param X: A numpy matrix, where each row is a data element (X)
    :param Y: A numpy vector of responses for each of the rows (y)
    :param fitter: A function that takes X, Y as parameters and returns beta
    :param folds: number of cross validation folds (parts)
    :return: list of corss-validation scores
    """
    scores = []
    # TODO: Divide X, Y into `folds` parts (e.g. 5)
    for i in range(folds):
        # TODO: train on the rest
        # TODO: Add corresponding score to scores
        pass
    return scores

def my_featurize(apartment):
    """
    This is the function we will use for scoring your implmentation.
    :param apartment: apartment row
    :return: (x, y) pair where x is feature vector, y is the response variable.
    """
    return featurize(apartment)

def my_beta():
    """
    :return: beta_hat that you estimate.
    """
    return np.zeros(1)

def main(args):
    df = pd.read_csv(args.csv)
    # TODO: Convert `df` into features (X) and responses (Y) using featurize
    beta = fit_ridge_regression(X, Y, l=0)
    # TODO you should probably create another function to pass to `cross_validate`
    scores = cross_validate(X, Y, fit_ridge_regression)
    print(np.mean(scores))

def test_function_signatures(args):
    apt = pd.Series({'price': 65000.0, 'condition': 'good', 'district': 'Center', 'max_floor': 9, 'street': 'Vardanants St', 'num_rooms': 3, 'region': 'Yerevan', 'area': 80.0, 'url': 'http://www.myrealty.am/en/item/24032/3-senyakanoc-bnakaran-vacharq-Yerevan-Center', 'num_bathrooms': 1, 'building_type': 'panel', 'floor': 4, 'ceiling_height': 2.7999999999999998})  # noqa
    x, y = my_featurize(apt)
    beta = my_beta()

    assert type(y) == float
    assert len(x.shape) == 1
    assert x.shape == beta.shape

if __name__ == '__main__':
    args = parse_args()
    args.function(args)


text:
SALVADOR	CONTINUED	LAURELS
I	SEEK	LAURELS
I	SEEK	LAURELS
I	SEEK	WHAT
I	SEEK	DEMOCRACY
I	SEEK	PROBLEMS
THAT	BENEFIT	PROBLEMS
I	SEEK	ECONOMY
THAT	BENEFIT	ECONOMY
I	SEEK	SALVADORANS
THAT	BENEFIT	SALVADORANS
WE	WISH	YOU
WE	WORK	YOU
WE	WISH	US
WE	WORK	US
US	SET	BANNERS
US	SET	FLAG
I	REITERATE	DETERMINATION
I	INTERESTED	END
I	HOPE	CALL
FMLN	HEAR	CALL
I	HOPE	RECONCILIATION
FMLN	HEAR	RECONCILIATION
I	HOPE	ATTITUDE
FMLN	SET	ATTITUDE
IT	DEMONSTRATE	ATTITUDE
I	HOPE	HOSTILITIES
FMLN	SET	HOSTILITIES
IT	DEMONSTRATE	HOSTILITIES
I	HOPE	INTENTIONS
FMLN	SET	INTENTIONS
IT	DEMONSTRATE	INTENTIONS
I	HOPE	ACTIONS
FMLN	SET	ACTIONS
IT	DEMONSTRATE	ACTIONS
I	HOPE	PROCESS
FMLN	MEET	PROCESS
WE	WILLING	PROCESS
I	HOPE	WHICH
FMLN	MEET	WHICH
WE	WILLING	WHICH
WHO	SUFFERING	CONSEQUENCES
WHO	AWAITING	CONSEQUENCES
I	ASSURE	CONSEQUENCES
GOVERNMENT	DETERMINED	CONSEQUENCES
WHO	SUFFERING	ACHIEVEMENT
WHO	AWAITING	ACHIEVEMENT
I	ASSURE	ACHIEVEMENT
GOVERNMENT	DETERMINED	ACHIEVEMENT
WHO	SUFFERING	YOU
WHO	AWAITING	YOU
I	ASSURE	YOU
GOVERNMENT	DETERMINED	YOU
WHO	SUFFERING	INTERESTS
WHO	AWAITING	INTERESTS
I	ASSURE	INTERESTS
GOVERNMENT	DETERMINED	INTERESTS
I	WANT	SALVADORANS
I	LIKE	SALVADORANS
THAT	HINDER	SALVADORANS
I	WANT	END
I	LIKE	END
THAT	HINDER	END
I	WANT	ATTITUDES
I	LIKE	ATTITUDES
THAT	HINDER	ATTITUDES
I	WANT	ACHIEVEMENT
I	LIKE	ACHIEVEMENT
THAT	HINDER	ACHIEVEMENT
US	SWITCH	ROLES
US	INSTRUMENTS	PEACE
WE	UNDERSTAND	PEACE
THIS	MEAN	PEACE
WE	UNDERSTAND	SURRENDER
THIS	MEAN	SURRENDER
WE	HAVE	OPPORTUNITIES
BROTHERS	LET	EFFORT
US	PRAY	EFFORT
GOD	OVERSEE	EFFORT
YOU	THANK	YOU
GOD	BLESS	YOU


text:
package io.gravitee.maven.plugins.json.schema.generator.util;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Aurélien Bourdon (aurelien.bourdon at gmail.com)
 */
public class GlobsTest {

    private static final List<String> INCLUDES = Arrays.asList(new String[]{"path/to/include/*.class"});

    private static final List<String> EXCLUDES = Arrays.asList(new String[]{"path/to/exclude/*.class"});

    @Test
    public void testGlobsCreationWithNullIncludes() {
        Globs globs = new Globs(null, EXCLUDES);
        Assert.assertEquals(Collections.<String>emptyList(), globs.getIncludes());
        Assert.assertEquals(EXCLUDES, globs.getExcludes());
    }

    @Test
    public void testGlobsCreationWithNullExcludes() {
        Globs globs = new Globs(INCLUDES, null);
        Assert.assertEquals(INCLUDES, globs.getIncludes());
        Assert.assertEquals(Collections.<String>emptyList(), globs.getExcludes());
    }

    @Test
    public void testGlobsCreationWithNullBothIncludesAndExclude() {
        Globs globs = new Globs(null, null);
        Assert.assertEquals(Collections.<String>emptyList(), globs.getIncludes());
        Assert.assertEquals(Collections.<String>emptyList(), globs.getExcludes());
    }

    @Test
    public void testGlobsCreationWithNonNullBothIncludesAndExclude() {
        Globs globs = new Globs(INCLUDES, EXCLUDES);
        Assert.assertEquals(INCLUDES, globs.getIncludes());
        Assert.assertEquals(EXCLUDES, globs.getExcludes());
    }

}


text:
#include <aws/appmesh/model/TlsValidationContextFileTrust.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace AppMesh
{
namespace Model
{

TlsValidationContextFileTrust::TlsValidationContextFileTrust() :
    m_certificateChainHasBeenSet(false)
{
}

TlsValidationContextFileTrust::TlsValidationContextFileTrust(JsonView jsonValue) :
    m_certificateChainHasBeenSet(false)
{
  *this = jsonValue;
}

TlsValidationContextFileTrust& TlsValidationContextFileTrust::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("certificateChain"))
  {
    m_certificateChain = jsonValue.GetString("certificateChain");

    m_certificateChainHasBeenSet = true;
  }

  return *this;
}

JsonValue TlsValidationContextFileTrust::Jsonize() const
{
  JsonValue payload;

  if(m_certificateChainHasBeenSet)
  {
   payload.WithString("certificateChain", m_certificateChain);

  }

  return payload;
}

} // namespace Model
} // namespace AppMesh
} // namespace Aws


text:
namespace syncer {

InvalidationNotifier::InvalidationNotifier(
    scoped_ptr<SyncNetworkChannel> network_channel,
    const std::string& invalidator_client_id,
    const UnackedInvalidationsMap& saved_invalidations,
    const std::string& invalidation_bootstrap_data,
    const WeakHandle<InvalidationStateTracker>& invalidation_state_tracker,
    const std::string& client_info)
    : state_(STOPPED),
      saved_invalidations_(saved_invalidations),
      invalidation_state_tracker_(invalidation_state_tracker),
      client_info_(client_info),
      invalidator_client_id_(invalidator_client_id),
      invalidation_bootstrap_data_(invalidation_bootstrap_data),
      invalidation_listener_(network_channel.Pass()) {
}

InvalidationNotifier::~InvalidationNotifier() {
  DCHECK(CalledOnValidThread());
}

void InvalidationNotifier::RegisterHandler(InvalidationHandler* handler) {
  DCHECK(CalledOnValidThread());
  registrar_.RegisterHandler(handler);
}

void InvalidationNotifier::UpdateRegisteredIds(InvalidationHandler* handler,
                                               const ObjectIdSet& ids) {
  DCHECK(CalledOnValidThread());
  registrar_.UpdateRegisteredIds(handler, ids);
  invalidation_listener_.UpdateRegisteredIds(registrar_.GetAllRegisteredIds());
}

void InvalidationNotifier::UnregisterHandler(InvalidationHandler* handler) {
  DCHECK(CalledOnValidThread());
  registrar_.UnregisterHandler(handler);
}

InvalidatorState InvalidationNotifier::GetInvalidatorState() const {
  DCHECK(CalledOnValidThread());
  return registrar_.GetInvalidatorState();
}

void InvalidationNotifier::UpdateCredentials(
    const std::string& email, const std::string& token) {
  if (state_ == STOPPED) {
    invalidation_listener_.Start(
        base::Bind(&invalidation::CreateInvalidationClient),
        invalidator_client_id_, client_info_, invalidation_bootstrap_data_,
        saved_invalidations_,
        invalidation_state_tracker_,
        this);
    state_ = STARTED;
  }
  invalidation_listener_.UpdateCredentials(email, token);
}

void InvalidationNotifier::RequestDetailedStatus(
    base::Callback<void(const base::DictionaryValue&)> callback) const {
  DCHECK(CalledOnValidThread());
  invalidation_listener_.RequestDetailedStatus(callback);
}

void InvalidationNotifier::OnInvalidate(
    const ObjectIdInvalidationMap& invalidation_map) {
  DCHECK(CalledOnValidThread());
  registrar_.DispatchInvalidationsToHandlers(invalidation_map);
}

void InvalidationNotifier::OnInvalidatorStateChange(InvalidatorState state) {
  DCHECK(CalledOnValidThread());
  registrar_.UpdateInvalidatorState(state);
}

}  // namespace syncer


text:
Identity Datastore
==================

To be confirmed.


text:
package com.jamal.springdemo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.jamal.springdemo.dao.OrganizationDao;
import com.jamal.springdemo.domain.Organization;

@Component
public class LoggingApp {

	@Autowired
	@Qualifier("orgDao")
	private OrganizationDao dao;

	@Autowired
	private DaoUtils daoUtils;

	public void actionMethod() {

		// Creating seed data.
		daoUtils.createSeedData(dao);

		// List organizations
		List<Organization> orgs = dao.getAllOrganizations();
		daoUtils.printOrganizations(orgs, daoUtils.readOperation);

		// Create a new organization record
		Organization org = new Organization("General Electric", 1978, "98989", 5776, "Imagination at work");
		boolean isCreated = dao.create(org);
		daoUtils.printSuccessFailure(daoUtils.createOperation, isCreated);
		daoUtils.printOrganizations(dao.getAllOrganizations(), daoUtils.readOperation);

		// get a single organization
		Organization org2 = dao.getOrganization(1);
		daoUtils.printOrganization(org2, "getOrganization");

		// Updating a slogan for an organization
		Organization org3 = dao.getOrganization(2);
		org3.setSlogan("We build ** awesome ** driving machines!");
		boolean isUpdated = dao.update(org3);
		daoUtils.printSuccessFailure(daoUtils.updateOperation, isUpdated);
		daoUtils.printOrganization(dao.getOrganization(2), daoUtils.updateOperation);

		// Delete an organization
		boolean isDeleted = dao.delete(dao.getOrganization(3));
		daoUtils.printSuccessFailure(daoUtils.deleteOperation, isDeleted);
		daoUtils.printOrganizations(dao.getAllOrganizations(), daoUtils.deleteOperation);

		// Cleanup
		dao.cleanup();
		daoUtils.printOrganizationCount(dao.getAllOrganizations(), daoUtils.cleanupOperation);

	}

	public static void main(String[] args) {

		// creating the application context
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cp.xml");
		LoggingApp mainApp = ctx.getBean(LoggingApp.class);
		mainApp.actionMethod();

		// close the application context
		((ClassPathXmlApplicationContext) ctx).close();

		// Create the bean
//		OrganizationDao dao = (OrganizationDaoImpl) ctx.getBean("orgDao");

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<checkstyle version="6.11.2">
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/batch/connectors/cassandra/CassandraInputFormat.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/batch/connectors/cassandra/CassandraOutputFormat.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraCommitter.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraPojoSink.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraSink.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraSinkBase.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraTupleSink.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/CassandraTupleWriteAheadSink.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/main/java/org/apache/flink/streaming/connectors/cassandra/ClusterBuilder.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-cassandra/src/test/resources/log4j-test.properties">
</file>
</checkstyle>


text:
package apple.homekit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;

@Library("HomeKit/HomeKit.h")
@Mapping("HMErrorCode")
public final class HMErrorCode extends ObjCEnum {

    @GlobalConstant("HMErrorCodeAlreadyExists")
    public static final long AlreadyExists = 1L;
    @GlobalConstant("HMErrorCodeNotFound")
    public static final long NotFound = 2L;
    @GlobalConstant("HMErrorCodeInvalidParameter")
    public static final long InvalidParameter = 3L;
    @GlobalConstant("HMErrorCodeAccessoryNotReachable")
    public static final long AccessoryNotReachable = 4L;
    @GlobalConstant("HMErrorCodeReadOnlyCharacteristic")
    public static final long ReadOnlyCharacteristic = 5L;
    @GlobalConstant("HMErrorCodeWriteOnlyCharacteristic")
    public static final long WriteOnlyCharacteristic = 6L;
    @GlobalConstant("HMErrorCodeNotificationNotSupported")
    public static final long NotificationNotSupported = 7L;
    @GlobalConstant("HMErrorCodeOperationTimedOut")
    public static final long OperationTimedOut = 8L;
    @GlobalConstant("HMErrorCodeAccessoryPoweredOff")
    public static final long AccessoryPoweredOff = 9L;
    @GlobalConstant("HMErrorCodeAccessDenied")
    public static final long AccessDenied = 10L;
    @GlobalConstant("HMErrorCodeObjectAssociatedToAnotherHome")
    public static final long ObjectAssociatedToAnotherHome = 11L;
    @GlobalConstant("HMErrorCodeObjectNotAssociatedToAnyHome")
    public static final long ObjectNotAssociatedToAnyHome = 12L;
    @GlobalConstant("HMErrorCodeObjectAlreadyAssociatedToHome")
    public static final long ObjectAlreadyAssociatedToHome = 13L;
    @GlobalConstant("HMErrorCodeAccessoryIsBusy")
    public static final long AccessoryIsBusy = 14L;
    @GlobalConstant("HMErrorCodeOperationInProgress")
    public static final long OperationInProgress = 15L;
    @GlobalConstant("HMErrorCodeAccessoryOutOfResources")
    public static final long AccessoryOutOfResources = 16L;
    @GlobalConstant("HMErrorCodeInsufficientPrivileges")
    public static final long InsufficientPrivileges = 17L;
    @GlobalConstant("HMErrorCodeAccessoryPairingFailed")
    public static final long AccessoryPairingFailed = 18L;
    @GlobalConstant("HMErrorCodeInvalidDataFormatSpecified")
    public static final long InvalidDataFormatSpecified = 19L;
    @GlobalConstant("HMErrorCodeNilParameter")
    public static final long NilParameter = 20L;
    @GlobalConstant("HMErrorCodeUnconfiguredParameter")
    public static final long UnconfiguredParameter = 21L;
    @GlobalConstant("HMErrorCodeInvalidClass")
    public static final long InvalidClass = 22L;
    @GlobalConstant("HMErrorCodeOperationCancelled")
    public static final long OperationCancelled = 23L;
    @GlobalConstant("HMErrorCodeRoomForHomeCannotBeInZone")
    public static final long RoomForHomeCannotBeInZone = 24L;
    @GlobalConstant("HMErrorCodeNoActionsInActionSet")
    public static final long NoActionsInActionSet = 25L;
    @GlobalConstant("HMErrorCodeNoRegisteredActionSets")
    public static final long NoRegisteredActionSets = 26L;
    @GlobalConstant("HMErrorCodeMissingParameter")
    public static final long MissingParameter = 27L;
    @GlobalConstant("HMErrorCodeFireDateInPast")
    public static final long FireDateInPast = 28L;
    @GlobalConstant("HMErrorCodeRoomForHomeCannotBeUpdated")
    public static final long RoomForHomeCannotBeUpdated = 29L;
    @GlobalConstant("HMErrorCodeActionInAnotherActionSet")
    public static final long ActionInAnotherActionSet = 30L;
    @GlobalConstant("HMErrorCodeObjectWithSimilarNameExistsInHome")
    public static final long ObjectWithSimilarNameExistsInHome = 31L;
    @GlobalConstant("HMErrorCodeHomeWithSimilarNameExists")
    public static final long HomeWithSimilarNameExists = 32L;
    @GlobalConstant("HMErrorCodeRenameWithSimilarName")
    public static final long RenameWithSimilarName = 33L;
    @GlobalConstant("HMErrorCodeCannotRemoveNonBridgeAccessory")
    public static final long CannotRemoveNonBridgeAccessory = 34L;
    @GlobalConstant("HMErrorCodeNameContainsProhibitedCharacters")
    public static final long NameContainsProhibitedCharacters = 35L;
    @GlobalConstant("HMErrorCodeNameDoesNotStartWithValidCharacters")
    public static final long NameDoesNotStartWithValidCharacters = 36L;
    @GlobalConstant("HMErrorCodeUserIDNotEmailAddress")
    public static final long UserIDNotEmailAddress = 37L;
    @GlobalConstant("HMErrorCodeUserDeclinedAddingUser")
    public static final long UserDeclinedAddingUser = 38L;
    @GlobalConstant("HMErrorCodeUserDeclinedRemovingUser")
    public static final long UserDeclinedRemovingUser = 39L;
    @GlobalConstant("HMErrorCodeUserDeclinedInvite")
    public static final long UserDeclinedInvite = 40L;
    @GlobalConstant("HMErrorCodeUserManagementFailed")
    public static final long UserManagementFailed = 41L;
    @GlobalConstant("HMErrorCodeRecurrenceTooSmall")
    public static final long RecurrenceTooSmall = 42L;
    @GlobalConstant("HMErrorCodeInvalidValueType")
    public static final long InvalidValueType = 43L;
    @GlobalConstant("HMErrorCodeValueLowerThanMinimum")
    public static final long ValueLowerThanMinimum = 44L;
    @GlobalConstant("HMErrorCodeValueHigherThanMaximum")
    public static final long ValueHigherThanMaximum = 45L;
    @GlobalConstant("HMErrorCodeStringLongerThanMaximum")
    public static final long StringLongerThanMaximum = 46L;
    @GlobalConstant("HMErrorCodeHomeAccessNotAuthorized")
    public static final long HomeAccessNotAuthorized = 47L;
    @GlobalConstant("HMErrorCodeOperationNotSupported")
    public static final long OperationNotSupported = 48L;
    @GlobalConstant("HMErrorCodeMaximumObjectLimitReached")
    public static final long MaximumObjectLimitReached = 49L;
    @GlobalConstant("HMErrorCodeAccessorySentInvalidResponse")
    public static final long AccessorySentInvalidResponse = 50L;
    @GlobalConstant("HMErrorCodeStringShorterThanMinimum")
    public static final long StringShorterThanMinimum = 51L;
    @GlobalConstant("HMErrorCodeGenericError")
    public static final long GenericError = 52L;
    @GlobalConstant("HMErrorCodeSecurityFailure")
    public static final long SecurityFailure = 53L;
    @GlobalConstant("HMErrorCodeCommunicationFailure")
    public static final long CommunicationFailure = 54L;
    @GlobalConstant("HMErrorCodeMessageAuthenticationFailed")
    public static final long MessageAuthenticationFailed = 55L;
    @GlobalConstant("HMErrorCodeInvalidMessageSize")
    public static final long InvalidMessageSize = 56L;
    @GlobalConstant("HMErrorCodeAccessoryDiscoveryFailed")
    public static final long AccessoryDiscoveryFailed = 57L;
    @GlobalConstant("HMErrorCodeClientRequestError")
    public static final long ClientRequestError = 58L;
    @GlobalConstant("HMErrorCodeAccessoryResponseError")
    public static final long AccessoryResponseError = 59L;
    @GlobalConstant("HMErrorCodeNameDoesNotEndWithValidCharacters")
    public static final long NameDoesNotEndWithValidCharacters = 60L;
    @GlobalConstant("HMErrorCodeAccessoryIsBlocked")
    public static final long AccessoryIsBlocked = 61L;
    @GlobalConstant("HMErrorCodeInvalidAssociatedServiceType")
    public static final long InvalidAssociatedServiceType = 62L;
    @GlobalConstant("HMErrorCodeActionSetExecutionFailed")
    public static final long ActionSetExecutionFailed = 63L;
    @GlobalConstant("HMErrorCodeActionSetExecutionPartialSuccess")
    public static final long ActionSetExecutionPartialSuccess = 64L;
    @GlobalConstant("HMErrorCodeActionSetExecutionInProgress")
    public static final long ActionSetExecutionInProgress = 65L;
    @GlobalConstant("HMErrorCodeAccessoryOutOfCompliance")
    public static final long AccessoryOutOfCompliance = 66L;
    @GlobalConstant("HMErrorCodeDataResetFailure")
    public static final long DataResetFailure = 67L;
    @GlobalConstant("HMErrorCodeNotificationAlreadyEnabled")
    public static final long NotificationAlreadyEnabled = 68L;
    @GlobalConstant("HMErrorCodeRecurrenceMustBeOnSpecifiedBoundaries")
    public static final long RecurrenceMustBeOnSpecifiedBoundaries = 69L;
    @GlobalConstant("HMErrorCodeDateMustBeOnSpecifiedBoundaries")
    public static final long DateMustBeOnSpecifiedBoundaries = 70L;
    @GlobalConstant("HMErrorCodeCannotActivateTriggerTooFarInFuture")
    public static final long CannotActivateTriggerTooFarInFuture = 71L;
    @GlobalConstant("HMErrorCodeRecurrenceTooLarge")
    public static final long RecurrenceTooLarge = 72L;
    @GlobalConstant("HMErrorCodeReadWritePartialSuccess")
    public static final long ReadWritePartialSuccess = 73L;
    @GlobalConstant("HMErrorCodeReadWriteFailure")
    public static final long ReadWriteFailure = 74L;
    @GlobalConstant("HMErrorCodeNotSignedIntoiCloud")
    public static final long NotSignedIntoiCloud = 75L;
    @GlobalConstant("HMErrorCodeKeychainSyncNotEnabled")
    public static final long KeychainSyncNotEnabled = 76L;
    @GlobalConstant("HMErrorCodeCloudDataSyncInProgress")
    public static final long CloudDataSyncInProgress = 77L;
    @GlobalConstant("HMErrorCodeNetworkUnavailable")
    public static final long NetworkUnavailable = 78L;
    @GlobalConstant("HMErrorCodeAddAccessoryFailed")
    public static final long AddAccessoryFailed = 79L;
    @GlobalConstant("HMErrorCodeMissingEntitlement")
    public static final long MissingEntitlement = 80L;

}


text:
require 'spec_helper'

describe 'prometheus::statsd_exporter' do
  on_supported_os.each do |os, facts|
    context "on #{os}" do
      let(:facts) do
        facts.merge(os_specific_facts(facts))
      end

      context 'with version specified' do
        let(:params) do
          {
            version: '0.8.0',
            arch: 'amd64',
            os: 'linux',
            bin_dir: '/usr/local/bin',
            install_method: 'url',
            mappings: [
              {
                match: 'test.dispatcher.*.*.*',
                name: 'dispatcher_events_total',
                labels: {
                  processor: '$1',
                  action: '$2',
                  outcome: '$3',
                  job: 'test_dispatcher'
                }
              },
              {
                match: '*.signup.*.*',
                name: 'signup_events_total',
                labels: {
                  provider: '$2',
                  outcome: '$3',
                  job: '${1}_server'
                }
              }
            ]
          }
        end

        it { is_expected.to contain_archive('/tmp/statsd_exporter-0.8.0.tar.gz') }

        describe 'compile manifest' do
          it { is_expected.to compile.with_all_deps }
        end

        describe 'install correct binary' do
          it { is_expected.to contain_file('/usr/local/bin/statsd_exporter').with('target' => '/opt/statsd_exporter-0.8.0.linux-amd64/statsd_exporter') }
        end

        describe 'required resources' do
          it { is_expected.to contain_prometheus__daemon('statsd_exporter').with(options: "--statsd.mapping-config='/etc/statsd-exporter-mapping.yaml' ") }
          it { is_expected.to contain_user('statsd-exporter') }
          it { is_expected.to contain_group('statsd-exporter') }
          it { is_expected.to contain_service('statsd_exporter') }
        end

        describe 'mapping config file' do
          it {
            is_expected.to contain_file('/etc/statsd-exporter-mapping.yaml').with(
              'ensure'  => 'file',
              'owner'   => 'root',
              'group'   => 'statsd-exporter',
              'mode'    => '0640',
              'notify'  => 'Service[statsd_exporter]',
              'content' => <<-YAML.gsub(%r{^\s+\|}, '')
                |---
                |mappings:
                |- match: test.dispatcher.*.*.*
                |  name: dispatcher_events_total
                |  labels:
                |    processor: "$1"
                |    action: "$2"
                |    outcome: "$3"
                |    job: test_dispatcher
                |- match: "*.signup.*.*"
                |  name: signup_events_total
                |  labels:
                |    provider: "$2"
                |    outcome: "$3"
                |    job: "${1}_server"
              YAML
            )
          }
        end
      end

      context 'with older version that does not support posix like option flags specified' do
        let(:params) do
          {
            version: '0.6.0',
            arch: 'amd64',
            os: 'linux',
            bin_dir: '/usr/local/bin',
            install_method: 'url'
          }
        end

        describe 'compile manifest' do
          it { is_expected.to compile.with_all_deps }
        end

        it { is_expected.to contain_prometheus__daemon('statsd_exporter').with(options: "-statsd.mapping-config='/etc/statsd-exporter-mapping.yaml' ") }
      end
    end
  end
end


text:
'use strict';

class PricesRoutes {
    constructor($stateProvider) {
        this.$stateProvider = $stateProvider;
        this.init();
    }

    init() {
        this.$stateProvider
            .state('prices', {
                url: '/prices',
                controller: 'PricesController',
                controllerAs: 'vm',
                templateUrl: '/modules/prices/views/list-prices.client.view.html'
            });
    }

    // @ngInject
    static factory($stateProvider){
        return new PricesRoutes($stateProvider);
    }
}

angular.module('prices').config(PricesRoutes.factory);


text:
using System;
using System.Collections.Generic;

namespace FluentRest.Fake
{
    /// <summary>
    /// A fake response container used to store fake responses.
    /// </summary>
    public class FakeResponseContainer
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="FakeResponseContainer"/> class.
        /// </summary>
        public FakeResponseContainer()
        {
            ResponseMessage = new FakeResponseMessage();
            ResponseMessage.ReasonPhrase = "OK";
            ResponseMessage.StatusCode = System.Net.HttpStatusCode.OK;
            ResponseMessage.ResponseHeaders["Status"] = new List<string> { "200 OK" };
        }

        /// <summary>
        /// The callback used to serialize the fake response data objects into a byte array.
        /// If not specified, the default settings for the System.Text.Json.JsonSerializer will be used.
        ///</summary>
        public SerializeResponseContentCallback SerializeResponseContentCallback { get; set; }

        /// <summary>
        /// Gets or sets the request URI.
        /// </summary>
        /// <value>
        /// The request URI.
        /// </value>
        public Uri RequestUri { get; set; }

        /// <summary>
        /// Gets or sets the response message.
        /// </summary>
        /// <value>
        /// The response message.
        /// </value>
        public FakeResponseMessage ResponseMessage { get; set; }

        /// <summary>
        /// Gets or sets the content of the HTTP response.
        /// </summary>
        /// <value>
        /// The content of the HTTP response.
        /// </value>
        public byte[] HttpContent { get; set; }
    }
}


text:
package kademlia

func (k *Kademlia) Bootstrap(target, self Contact) ([]Contact, error) {
	client, err := dialContact(target)
	if err != nil {
		return nil, err
	}

	req := k.NewFindNodeRequest(self.ID)
	res := FindNodeResponse{}

	err = client.Call("KademliaCore.FindNodeRPC", &req, &res)
	if err != nil {
		return nil, err
	}

	k.routes.Update(res.Sender)

	return res.Contacts, nil
}


text:
export interface MarkSearchStringPart {
    text: string;
    marked?: boolean
}

export function markSearchString (text: string, query: string): MarkSearchStringPart[] {
    if (!query) return [{ text }];

    const chunks = [];

    const lowerText = text.toLowerCase();
    const lowerQuery = query.toLowerCase();

    let start = 0;
    let end = 0;

    while (end < text.length) {
        const foundIdx = lowerText.indexOf(lowerQuery, end);
        const found = foundIdx >= 0;

        end = found ? foundIdx : text.length;

        if (end) {
            chunks.push({ text: text.substring(start, end) });
            start = end;
        }

        if (found) {
            end += query.length;

            chunks.push({
                text: text.substring(start, end),
                marked: true
            });

            start = end;
        }
    }

    return chunks;
}


text:
package io.cattle.platform.framework.encryption.impl;

import io.cattle.platform.framework.encryption.EncryptionUtils;
import io.github.ibuildthecloud.gdapi.model.Transformer;
import org.apache.commons.lang3.StringUtils;

public class NoOpTransformer implements Transformer {

    private static final String METADATA = "***";
    private static final String NAME = "NoOp";

    @Override
    public String transform(String value) {
        if (StringUtils.isBlank(value)){
            return "";
        }
        return METADATA + StringUtils.reverse(value) + StringUtils.reverse(METADATA);
    }

    @Override
    public String untransform(String value) {
        if (StringUtils.isBlank(value)){
            return "";
        }
        return StringUtils.reverse(StringUtils.removeEnd(StringUtils.removeStart(value, METADATA), StringUtils.reverse(METADATA)));
    }

    @Override
    public boolean compare(String plainText, String transformed) {
        return EncryptionUtils.isEqual(plainText, untransform(transformed));
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public void init() {
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
	selector:    'app-register',
	templateUrl: './register.component.html',
	styleUrls:   ['./register.component.less'],
})
export class UserRegisterComponent implements OnInit {

	constructor() {

	}

	ngOnInit() {
	}

	signUp(userForm) {
		console.log('u click submit', userForm);
	}

	showMsg(msg) {
		console.log(msg);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Threading;

namespace egb.ordenandoCartas
{
	class ordenandoCartas
	{
		static List<Carta> baraja = new List<Carta> (48);
		static Random dado = new Random ();

		static void ListarBaraja(List<Carta> b)
		{
			foreach (Carta item in b) {
				Console.WriteLine (item.ToString());
			}
		}

		static Carta CrearCarta()
		{
			Carta cartaTMP = new Carta ();
			int valor = 0;
			bool noValido = true;

			while (noValido) {
				if ((valor = dado.Next (1, 13)) != 8 && valor != 9)
					noValido = false;
			}
			cartaTMP = new Carta ((Carta.Palos)dado.Next (0, 4), valor, (Carta.Figuras)(valor - 1));
			return cartaTMP;
		}

		public static void Main (string[] args)
		{
			Console.Title = "Operando con cartas";

			for (int i = 0; i < 50; i++) {
				baraja.Add(CrearCarta ());
			}
			ListarBaraja (baraja);
			Console.ReadLine ();

			baraja.Sort(new OrdenAscPorValor());
			Console.WriteLine ("\nPor valor:");
			ListarBaraja (baraja);
			baraja.Sort(new OrdenDescPorPalos());
			Console.WriteLine ("Por palos:");
			ListarBaraja (baraja);
			baraja.Sort(new OrdenAscPorFiguras());
			Console.WriteLine ("Por figuras:");
			ListarBaraja (baraja);

			Console.ReadLine ();
		}
	}
}


text:
class PolygraphException(Exception):
    pass

class PolygraphValueError(PolygraphException):
    pass

class PolygraphTypeError(PolygraphException):
    pass

class PolygraphSchemaError(PolygraphException):
    pass


text:
$:.unshift('.')
$:.unshift(File.expand_path(File.dirname(__FILE__)) + '/../lib')
require 'zmq'

ctx = ZMQ::Context.new
pub = ctx.bind(:PUB, 'inproc://example.poller')

subscribers = []

poller = ZMQ::Poller.new

5.times do
  sub = ctx.connect(:SUB, 'inproc://example.poller')
  sub.subscribe("")
  subscribers << sub
  poller.register_readable(sub)
end

puts "[#{subscribers.size}] subscribers registered with the poller"
p subscribers

puts "publisher sends 'test'"
pub.send("test")

puts "poll, timeout 1s"
poller.poll(1)
puts "readable sockets ..."
p poller.readables
puts "writable sockets ..."
p poller.writables

puts "Subscriber sockets can receive without blocking ..."
p subscribers.map{|s| s.recv_nonblock }

ctx.destroy


text:
A DMFontPreview shows a text morph that can change the size. This class is used by DMGui.

Instance Variables
	fontPreview:		pluggable textMorph


text:
package com.kaduu.model;

public class Gasto implements HasID {

	private int id;
	private String descripcion;
	private double valor;

	public Gasto(){}

	public Gasto(int id, String descripcion, double valor){
		this.id = id;
		this.descripcion = descripcion;
		this.valor = valor;
	}

	public String getDescripcion() {
		return descripcion;
	}

	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion;
	}

	public double getValor() {
		return valor;
	}

	public void setValor(double valor) {
		this.valor = valor;
	}

	@Override
	public String toString() {
		return "Costo: Descripcion: " + this.descripcion + " Valor: " + valor;
	}

	public int getID() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void setID(int id) {
		// TODO Auto-generated method stub

	}

}


text:
"""Ce fichier contient la configuration par défaut du module 'systeme'."""

cfg_droits = r"""
# Ce fichier contient la configuration des droits du module systeme.
# Il permet de paramétrer les options de sécurité du module systeme.
# Ce module permettant l'accès aux commandes systèmes de Kassie, configurer
# ces options est recommandé.
# Pour plus d'informations, consultez la documentation :
# http://redmine.kassie.fr/projects/documentation/wiki/Deploiement
# ou consultez le fichier doc/Deploiement.txt

## Commande systeme

# Active ou inactive
# Vous pouvez ici activer ou désactiver la commande système/system.
# Mettez la variable à False pour désactiver la commande ou à True sinon.
cmd_systeme = True

# Adresses IP autorisées
# Vous pouvez configurer ici une liste d'adresse IP ayant le droit
# d'utiliser la commande système/system. Notez que si la variable
# cmd_systeme est à True, un client connecté en local aura toujours
# le droit d'exécuter système/system. Cela veut dire que l'adresse
# IP 127.0.0.1 est toujours implicite dans la liste ci-dessous.
# Rajoutez les adresses IP des personnes en qui vous pouvez avoir
# confiance.
cmd_systeme_ip = []

"""


text:
package org.codehaus.groovy.grails.orm.hibernate;

import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class GrailsHibernateTemplate extends HibernateTemplate {

    public GrailsHibernateTemplate() {
        initialize(null);
    }

    public GrailsHibernateTemplate(SessionFactory sessionFactory, boolean allowCreate) {
        super(sessionFactory, allowCreate);
        initialize(null);
    }

    public GrailsHibernateTemplate(SessionFactory sessionFactory) {
        super(sessionFactory);
        initialize(null);
    }

    public GrailsHibernateTemplate(SessionFactory sessionFactory, GrailsApplication application) {
        super(sessionFactory);
        initialize(application);
    }

    private void initialize(GrailsApplication application) {
        setExposeNativeSession(true);
        if (application != null) {
            setCacheQueries(GrailsHibernateUtil.isCacheQueriesByDefault(application));
        }
    }

    public void applySettings(Query queryObject) {
        if (isExposeNativeSession()) {
            super.prepareQuery(queryObject);
        }
    }

    public void applySettings(Criteria criteria) {
        if (isExposeNativeSession()) {
            super.prepareCriteria(criteria);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="fos_elastica.provider_registry.class">FOS\ElasticaBundle\Provider\ProviderRegistry</parameter>
    </parameters>

    <services>
        <service id="fos_elastica.provider_registry" class="%fos_elastica.provider_registry.class%">
            <call method="setContainer">
                <argument type="service" id="service_container" />
            </call>
        </service>
    </services>
</container>


text:
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__.'/vendor/google-api-php-client/src/');

class sfIzarusGoogleOAuth2
{

  protected $client = null;
  protected $access_token = null;

  public function __construct($domain=false){
    sfContext::getInstance()->getConfiguration()->loadHelpers(array('Url'));

    $client_id = sfConfig::get('app_googleoauth2_client_id');
    $client_secret = sfConfig::get('app_googleoauth2_client_secret');
    $hd = sfConfig::get('app_googleoauth2_hosted_domain');
    $allowed_domains = sfConfig::get('app_googleoauth2_allowed_domains');

    $this->client = new Google_Client();
    if(!$domain && !empty($hd))
      $this->client->setHostedDomain($hd);
    else if($domain && in_array($domain,$allowed_domains))
      $this->client->setHostedDomain($domain);
    else if($domain && !in_array($domain,$allowed_domains))
      die;
    $this->client->setClientId($client_id);
    $this->client->setClientSecret($client_secret);
    $this->client->setRedirectUri(url_for('@izarus_googleoauth2_signin',true));
    $this->client->addScope("https://www.googleapis.com/auth/userinfo.email");
    $this->client->addScope("https://www.googleapis.com/auth/userinfo.profile");
  }

  public function getUser() {
    if($this->client->getAccessToken()){
      $oauth2 = new apiOauth2Service($this->client);
      return $oauth2->userinfo->get();
    }
    return false;
  }

  public function getLoginUrl(){
    return $this->client->createAuthUrl();
  }

  public function getClient(){
    return $this->client;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workbook>
	<worksheet name="工作表1">

		<loop startRow="2" endRow="2" items="warehouseVOs" var="warehouseVO"
			varType="ndm.miniwms.vo.WarehouseVO">

				<mapping row="2" col="0">warehouseVO.name</mapping>

				<mapping row="2" col="1">warehouseVO.address</mapping>
				<mapping row="2" col="2">warehouseVO.description</mapping>
				<mapping row="2" col="3">warehouseVO.contactName</mapping>
				<mapping row="2" col="4">warehouseVO.contactTel</mapping>
				<mapping row="2" col="5">warehouseVO.contactFax</mapping>
				<mapping row="2" col="6">warehouseVO.contactEmail</mapping>
				<mapping row="2" col="7">warehouseVO.contactQq</mapping>
				<mapping row="2" col="8">warehouseVO.contactMsn</mapping>
				<mapping row="2" col="9">warehouseVO.contactDesc</mapping>

			<loopbreakcondition>
				<rowcheck offset="0">
					<cellcheck offset="0"></cellcheck>
				</rowcheck>
			</loopbreakcondition>
		</loop>
	</worksheet>
</workbook>


text:
/* Copied from http://stackoverflow.com/a/17646775/1821055
 * with the following modifications:
 *   * remove test code
 *   * global hw/sw initialization to be called once per process
 *   * HW support is determined by configure's WITH_CRC32C_HW
 *   * Windows porting (no hardware support on Windows yet)
 *
 * FIXME:
 *   * Hardware support on Windows (MSVC assembler)
 *   * Hardware support on ARM
 */

/* crc32c.c -- compute CRC-32C using the Intel crc32 instruction
 * Copyright (C) 2013 Mark Adler
 * Version 1.1  1 Aug 2013  Mark Adler
 */

/*
  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the author be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Mark Adler
  madler@alumni.caltech.edu
 */

/* Use hardware CRC instruction on Intel SSE 4.2 processors.  This computes a
   CRC-32C, *not* the CRC-32 used by Ethernet and zip, gzip, etc.  A software
   version is provided as a fall-back, as well as for speed comparisons. */

/* Version history:
   1.0  10 Feb 2013  First version
   1.1   1 Aug 2013  Correct comments on why three crc instructions in parallel
 */

#include "rd.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef _WIN32
#include <unistd.h>
#endif

#include "rdunittest.h"
#include "rdendian.h"

#include "crc32c.h"

/* CRC-32C (iSCSI) polynomial in reversed bit order. */
#define POLY 0x82f63b78

/* Table for a quadword-at-a-time software crc. */
static uint32_t crc32c_table[8][256];

/* Construct table for software CRC-32C calculation. */
static void crc32c_init_sw(void)
{
    uint32_t n, crc, k;

    for (n = 0; n < 256; n++) {
        crc = n;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc = crc & 1 ? (crc >> 1) ^ POLY : crc >> 1;
        crc32c_table[0][n] = crc;
    }
    for (n = 0; n < 256; n++) {
        crc = crc32c_table[0][n];
        for (k = 1; k < 8; k++) {
            crc = crc32c_table[0][crc & 0xff] ^ (crc >> 8);
            crc32c_table[k][n] = crc;
        }
    }
}

/* Table-driven software version as a fall-back.  This is about 15 times slower
   than using the hardware instructions.  This assumes little-endian integers,
   as is the case on Intel processors that the assembler code here is for. */
static uint32_t crc32c_sw(uint32_t crci, const void *buf, size_t len)
{
    const unsigned char *next = buf;
    uint64_t crc;

    crc = crci ^ 0xffffffff;
    while (len && ((uintptr_t)next & 7) != 0) {
        crc = crc32c_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
        len--;
    }
    while (len >= 8) {
        /* Alignment-safe */
        uint64_t ncopy;
        memcpy(&ncopy, next, sizeof(ncopy));
        crc ^= le64toh(ncopy);
        crc = crc32c_table[7][crc & 0xff] ^
              crc32c_table[6][(crc >> 8) & 0xff] ^
              crc32c_table[5][(crc >> 16) & 0xff] ^
              crc32c_table[4][(crc >> 24) & 0xff] ^
              crc32c_table[3][(crc >> 32) & 0xff] ^
              crc32c_table[2][(crc >> 40) & 0xff] ^
              crc32c_table[1][(crc >> 48) & 0xff] ^
              crc32c_table[0][crc >> 56];
        next += 8;
        len -= 8;
    }
    while (len) {
        crc = crc32c_table[0][(crc ^ *next++) & 0xff] ^ (crc >> 8);
        len--;
    }
    return (uint32_t)crc ^ 0xffffffff;
}

#if WITH_CRC32C_HW
static int sse42;  /* Cached SSE42 support */

/* Multiply a matrix times a vector over the Galois field of two elements,
   GF(2).  Each element is a bit in an unsigned integer.  mat must have at
   least as many entries as the power of two for most significant one bit in
   vec. */
static RD_INLINE uint32_t gf2_matrix_times(uint32_t *mat, uint32_t vec)
{
    uint32_t sum;

    sum = 0;
    while (vec) {
        if (vec & 1)
            sum ^= *mat;
        vec >>= 1;
        mat++;
    }
    return sum;
}

/* Multiply a matrix by itself over GF(2).  Both mat and square must have 32
   rows. */
static RD_INLINE void gf2_matrix_square(uint32_t *square, uint32_t *mat)
{
    int n;

    for (n = 0; n < 32; n++)
        square[n] = gf2_matrix_times(mat, mat[n]);
}

/* Construct an operator to apply len zeros to a crc.  len must be a power of
   two.  If len is not a power of two, then the result is the same as for the
   largest power of two less than len.  The result for len == 0 is the same as
   for len == 1.  A version of this routine could be easily written for any
   len, but that is not needed for this application. */
static void crc32c_zeros_op(uint32_t *even, size_t len)
{
    int n;
    uint32_t row;
    uint32_t odd[32];       /* odd-power-of-two zeros operator */

    /* put operator for one zero bit in odd */
    odd[0] = POLY;              /* CRC-32C polynomial */
    row = 1;
    for (n = 1; n < 32; n++) {
        odd[n] = row;
        row <<= 1;
    }

    /* put operator for two zero bits in even */
    gf2_matrix_square(even, odd);

    /* put operator for four zero bits in odd */
    gf2_matrix_square(odd, even);

    /* first square will put the operator for one zero byte (eight zero bits),
       in even -- next square puts operator for two zero bytes in odd, and so
       on, until len has been rotated down to zero */
    do {
        gf2_matrix_square(even, odd);
        len >>= 1;
        if (len == 0)
            return;
        gf2_matrix_square(odd, even);
        len >>= 1;
    } while (len);

    /* answer ended up in odd -- copy to even */
    for (n = 0; n < 32; n++)
        even[n] = odd[n];
}

/* Take a length and build four lookup tables for applying the zeros operator
   for that length, byte-by-byte on the operand. */
static void crc32c_zeros(uint32_t zeros[][256], size_t len)
{
    uint32_t n;
    uint32_t op[32];

    crc32c_zeros_op(op, len);
    for (n = 0; n < 256; n++) {
        zeros[0][n] = gf2_matrix_times(op, n);
        zeros[1][n] = gf2_matrix_times(op, n << 8);
        zeros[2][n] = gf2_matrix_times(op, n << 16);
        zeros[3][n] = gf2_matrix_times(op, n << 24);
    }
}

/* Apply the zeros operator table to crc. */
static RD_INLINE uint32_t crc32c_shift(uint32_t zeros[][256], uint32_t crc)
{
    return zeros[0][crc & 0xff] ^ zeros[1][(crc >> 8) & 0xff] ^
           zeros[2][(crc >> 16) & 0xff] ^ zeros[3][crc >> 24];
}

/* Block sizes for three-way parallel crc computation.  LONG and SHORT must
   both be powers of two.  The associated string constants must be set
   accordingly, for use in constructing the assembler instructions. */
#define LONG 8192
#define LONGx1 "8192"
#define LONGx2 "16384"
#define SHORT 256
#define SHORTx1 "256"
#define SHORTx2 "512"

/* Tables for hardware crc that shift a crc by LONG and SHORT zeros. */
static uint32_t crc32c_long[4][256];
static uint32_t crc32c_short[4][256];

/* Initialize tables for shifting crcs. */
static void crc32c_init_hw(void)
{
    crc32c_zeros(crc32c_long, LONG);
    crc32c_zeros(crc32c_short, SHORT);
}

/* Compute CRC-32C using the Intel hardware instruction. */
static uint32_t crc32c_hw(uint32_t crc, const void *buf, size_t len)
{
    const unsigned char *next = buf;
    const unsigned char *end;
    uint64_t crc0, crc1, crc2;      /* need to be 64 bits for crc32q */

    /* pre-process the crc */
    crc0 = crc ^ 0xffffffff;

    /* compute the crc for up to seven leading bytes to bring the data pointer
       to an eight-byte boundary */
    while (len && ((uintptr_t)next & 7) != 0) {
        __asm__("crc32b\t" "(%1), %0"
                : "=r"(crc0)
                : "r"(next), "0"(crc0));
        next++;
        len--;
    }

    /* compute the crc on sets of LONG*3 bytes, executing three independent crc
       instructions, each on LONG bytes -- this is optimized for the Nehalem,
       Westmere, Sandy Bridge, and Ivy Bridge architectures, which have a
       throughput of one crc per cycle, but a latency of three cycles */
    while (len >= LONG*3) {
        crc1 = 0;
        crc2 = 0;
        end = next + LONG;
        do {
            __asm__("crc32q\t" "(%3), %0\n\t"
                    "crc32q\t" LONGx1 "(%3), %1\n\t"
                    "crc32q\t" LONGx2 "(%3), %2"
                    : "=r"(crc0), "=r"(crc1), "=r"(crc2)
                    : "r"(next), "0"(crc0), "1"(crc1), "2"(crc2));
            next += 8;
        } while (next < end);
        crc0 = crc32c_shift(crc32c_long, crc0) ^ crc1;
        crc0 = crc32c_shift(crc32c_long, crc0) ^ crc2;
        next += LONG*2;
        len -= LONG*3;
    }

    /* do the same thing, but now on SHORT*3 blocks for the remaining data less
       than a LONG*3 block */
    while (len >= SHORT*3) {
        crc1 = 0;
        crc2 = 0;
        end = next + SHORT;
        do {
            __asm__("crc32q\t" "(%3), %0\n\t"
                    "crc32q\t" SHORTx1 "(%3), %1\n\t"
                    "crc32q\t" SHORTx2 "(%3), %2"
                    : "=r"(crc0), "=r"(crc1), "=r"(crc2)
                    : "r"(next), "0"(crc0), "1"(crc1), "2"(crc2));
            next += 8;
        } while (next < end);
        crc0 = crc32c_shift(crc32c_short, crc0) ^ crc1;
        crc0 = crc32c_shift(crc32c_short, crc0) ^ crc2;
        next += SHORT*2;
        len -= SHORT*3;
    }

    /* compute the crc on the remaining eight-byte units less than a SHORT*3
       block */
    end = next + (len - (len & 7));
    while (next < end) {
        __asm__("crc32q\t" "(%1), %0"
                : "=r"(crc0)
                : "r"(next), "0"(crc0));
        next += 8;
    }
    len &= 7;

    /* compute the crc for up to seven trailing bytes */
    while (len) {
        __asm__("crc32b\t" "(%1), %0"
                : "=r"(crc0)
                : "r"(next), "0"(crc0));
        next++;
        len--;
    }

    /* return a post-processed crc */
    return (uint32_t)crc0 ^ 0xffffffff;
}

/* Check for SSE 4.2.  SSE 4.2 was first supported in Nehalem processors
   introduced in November, 2008.  This does not check for the existence of the
   cpuid instruction itself, which was introduced on the 486SL in 1992, so this
   will fail on earlier x86 processors.  cpuid works on all Pentium and later
   processors. */
#define SSE42(have) \
    do { \
        uint32_t eax, ecx; \
        eax = 1; \
        __asm__("cpuid" \
                : "=c"(ecx) \
                : "a"(eax) \
                : "%ebx", "%edx"); \
        (have) = (ecx >> 20) & 1; \
    } while (0)

#endif /* WITH_CRC32C_HW */

/* Compute a CRC-32C.  If the crc32 instruction is available, use the hardware
   version.  Otherwise, use the software version. */
uint32_t rd_crc32c(uint32_t crc, const void *buf, size_t len)
{
#if WITH_CRC32C_HW
        if (sse42)
                return crc32c_hw(crc, buf, len);
        else
#endif
                return crc32c_sw(crc, buf, len);
}

/**
 * @brief Populate shift tables once
 */
void rd_crc32c_global_init (void) {
#if WITH_CRC32C_HW
        SSE42(sse42);
        if (sse42)
                crc32c_init_hw();
        else
#endif
                crc32c_init_sw();
}

int unittest_rd_crc32c (void) {
        const char *buf =
"  This software is provided 'as-is', without any express or implied\n"
"  warranty.  In no event will the author be held liable for any damages\n"
"  arising from the use of this software.\n"
"\n"
"  Permission is granted to anyone to use this software for any purpose,\n"
"  including commercial applications, and to alter it and redistribute it\n"
"  freely, subject to the following restrictions:\n"
"\n"
"  1. The origin of this software must not be misrepresented; you must not\n"
"     claim that you wrote the original software. If you use this software\n"
"     in a product, an acknowledgment in the product documentation would be\n"
"     appreciated but is not required.\n"
"  2. Altered source versions must be plainly marked as such, and must not be\n"
"     misrepresented as being the original software.\n"
"  3. This notice may not be removed or altered from any source distribution.";
        const uint32_t expected_crc = 0x7dcde113;
        uint32_t crc;
        const char *how;

#if WITH_CRC32C_HW
        if (sse42)
                how = "hardware (SSE42)";
        else
                how = "software (SSE42 supported in build but not at runtime)";
#else
        how = "software";
#endif
        RD_UT_SAY("Calculate CRC32C using %s", how);

        crc = rd_crc32c(0, buf, strlen(buf));
        RD_UT_ASSERT(crc == expected_crc,
                     "Calculated CRC (%s) 0x%"PRIx32
                     " not matching expected CRC 0x%"PRIx32,
                     how, crc, expected_crc);

        /* Verify software version too, regardless of which
         * version was used above. */
        crc32c_init_sw();
        RD_UT_SAY("Calculate CRC32C using software");
        crc = crc32c_sw(0, buf, strlen(buf));
        RD_UT_ASSERT(crc == expected_crc,
                     "Calculated CRC (software) 0x%"PRIx32
                     " not matching expected CRC 0x%"PRIx32,
                     crc, expected_crc);

        RD_UT_PASS();
}


text:
package me.yamakaja.irc.client.network.event.packet;

import me.yamakaja.irc.client.network.packet.client.PacketClientError;

/**
 * Created by Yamakaja on 01.02.17.
 */
public class ErrorReceiveEvent extends PacketEvent<PacketClientError> {

}


text:
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;
using System.Threading;

namespace Nest
{
	public partial interface IElasticClient
	{
		IForceMergeResponse ForceMerge(Indices indices, Func<ForceMergeDescriptor, IForceMergeRequest> selector = null);

		/// <inheritdoc/>
		IForceMergeResponse ForceMerge(IForceMergeRequest request);

		/// <inheritdoc/>
		Task<IForceMergeResponse> ForceMergeAsync(Indices indices, Func<ForceMergeDescriptor, IForceMergeRequest> selector = null, CancellationToken cancellationToken = default(CancellationToken));

		/// <inheritdoc/>
		Task<IForceMergeResponse> ForceMergeAsync(IForceMergeRequest request, CancellationToken cancellationToken = default(CancellationToken));

	}

	public partial class ElasticClient
	{
		/// <inheritdoc/>
		public IForceMergeResponse ForceMerge(Indices indices, Func<ForceMergeDescriptor, IForceMergeRequest> selector = null) =>
			this.ForceMerge(selector.InvokeOrDefault(new ForceMergeDescriptor().Index(indices)));

		/// <inheritdoc/>
		public IForceMergeResponse ForceMerge(IForceMergeRequest request) =>
			this.Dispatcher.Dispatch<IForceMergeRequest, ForceMergeRequestParameters, ForceMergeResponse>(
				request,
				(p, d) => this.LowLevelDispatch.IndicesForcemergeDispatch<ForceMergeResponse>(p)
			);

		/// <inheritdoc/>
		public Task<IForceMergeResponse> ForceMergeAsync(Indices indices, Func<ForceMergeDescriptor, IForceMergeRequest> selector = null, CancellationToken cancellationToken = default(CancellationToken)) =>
			this.ForceMergeAsync(selector.InvokeOrDefault(new ForceMergeDescriptor().Index(indices)), cancellationToken);

		/// <inheritdoc/>
		public Task<IForceMergeResponse> ForceMergeAsync(IForceMergeRequest request, CancellationToken cancellationToken = default(CancellationToken)) =>
			this.Dispatcher.DispatchAsync<IForceMergeRequest, ForceMergeRequestParameters, ForceMergeResponse, IForceMergeResponse>(
				request,
				cancellationToken,
				(p, d, c) => this.LowLevelDispatch.IndicesForcemergeDispatchAsync<ForceMergeResponse>(p, c)
			);
	}
}


text:
title: Human Enhancers
taxonomy:
    category: docs
---

# FANTOM5 Human Enhancers

#### This section describes the [SlideBase tool for FANTOM5 human enhancers](http://slidebase.binf.ku.dk/human_enhancers)


text:
package com.google.ads.googleads.v12.errors;

public final class PolicyFindingErrorProto {
  private PolicyFindingErrorProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v12_errors_PolicyFindingErrorEnum_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v12_errors_PolicyFindingErrorEnum_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n:google/ads/googleads/v12/errors/policy" +
      "_finding_error.proto\022\037google.ads.googlea" +
      "ds.v12.errors\"|\n\026PolicyFindingErrorEnum\"" +
      "b\n\022PolicyFindingError\022\017\n\013UNSPECIFIED\020\000\022\013" +
      "\n\007UNKNOWN\020\001\022\022\n\016POLICY_FINDING\020\002\022\032\n\026POLIC" +
      "Y_TOPIC_NOT_FOUND\020\003B\367\001\n#com.google.ads.g" +
      "oogleads.v12.errorsB\027PolicyFindingErrorP" +
      "rotoP\001ZEgoogle.golang.org/genproto/googl" +
      "eapis/ads/googleads/v12/errors;errors\242\002\003" +
      "GAA\252\002\037Google.Ads.GoogleAds.V12.Errors\312\002\037" +
      "Google\\Ads\\GoogleAds\\V12\\Errors\352\002#Google" +
      "::Ads::GoogleAds::V12::Errorsb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        });
    internal_static_google_ads_googleads_v12_errors_PolicyFindingErrorEnum_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v12_errors_PolicyFindingErrorEnum_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v12_errors_PolicyFindingErrorEnum_descriptor,
        new java.lang.String[] { });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
package broker

import (
	"bytes"
	"errors"
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/Jeffail/benthos/v3/internal/component/metrics"
	"github.com/Jeffail/benthos/v3/internal/component/output"
	"github.com/Jeffail/benthos/v3/internal/log"
	"github.com/Jeffail/benthos/v3/internal/message"
)

var _ output.Streamed = &FanOut{}

//------------------------------------------------------------------------------

func TestBasicFanOut(t *testing.T) {
	nOutputs, nMsgs := 10, 1000

	outputs := []output.Streamed{}
	mockOutputs := []*MockOutputType{}

	for i := 0; i < nOutputs; i++ {
		mockOutputs = append(mockOutputs, &MockOutputType{})
		outputs = append(outputs, mockOutputs[i])
	}

	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Error(err)
		return
	}

	if !oTM.Connected() {
		t.Error("Not connected")
	}

	for i := 0; i < nMsgs; i++ {
		content := [][]byte{[]byte(fmt.Sprintf("hello world %v", i))}
		select {
		case readChan <- message.NewTransaction(message.QuickBatch(content), resChan):
		case <-time.After(time.Second):
			t.Errorf("Timed out waiting for broker send")
			return
		}
		resChanSlice := []chan<- error{}
		for j := 0; j < nOutputs; j++ {
			var ts message.Transaction
			select {
			case ts = <-mockOutputs[j].TChan:
				if !bytes.Equal(ts.Payload.Get(0).Get(), content[0]) {
					t.Errorf("Wrong content returned %s != %s", ts.Payload.Get(0).Get(), content[0])
				}
				resChanSlice = append(resChanSlice, ts.ResponseChan)
			case <-time.After(time.Second):
				t.Errorf("Timed out waiting for broker propagate")
				return
			}
		}
		for j := 0; j < nOutputs; j++ {
			select {
			case resChanSlice[j] <- nil:
			case <-time.After(time.Second):
				t.Errorf("Timed out responding to broker")
				return
			}
		}
		select {
		case res := <-resChan:
			if res != nil {
				t.Errorf("Received unexpected errors from broker: %v", res)
			}
		case <-time.After(time.Second):
			t.Errorf("Timed out responding to broker")
			return
		}
	}

	oTM.CloseAsync()

	if err := oTM.WaitForClose(time.Second * 5); err != nil {
		t.Error(err)
	}
}

func TestFanOutBackPressure(t *testing.T) {
	mockOne := MockOutputType{}
	mockTwo := MockOutputType{}

	outputs := []output.Streamed{&mockOne, &mockTwo}
	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(outputs, log.Noop(), metrics.Noop())
	if err != nil {
		t.Fatal(err)
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Fatal(err)
	}

	wg := sync.WaitGroup{}
	wg.Add(1)
	doneChan := make(chan struct{})
	go func() {
		defer wg.Done()
		// Consume as fast as possible from mock one
		for {
			select {
			case ts := <-mockOne.TChan:
				select {
				case ts.ResponseChan <- nil:
				case <-doneChan:
					return
				}
			case <-doneChan:
				return
			}
		}
	}()

	i := 0
bpLoop:
	for ; i < 1000; i++ {
		select {
		case readChan <- message.NewTransaction(message.QuickBatch([][]byte{[]byte("hello world")}), resChan):
		case <-time.After(time.Millisecond * 200):
			break bpLoop
		}
	}
	if i > 500 {
		t.Error("We shouldn't be capable of dumping this many messages into a blocked broker")
	}

	close(readChan)
	close(doneChan)
	wg.Wait()
}

func TestFanOutAtLeastOnce(t *testing.T) {
	mockOne := MockOutputType{}
	mockTwo := MockOutputType{}

	outputs := []output.Streamed{&mockOne, &mockTwo}
	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err == nil {
		t.Error("Expected error on duplicate receive call")
	}

	select {
	case readChan <- message.NewTransaction(message.QuickBatch([][]byte{[]byte("hello world")}), resChan):
	case <-time.After(time.Second):
		t.Error("Timed out waiting for broker send")
		return
	}
	var ts1, ts2 message.Transaction
	select {
	case ts1 = <-mockOne.TChan:
	case <-time.After(time.Second):
		t.Error("Timed out waiting for mockOne")
		return
	}
	select {
	case ts2 = <-mockTwo.TChan:
	case <-time.After(time.Second):
		t.Error("Timed out waiting for mockOne")
		return
	}
	select {
	case ts1.ResponseChan <- nil:
	case <-time.After(time.Second):
		t.Error("Timed out responding to broker")
		return
	}
	select {
	case ts2.ResponseChan <- errors.New("this is a test"):
	case <-time.After(time.Second):
		t.Error("Timed out responding to broker")
		return
	}
	select {
	case <-mockOne.TChan:
		t.Error("Received duplicate message to mockOne")
	case ts2 = <-mockTwo.TChan:
	case <-resChan:
		t.Error("Received premature response from broker")
	case <-time.After(time.Second):
		t.Error("Timed out waiting for mockTwo")
		return
	}
	select {
	case ts2.ResponseChan <- nil:
	case <-time.After(time.Second):
		t.Error("Timed out responding to broker")
		return
	}
	select {
	case res := <-resChan:
		if res != nil {
			t.Errorf("Fan out returned error %v", res)
		}
	case <-time.After(time.Second):
		t.Errorf("Timed out responding to broker")
		return
	}

	close(readChan)

	if err := oTM.WaitForClose(time.Second * 5); err != nil {
		t.Error(err)
	}
}

func TestFanOutShutDownFromErrorResponse(t *testing.T) {
	outputs := []output.Streamed{}
	mockOutput := &MockOutputType{}
	outputs = append(outputs, mockOutput)
	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Error(err)
		return
	}

	select {
	case readChan <- message.NewTransaction(message.QuickBatch(nil), resChan):
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg send")
	}

	var ts message.Transaction
	var open bool
	select {
	case ts, open = <-mockOutput.TChan:
		if !open {
			t.Error("fan out output closed early")
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg rcv")
	}

	select {
	case ts.ResponseChan <- errors.New("test"):
	case <-time.After(time.Second):
		t.Error("Timed out waiting for res send")
	}

	oTM.CloseAsync()
	if err := oTM.WaitForClose(time.Second); err != nil {
		t.Error(err)
	}

	select {
	case _, open := <-mockOutput.TChan:
		if open {
			t.Error("fan out output still open after closure")
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg rcv")
	}
}

func TestFanOutShutDownFromReceive(t *testing.T) {
	outputs := []output.Streamed{}
	mockOutput := &MockOutputType{}
	outputs = append(outputs, mockOutput)
	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Error(err)
		return
	}

	select {
	case readChan <- message.NewTransaction(message.QuickBatch(nil), resChan):
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg send")
	}

	select {
	case _, open := <-mockOutput.TChan:
		if !open {
			t.Error("fan out output closed early")
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg rcv")
	}

	oTM.CloseAsync()
	if err := oTM.WaitForClose(time.Second); err != nil {
		t.Error(err)
	}

	select {
	case _, open := <-mockOutput.TChan:
		if open {
			t.Error("fan out output still open after closure")
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg rcv")
	}
}

func TestFanOutShutDownFromSend(t *testing.T) {
	outputs := []output.Streamed{}
	mockOutput := &MockOutputType{}
	outputs = append(outputs, mockOutput)
	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		t.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		t.Error(err)
		return
	}

	select {
	case readChan <- message.NewTransaction(message.QuickBatch(nil), resChan):
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg send")
	}

	oTM.CloseAsync()
	if err := oTM.WaitForClose(time.Second); err != nil {
		t.Error(err)
	}

	select {
	case _, open := <-mockOutput.TChan:
		if open {
			t.Error("fan out output still open after closure")
		}
	case <-time.After(time.Second):
		t.Error("Timed out waiting for msg rcv")
	}
}

//------------------------------------------------------------------------------

func BenchmarkBasicFanOut(b *testing.B) {
	nOutputs, nMsgs := 3, b.N

	outputs := []output.Streamed{}
	mockOutputs := []*MockOutputType{}

	for i := 0; i < nOutputs; i++ {
		mockOutputs = append(mockOutputs, &MockOutputType{})
		outputs = append(outputs, mockOutputs[i])
	}

	readChan := make(chan message.Transaction)
	resChan := make(chan error)

	oTM, err := NewFanOut(
		outputs, log.Noop(), metrics.Noop(),
	)
	if err != nil {
		b.Error(err)
		return
	}
	if err = oTM.Consume(readChan); err != nil {
		b.Error(err)
		return
	}

	content := [][]byte{[]byte("hello world")}
	rChanSlice := make([]chan<- error, nOutputs)

	b.ReportAllocs()
	b.StartTimer()

	for i := 0; i < nMsgs; i++ {
		readChan <- message.NewTransaction(message.QuickBatch(content), resChan)
		for j := 0; j < nOutputs; j++ {
			ts := <-mockOutputs[j].TChan
			rChanSlice[j] = ts.ResponseChan
		}
		for j := 0; j < nOutputs; j++ {
			rChanSlice[j] <- nil
		}
		res := <-resChan
		if res != nil {
			b.Errorf("Received unexpected errors from broker: %v", res)
		}
	}

	b.StopTimer()
}

//------------------------------------------------------------------------------


text:
class ZoomUrlValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if Gitlab::ZoomLinkExtractor.new(value).links.size == 1

    record.errors.add(:url, 'must contain one valid Zoom URL')
  end
end