text:
use std::fmt;

use tipb::{ColumnInfo, FieldType};

use crate::error::DataTypeError;

/// Valid values of `tipb::FieldType::tp` and `tipb::ColumnInfo::tp`.
///
/// `FieldType` is the field type of a column defined by schema.
///
/// `ColumnInfo` describes a column. It contains `FieldType` and some other column specific
/// information. However for historical reasons, fields in `FieldType` (for example, `tp`)
/// are flattened into `ColumnInfo`. Semantically these fields are identical.
///
/// Please refer to [mysql/type.go](https://github.com/pingcap/parser/blob/master/mysql/type.go).
#[derive(PartialEq, Debug, Clone, Copy)]
#[repr(i32)]
pub enum FieldTypeTp {
    Unspecified = 0, // Default
    Tiny = 1,
    Short = 2,
    Long = 3,
    Float = 4,
    Double = 5,
    Null = 6,
    Timestamp = 7,
    LongLong = 8,
    Int24 = 9,
    Date = 10,
    Duration = 11,
    DateTime = 12,
    Year = 13,
    NewDate = 14,
    VarChar = 15,
    Bit = 16,
    JSON = 0xf5,
    NewDecimal = 0xf6,
    Enum = 0xf7,
    Set = 0xf8,
    TinyBlob = 0xf9,
    MediumBlob = 0xfa,
    LongBlob = 0xfb,
    Blob = 0xfc,
    VarString = 0xfd,
    String = 0xfe,
    Geometry = 0xff,
}

impl FieldTypeTp {
    fn from_i32(i: i32) -> Option<FieldTypeTp> {
        if (i >= FieldTypeTp::Unspecified as i32 && i <= FieldTypeTp::Bit as i32)
            || (i >= FieldTypeTp::JSON as i32 && i <= FieldTypeTp::Geometry as i32)
        {
            Some(unsafe { ::std::mem::transmute::<i32, FieldTypeTp>(i) })
        } else {
            None
        }
    }

    pub fn from_u8(i: u8) -> Option<FieldTypeTp> {
        if i <= FieldTypeTp::Bit as u8 || i >= FieldTypeTp::JSON as u8 {
            Some(unsafe { ::std::mem::transmute::<i32, FieldTypeTp>(i32::from(i)) })
        } else {
            None
        }
    }

    pub fn to_u8(self) -> Option<u8> {
        Some(self as i32 as u8)
    }
}

impl fmt::Display for FieldTypeTp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl From<FieldTypeTp> for FieldType {
    fn from(fp: FieldTypeTp) -> FieldType {
        let mut ft = FieldType::default();
        ft.as_mut_accessor().set_tp(fp);
        ft
    }
}

impl From<FieldTypeTp> for ColumnInfo {
    fn from(fp: FieldTypeTp) -> ColumnInfo {
        let mut ft = ColumnInfo::default();
        ft.as_mut_accessor().set_tp(fp);
        ft
    }
}

/// Valid values of `tipb::FieldType::collate` and
/// `tipb::ColumnInfo::collation`.
///
/// Legacy Utf8Bin collator (was the default) does not pad. For compatibility,
/// all new collation with padding behavior is negative.
///
/// Please refer to [mysql/charset.go](https://github.com/pingcap/parser/blob/master/mysql/charset.go).
#[derive(PartialEq, Debug, Clone, Copy)]
#[repr(i32)]
pub enum Collation {
    Binary = 63,
    Utf8Mb4Bin = -46,
    Utf8Mb4BinNoPadding = 46,
    Utf8Mb4GeneralCi = -45,
    Utf8Mb4UnicodeCi = -224,
    Latin1Bin = -47,
    GbkBin = -87,
    GbkChineseCi = -28,
}

impl Collation {
    /// Parse from collation id.
    ///
    /// These are magic numbers defined in tidb, where positive numbers are for legacy
    /// compatibility, and all new clusters with padding configuration enabled will
    /// use negative numbers to indicate the padding behavior.
    pub fn from_i32(n: i32) -> Result<Self, DataTypeError> {
        match n {
            -33 | -45 => Ok(Collation::Utf8Mb4GeneralCi),
            -46 | -83 | -65 => Ok(Collation::Utf8Mb4Bin),
            -47 => Ok(Collation::Latin1Bin),
            -63 | 63 | 47 => Ok(Collation::Binary),
            -224 | -192 => Ok(Collation::Utf8Mb4UnicodeCi),
            -87 => Ok(Collation::GbkBin),
            -28 => Ok(Collation::GbkChineseCi),
            n if n >= 0 => Ok(Collation::Utf8Mb4BinNoPadding),
            n => Err(DataTypeError::UnsupportedCollation { code: n }),
        }
    }

    pub fn is_bin_collation(&self) -> bool {
        matches!(self, Collation::Utf8Mb4Bin | Collation::Latin1Bin)
    }
}

impl fmt::Display for Collation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Charset {
    UTF8,
    UTF8Mb4,
    Latin1,
    GBK,
    Binary,
    Ascii,
}

impl Charset {
    pub fn from_name(name: &str) -> Result<Self, DataTypeError> {
        match name {
            "utf8mb4" => Ok(Charset::UTF8Mb4),
            "utf8" => Ok(Charset::UTF8),
            "latin1" => Ok(Charset::Latin1),
            "gbk" => Ok(Charset::GBK),
            "binary" => Ok(Charset::Binary),
            "ascii" => Ok(Charset::Ascii),
            _ => Err(DataTypeError::UnsupportedCharset {
                name: String::from(name),
            }),
        }
    }
}

bitflags! {
    pub struct FieldTypeFlag: u32 {
        /// Field can't be NULL.
        const NOT_NULL = 1;

        /// Field is unsigned.
        const UNSIGNED = 1 << 5;

        /// Field is binary.
        const BINARY = 1 << 7;

        /// Internal: Used when we want to parse string to JSON in CAST.
        const PARSE_TO_JSON = 1 << 18;

        /// Internal: Used for telling boolean literal from integer.
        const IS_BOOLEAN = 1 << 19;

        /// Internal: Used for inferring enum eval type.
        const ENUM_SET_AS_INT = 1 << 21;
    }
}

/// A uniform `FieldType` access interface for `FieldType` and `ColumnInfo`.
pub trait FieldTypeAccessor {
    fn tp(&self) -> FieldTypeTp;

    fn set_tp(&mut self, tp: FieldTypeTp) -> &mut dyn FieldTypeAccessor;

    fn flag(&self) -> FieldTypeFlag;

    fn set_flag(&mut self, flag: FieldTypeFlag) -> &mut dyn FieldTypeAccessor;

    fn flen(&self) -> isize;

    fn set_flen(&mut self, flen: isize) -> &mut dyn FieldTypeAccessor;

    fn decimal(&self) -> isize;

    fn set_decimal(&mut self, decimal: isize) -> &mut dyn FieldTypeAccessor;

    fn collation(&self) -> Result<Collation, DataTypeError>;

    fn set_collation(&mut self, collation: Collation) -> &mut dyn FieldTypeAccessor;

    /// Convert reference to `FieldTypeAccessor` interface. Useful when an implementer
    /// provides inherent methods with the same name as the accessor trait methods.
    fn as_accessor(&self) -> &dyn FieldTypeAccessor
    where
        Self: Sized,
    {
        self as &dyn FieldTypeAccessor
    }

    /// Convert mutable reference to `FieldTypeAccessor` interface.
    fn as_mut_accessor(&mut self) -> &mut dyn FieldTypeAccessor
    where
        Self: Sized,
    {
        self as &mut dyn FieldTypeAccessor
    }

    /// Whether this type is a hybrid type, which can represent different types of value in
    /// specific context.
    ///
    /// Please refer to `Hybrid` in TiDB.
    #[inline]
    fn is_hybrid(&self) -> bool {
        let tp = self.tp();
        tp == FieldTypeTp::Enum || tp == FieldTypeTp::Bit || tp == FieldTypeTp::Set
    }

    /// Whether this type is a blob type.
    ///
    /// Please refer to `IsTypeBlob` in TiDB.
    #[inline]
    fn is_blob_like(&self) -> bool {
        let tp = self.tp();
        tp == FieldTypeTp::TinyBlob
            || tp == FieldTypeTp::MediumBlob
            || tp == FieldTypeTp::Blob
            || tp == FieldTypeTp::LongBlob
    }

    /// Whether this type is a char-like type like a string type or a varchar type.
    ///
    /// Please refer to `IsTypeChar` in TiDB.
    #[inline]
    fn is_char_like(&self) -> bool {
        let tp = self.tp();
        tp == FieldTypeTp::String || tp == FieldTypeTp::VarChar
    }

    /// Whether this type is a varchar-like type like a varstring type or a varchar type.
    ///
    /// Please refer to `IsTypeVarchar` in TiDB.
    #[inline]
    fn is_varchar_like(&self) -> bool {
        let tp = self.tp();
        tp == FieldTypeTp::VarString || tp == FieldTypeTp::VarChar
    }

    /// Whether this type is a string-like type.
    ///
    /// Please refer to `IsString` in TiDB.
    #[inline]
    fn is_string_like(&self) -> bool {
        self.is_blob_like()
            || self.is_char_like()
            || self.is_varchar_like()
            || self.tp() == FieldTypeTp::Unspecified
    }

    /// Whether this type is a binary-string-like type.
    ///
    /// Please refer to `IsBinaryStr` in TiDB.
    #[inline]
    fn is_binary_string_like(&self) -> bool {
        self.collation()
            .map(|col| col == Collation::Binary)
            .unwrap_or(false)
            && self.is_string_like()
    }

    /// Whether this type is a non-binary-string-like type.
    ///
    /// Please refer to `IsNonBinaryStr` in TiDB.
    #[inline]
    fn is_non_binary_string_like(&self) -> bool {
        self.collation()
            .map(|col| col != Collation::Binary)
            .unwrap_or(true)
            && self.is_string_like()
    }

    /// Whether the flag contains `FieldTypeFlag::UNSIGNED`
    #[inline]
    fn is_unsigned(&self) -> bool {
        self.flag().contains(FieldTypeFlag::UNSIGNED)
    }

    /// Whether the flag contains `FieldTypeFlag::IS_BOOLEAN`
    #[inline]
    fn is_bool(&self) -> bool {
        self.flag().contains(FieldTypeFlag::IS_BOOLEAN)
    }

    #[inline]
    fn need_restored_data(&self) -> bool {
        self.is_non_binary_string_like()
            && (!self
                .collation()
                .map(|col| col.is_bin_collation())
                .unwrap_or(false)
                || self.is_varchar_like())
    }
}

impl FieldTypeAccessor for FieldType {
    #[inline]
    fn tp(&self) -> FieldTypeTp {
        FieldTypeTp::from_i32(self.get_tp()).unwrap_or(FieldTypeTp::Unspecified)
    }

    #[inline]
    fn set_tp(&mut self, tp: FieldTypeTp) -> &mut dyn FieldTypeAccessor {
        FieldType::set_tp(self, tp as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn flag(&self) -> FieldTypeFlag {
        FieldTypeFlag::from_bits_truncate(self.get_flag())
    }

    #[inline]
    fn set_flag(&mut self, flag: FieldTypeFlag) -> &mut dyn FieldTypeAccessor {
        FieldType::set_flag(self, flag.bits());
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn flen(&self) -> isize {
        self.get_flen() as isize
    }

    #[inline]
    fn set_flen(&mut self, flen: isize) -> &mut dyn FieldTypeAccessor {
        FieldType::set_flen(self, flen as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn decimal(&self) -> isize {
        self.get_decimal() as isize
    }

    #[inline]
    fn set_decimal(&mut self, decimal: isize) -> &mut dyn FieldTypeAccessor {
        FieldType::set_decimal(self, decimal as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn collation(&self) -> Result<Collation, DataTypeError> {
        Collation::from_i32(self.get_collate())
    }

    #[inline]
    fn set_collation(&mut self, collation: Collation) -> &mut dyn FieldTypeAccessor {
        FieldType::set_collate(self, collation as i32);
        self as &mut dyn FieldTypeAccessor
    }
}

impl FieldTypeAccessor for ColumnInfo {
    #[inline]
    fn tp(&self) -> FieldTypeTp {
        FieldTypeTp::from_i32(self.get_tp()).unwrap_or(FieldTypeTp::Unspecified)
    }

    #[inline]
    fn set_tp(&mut self, tp: FieldTypeTp) -> &mut dyn FieldTypeAccessor {
        ColumnInfo::set_tp(self, tp as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn flag(&self) -> FieldTypeFlag {
        FieldTypeFlag::from_bits_truncate(self.get_flag() as u32)
    }

    #[inline]
    fn set_flag(&mut self, flag: FieldTypeFlag) -> &mut dyn FieldTypeAccessor {
        ColumnInfo::set_flag(self, flag.bits() as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn flen(&self) -> isize {
        self.get_column_len() as isize
    }

    #[inline]
    fn set_flen(&mut self, flen: isize) -> &mut dyn FieldTypeAccessor {
        ColumnInfo::set_column_len(self, flen as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn decimal(&self) -> isize {
        self.get_decimal() as isize
    }

    #[inline]
    fn set_decimal(&mut self, decimal: isize) -> &mut dyn FieldTypeAccessor {
        ColumnInfo::set_decimal(self, decimal as i32);
        self as &mut dyn FieldTypeAccessor
    }

    #[inline]
    fn collation(&self) -> Result<Collation, DataTypeError> {
        Collation::from_i32(self.get_collation())
    }

    #[inline]
    fn set_collation(&mut self, collation: Collation) -> &mut dyn FieldTypeAccessor {
        ColumnInfo::set_collation(self, collation as i32);
        self as &mut dyn FieldTypeAccessor
    }
}

#[cfg(test)]
mod tests {
    use std::i32;

    use super::*;

    fn field_types() -> Vec<FieldTypeTp> {
        vec![
            FieldTypeTp::Unspecified,
            FieldTypeTp::Tiny,
            FieldTypeTp::Short,
            FieldTypeTp::Long,
            FieldTypeTp::Float,
            FieldTypeTp::Double,
            FieldTypeTp::Null,
            FieldTypeTp::Timestamp,
            FieldTypeTp::LongLong,
            FieldTypeTp::Int24,
            FieldTypeTp::Date,
            FieldTypeTp::Duration,
            FieldTypeTp::DateTime,
            FieldTypeTp::Year,
            FieldTypeTp::NewDate,
            FieldTypeTp::VarChar,
            FieldTypeTp::Bit,
            FieldTypeTp::JSON,
            FieldTypeTp::NewDecimal,
            FieldTypeTp::Enum,
            FieldTypeTp::Set,
            FieldTypeTp::TinyBlob,
            FieldTypeTp::MediumBlob,
            FieldTypeTp::LongBlob,
            FieldTypeTp::Blob,
            FieldTypeTp::VarString,
            FieldTypeTp::String,
            FieldTypeTp::Geometry,
        ]
    }

    #[test]
    fn test_field_type_from_i32() {
        for ft in field_types() {
            assert_eq!(FieldTypeTp::from_i32(ft as i32), Some(ft));
        }

        let fail_cases = vec![-1, -42, i32::MIN, i32::MAX, 17, 42, 0xf4, 0x100];

        for fail_case in fail_cases {
            assert_eq!(FieldTypeTp::from_i32(fail_case), None);
        }
    }

    #[test]
    fn test_field_type_from_u8() {
        for ft in field_types() {
            assert_eq!(FieldTypeTp::from_u8(ft as i32 as u8), Some(ft));
        }

        for fail_case in 17u8..=0xf4u8 {
            assert_eq!(FieldTypeTp::from_u8(fail_case), None);
        }
    }

    #[test]
    fn test_field_type_to_u8() {
        for ft in field_types() {
            assert_eq!(FieldTypeTp::from_u8(ft.to_u8().unwrap()), Some(ft));
        }
    }

    #[test]
    fn test_collate_from_i32() {
        let cases = vec![
            (33, Some(Collation::Utf8Mb4BinNoPadding)),
            (-33, Some(Collation::Utf8Mb4GeneralCi)),
            (45, Some(Collation::Utf8Mb4BinNoPadding)),
            (-45, Some(Collation::Utf8Mb4GeneralCi)),
            (46, Some(Collation::Utf8Mb4BinNoPadding)),
            (-46, Some(Collation::Utf8Mb4Bin)),
            (63, Some(Collation::Binary)),
            (-63, Some(Collation::Binary)),
            (83, Some(Collation::Utf8Mb4BinNoPadding)),
            (-83, Some(Collation::Utf8Mb4Bin)),
            (255, Some(Collation::Utf8Mb4BinNoPadding)),
            (-255, None),
            (i32::MAX, Some(Collation::Utf8Mb4BinNoPadding)),
            (i32::MIN, None),
            (-192, Some(Collation::Utf8Mb4UnicodeCi)),
            (-224, Some(Collation::Utf8Mb4UnicodeCi)),
            (-28, Some(Collation::GbkChineseCi)),
            (-87, Some(Collation::GbkBin)),
        ];

        for (collate, expected) in cases {
            let mut ft = tipb::FieldType::default();
            ft.set_collate(collate);

            let coll = ft.as_accessor().collation();

            if let Some(c) = expected {
                assert_eq!(coll.unwrap(), c);
            } else {
                assert!(coll.is_err());
            }
        }
    }

    #[test]
    fn test_charset_from_str() {
        let cases = vec![
            ("gbk", Some(Charset::GBK)),
            ("utf8mb4", Some(Charset::UTF8Mb4)),
            ("utf8", Some(Charset::UTF8)),
            ("binary", Some(Charset::Binary)),
            ("latin1", Some(Charset::Latin1)),
            ("ascii", Some(Charset::Ascii)),
            ("somethingwrong", None),
        ];

        for (charset, expected) in cases {
            let mut ft = tipb::FieldType::default();
            ft.set_charset(charset.to_string());

            let charset = Charset::from_name(ft.get_charset());

            if let Some(c) = expected {
                assert_eq!(charset.unwrap(), c);
            } else {
                assert!(charset.is_err());
            }
        }
    }
}


text:
#ifndef HPP_PSI_TVM_FUNCTION
#define HPP_PSI_TVM_FUNCTION

#include "Core.hpp"
#include "Functional.hpp"
#include "ValueList.hpp"

#include <boost/unordered_map.hpp>

namespace Psi {
  namespace Tvm {
    class FunctionType;
    class Block;

    /**
     * \brief Base class for terms which belong to a block.
     */
    class PSI_TVM_EXPORT_DEBUG BlockMember : public Value {
      friend class Block;

    public:
      /// \brief Get the block this term is part of.
      ValuePtr<Block> block() {return ValuePtr<Block>(m_block);}
      /// \brief Get a raw pointer to the block this term is part of.
      Block* block_ptr() {return m_block;}
      /// \brief Get the function the block this is in is part of
      ValuePtr<Function> function();

      template<typename V> static void visit(V& v) {visit_base<Value>(v);}

      virtual Value* disassembler_source();

    protected:
      BlockMember(TermType term_type, const ValuePtr<>& type, const SourceLocation& location);

    private:
      template<typename T, boost::intrusive::list_member_hook<> T::*> friend class ValueList;
      void list_release() {m_block = NULL;}
      Block *m_block;
    };

    class PSI_TVM_EXPORT_DEBUG InstructionVisitor {
    public:
      virtual void next(ValuePtr<>& ptr) = 0;
    };

    class Instruction;

    class PSI_TVM_EXPORT_DEBUG InstructionVisitorWrapper : public ValuePtrVisitorBase<InstructionVisitorWrapper> {
      InstructionVisitor *m_callback;
    public:
      InstructionVisitorWrapper(InstructionVisitor *callback) : m_callback(callback) {}

      void visit_ptr(ValuePtr<>& ptr) {
        m_callback->next(ptr);
      }

      template<typename T> void visit_ptr(ValuePtr<T>& ptr) {
        ValuePtr<> copy(ptr);
        m_callback->next(copy);
        ptr = value_cast<T>(copy);
      }

      template<typename T> bool do_visit_base(VisitorTag<T>) {return !boost::is_same<T,Instruction>::value;}
    };

    /**
     * \brief Instruction term. Per-instruction funtionality is
     * created by implementing InstructionTermBackend and wrapping
     * that in InstructionTerm.
     */
    class PSI_TVM_EXPORT_DEBUG Instruction : public BlockMember {
      friend class Block;

    public:
      const char *operation_name() const {return m_operation;}
      virtual void instruction_visit(InstructionVisitor& visitor) = 0;

      void remove();

      static bool isa_impl(const Value& ptr) {return ptr.term_type() == term_instruction;}
      template<typename V> static void visit(V& v) {visit_base<BlockMember>(v);}

      virtual void type_check() = 0;

    protected:
      Instruction(const ValuePtr<>& type, const char *operation,
                  const SourceLocation& location);

      void require_available(const ValuePtr<>& value);
      virtual void check_source_hook(CheckSourceParameter& parameter);

    private:
      const char *m_operation;
      boost::intrusive::list_member_hook<> m_instruction_list_hook;
    };

    /**
     * \brief Base class for instructions which terminate blocks.
     */
    class PSI_TVM_EXPORT_DEBUG TerminatorInstruction : public Instruction {
    public:
      TerminatorInstruction(Context& context, const char *operation, const SourceLocation& location);

      virtual std::vector<ValuePtr<Block> > successors() = 0;

      static bool isa_impl(const Value& ptr);
      template<typename V> static void visit(V& v) {visit_base<Instruction>(v);}
    };

    template<typename T>
    OperationSetup instruction_setup() {
      return OperationSetup(T::operation);
    }

    template<typename T, typename U>
    OperationSetup instruction_setup(const U& x) {
      return instruction_setup<T>()(x);
    }

#define PSI_TVM_INSTRUCTION_DECL(Type) \
    PSI_TVM_VALUE_DECL(Type) \
  public: \
    PSI_TVM_EXPORT static const char operation[]; \
    virtual void type_check(); \
    virtual void instruction_visit(InstructionVisitor& callback); \
    template<typename V> static void visit(V& v); \
    static bool isa_impl(const Value& val) {return (val.term_type() == term_instruction) && (operation == static_cast<const Type&>(val).operation_name());} \

#define PSI_TVM_INSTRUCTION_IMPL(Type,Base,Name) \
    PSI_TVM_VALUE_IMPL(Type,Base) \
    \
    const char Type::operation[] = #Name; \
    \
    void Type::instruction_visit(InstructionVisitor& visitor) { \
      InstructionVisitorWrapper vw(&visitor); \
      boost::array<Type*,1> c = {{this}}; \
      visit_members(vw, c); \
    }

    /**
     * Describes incoming edges for Phi nodes.
     */
    struct PhiEdge {
      ValuePtr<Block> block;
      ValuePtr<> value;
    };

    template<typename V>
    void visit(V& v, VisitorTag<PhiEdge>) {
      v("block", &PhiEdge::block)
      ("value", &PhiEdge::value);
    }

    /**
     * \brief Phi node. These are used to unify values from different
     * predecessors on entry to a block.
     *
     * \sa http://en.wikipedia.org/wiki/Static_single_assignment_form
     */
    class PSI_TVM_EXPORT_DEBUG Phi : public BlockMember {
      PSI_TVM_VALUE_DECL(Phi)
      friend class Block;

    public:
      PSI_TVM_EXPORT void add_edge(const ValuePtr<Block>& block, const ValuePtr<>& value);
      /// \brief Get incoming edge list
      const std::vector<PhiEdge>& edges() const {return m_edges;}

      /// \brief Get the value from a specific source block.
      PSI_TVM_EXPORT ValuePtr<> incoming_value_from(const ValuePtr<Block>& block);

      void remove();

      static bool isa_impl(const Value& v) {return v.term_type() == term_phi;}
      template<typename V> static void visit(V& v);

    private:
      Phi(const ValuePtr<>& type, const SourceLocation& location);
      std::vector<PhiEdge> m_edges;
      boost::intrusive::list_member_hook<> m_phi_list_hook;
      virtual void check_source_hook(CheckSourceParameter& parameter);
    };

    /**
     * \brief Block (list of instructions) inside a function. The
     * value of this term is the label used to jump to this block.
     */
    class PSI_TVM_EXPORT_DEBUG Block : public Value {
      PSI_TVM_VALUE_DECL(Block);
      friend class Function;
      friend class Instruction;

    public:
      typedef ValueList<Instruction, &Instruction::m_instruction_list_hook> InstructionList;
      typedef ValueList<Phi, &Phi::m_phi_list_hook> PhiList;

      PSI_TVM_EXPORT ValuePtr<Phi> insert_phi(const ValuePtr<>& type, const SourceLocation& location);
      PSI_TVM_EXPORT void insert_instruction(const ValuePtr<Instruction>& insn, const ValuePtr<Instruction>& before=ValuePtr<Instruction>());

      PSI_TVM_EXPORT void erase_phi(Phi& phi);
      PSI_TVM_EXPORT void erase_instruction(Instruction& instruction);

      const InstructionList& instructions() const {return m_instructions;}
      const PhiList& phi_nodes() const {return m_phi_nodes;}

      /** \brief Whether this block has been terminated so no more instructions can be added. */
      bool terminated() {return !m_instructions.empty() && isa<TerminatorInstruction>(m_instructions.back());}
      /** \brief Get the function which contains this block. */
      ValuePtr<Function> function() {return ValuePtr<Function>(m_function);}
      /** \brief Get a raw pointer to the function which contains this block. */
      Function* function_ptr() {return m_function;}
      /** \brief Get a pointer to the dominating block. */
      const ValuePtr<Block>& dominator() {return m_dominator;}
      /** \brief Get this block's catch list (this will be NULL for a regular block). */
      const ValuePtr<Block>& landing_pad() {return m_landing_pad;}
      /// \brief Whether this block is a landing pad.
      bool is_landing_pad() const {return m_is_landing_pad;}

      std::vector<ValuePtr<Block> > successors();

      bool dominated_by(Block *block);
      /// \copydoc dominated_by(Block*)
      bool dominated_by(const ValuePtr<Block>& block) {return dominated_by(block.get());}
      bool same_or_dominated_by(Block *block);
      /// \copydoc same_or_dominated_by(Block*)
      bool same_or_dominated_by(const ValuePtr<Block>& block) {return same_or_dominated_by(block.get());}

      virtual Value* disassembler_source();

      static ValuePtr<Block> common_dominator(const ValuePtr<Block>&, const ValuePtr<Block>&);
      static bool isa_impl(const Value& v) {return v.term_type() == term_block;}

      template<typename V> static void visit(V& v);

    private:
      Block(Function *function, const ValuePtr<Block>& dominator,
            bool is_landing_pad, const ValuePtr<Block>& landing_pad,
            const SourceLocation& location);
      InstructionList m_instructions;
      PhiList m_phi_nodes;

      Function *m_function;
      ValuePtr<Block> m_dominator;
      ValuePtr<Block> m_landing_pad;

      bool m_is_landing_pad;
      template<typename T, boost::intrusive::list_member_hook<> T::*> friend class ValueList;
      boost::intrusive::list_member_hook<> m_block_list_hook;
      void list_release() {m_function = NULL;}
      virtual void check_source_hook(CheckSourceParameter& parameter);
    };

    inline ValuePtr<Function> BlockMember::function() {return m_block ? m_block->function() : ValuePtr<Function>();}

    class Function;

    class PSI_TVM_EXPORT_DEBUG FunctionParameter : public Value {
      PSI_TVM_VALUE_DECL(FunctionParameter);
      friend class Function;
    public:
      ValuePtr<Function> function() {return ValuePtr<Function>(m_function);}
      Function *function_ptr() {return m_function;}
      bool parameter_phantom() {return m_phantom;}

      static bool isa_impl(const Value& ptr) {
        return ptr.term_type() == term_function_parameter;
      }

      virtual Value* disassembler_source();

      template<typename V> static void visit(V& v);

    private:
      FunctionParameter(Context& context, Function *function, const ValuePtr<>& type, bool phantom, const SourceLocation& location);
      bool m_phantom;

      virtual void check_source_hook(CheckSourceParameter& parameter);

      void list_release() {m_function = NULL;}
      Function *m_function;
      boost::intrusive::list_member_hook<> m_parameter_list_hook;
      template<typename T, boost::intrusive::list_member_hook<> T::*> friend class ValueList;
    };

    /**
     * \brief Function.
     */
    class PSI_TVM_EXPORT_DEBUG Function : public Global {
      PSI_TVM_VALUE_DECL(Function);
      friend class Module;
    public:
      typedef boost::unordered_multimap<ValuePtr<>, std::string> TermNameMap;
      typedef ValueList<FunctionParameter, &FunctionParameter::m_parameter_list_hook> ParameterList;
      typedef ValueList<Block, &Block::m_block_list_hook> BlockList;

      /**
       * Get the type of this function. This returns the raw function
       * type, whereas the actual type of this term is a pointer to
       * that type.
       */
      PSI_TVM_EXPORT ValuePtr<FunctionType> function_type() const;

      /** \brief Get the parameters for this funtion */
      const ParameterList& parameters() const {return m_parameters;}

      /**
       * Get the return type of this function, as viewed from inside the
       * function (i.e., with parameterized types replaced by parameters
       * to this function).
       */
      const ValuePtr<>& result_type() const {return m_result_type;}

      const BlockList& blocks() {return m_blocks;}

      PSI_TVM_EXPORT ValuePtr<Block> new_block(const SourceLocation& location,
                                               const ValuePtr<Block>& dominator=ValuePtr<Block>(),
                                               const ValuePtr<Block>& landing_pad=ValuePtr<Block>());
      PSI_TVM_EXPORT ValuePtr<Block> new_landing_pad(const SourceLocation& location,
                                                     const ValuePtr<Block>& dominator=ValuePtr<Block>(),
                                                     const ValuePtr<Block>& landing_pad=ValuePtr<Block>());

      void add_term_name(const ValuePtr<>& term, const std::string& name);
      const TermNameMap& term_name_map() {return m_name_map;}

      /**
       * \brief Get the exception handling personality of this function.
       *
       * The exception handling personality is a string which is interpreted in an
       * unspecified way by the backend to distinguish different exception handling
       * styles for different languages.
       */
      const std::string& exception_personality() const {return m_exception_personality;}

      /**
       * \brief Set the exception handling personality of this function.
       * \see exception_personality()
       */
      void exception_personality(const std::string& v) {m_exception_personality = v;}

      template<typename V> static void visit(V& v);
      static bool isa_impl(const Value& v) {return v.term_type() == term_function;}

    private:
      Function(Context& context, const ValuePtr<FunctionType>& type, const std::string& name,
               Module *module, const SourceLocation& location);

      TermNameMap m_name_map;
      std::string m_exception_personality;
      ValuePtr<> m_result_type;
      ParameterList m_parameters;
      BlockList m_blocks;
    };

    /**
     * \brief Term type appearing in dependent types of completed function types.
     */
    class PSI_TVM_EXPORT_DEBUG ResolvedParameter : public HashableValue {
      PSI_TVM_HASHABLE_DECL(ResolvedParameter)

    private:
      ValuePtr<> m_parameter_type;
      unsigned m_depth;
      unsigned m_index;

    public:
      ResolvedParameter(const ValuePtr<>& type, unsigned depth, unsigned index, const SourceLocation& location);

      static bool isa_impl(const Value& ptr) {return ptr.term_type() == term_resolved_parameter;}

      /// \brief Get the depth of this parameter relative to the
      /// function type it is part of.
      ///
      /// If a parameter is used as the type of a parameter in its own
      /// functions argument list, then this is zero. For each function
      /// type it is then nested inside, this should increase by one.
      ///
      /// Note that depths in the type of this term are defined relative to
      /// this depth.
      unsigned depth() const {return m_depth;}
      /// \brief Get the parameter number of this parameter in its
      /// function.
      unsigned index() const {return m_index;}
    };

    template<typename T>
    struct ParameterTemplateType {
      ValuePtr<T> value;
      ParameterAttributes attributes;

      ParameterTemplateType() {}
      ParameterTemplateType(const ValuePtr<T>& value_) : value(value_) {}
      ParameterTemplateType(const ValuePtr<T>& value_, ParameterAttributes attributes_) : value(value_), attributes(attributes_) {}

      template<typename V>
      static void visit(V& v) {
        v("value", &ParameterTemplateType::value)
        ("attributes", &ParameterTemplateType::attributes);
      }

      friend std::size_t hash_value(const ParameterTemplateType<T>& self) {
        std::size_t h = 0;
        boost::hash_combine(h, self.value);
        boost::hash_combine(h, self.attributes);
        return h;
      }
    };

    template<typename T> bool operator == (const ParameterTemplateType<T>& lhs, const ParameterTemplateType<T>& rhs) {return (lhs.value==rhs.value) && (lhs.attributes==rhs.attributes);}
    template<typename T> bool operator != (const ParameterTemplateType<T>& lhs, const ParameterTemplateType<T>& rhs) {return !(lhs == rhs);}

    /**
     * \brief Type of functions.
     *
     * This is also used for implementing template types since the
     * template may be specialized by computing the result type of a
     * function call (note that there is no <tt>result_of</tt> term,
     * since the result must be the appropriate term itself).
     */
    class PSI_TVM_EXPORT_DEBUG FunctionType : public HashableValue {
      PSI_TVM_HASHABLE_DECL(FunctionType)
      friend class Context;

    public:
      FunctionType(CallingConvention calling_convention, const ParameterType& result_type,
                   const std::vector<ParameterType>& parameter_types, unsigned n_phantom,
                   bool sret, const SourceLocation& location);

      CallingConvention calling_convention() const {return m_calling_convention;}
      const ParameterType& result_type() const {return m_result_type;}
      /// \brief Get the number of phantom parameters.
      unsigned n_phantom() const {return m_n_phantom;}
      /**
       * \brief Whether this has an sret parameter.
       *
       * This means the last parameter is assumed to be a valid pointer to store the result
       * of the function to. It will also usually be passed as the first parameter according to
       * the platform calling convention.
       */
      bool sret() const {return m_sret;}
      /// \brief Get the vector parameter types.
      const std::vector<ParameterType>& parameter_types() const {return m_parameter_types;}

      ValuePtr<> parameter_type_after(const SourceLocation& location, const std::vector<ValuePtr<> >& previous);
      ValuePtr<> result_type_after(const SourceLocation& location, const std::vector<ValuePtr<> >& parameters);

      /// \brief Get the attributes of the nth parameter
      const ParameterAttributes& parameter_attributes(std::size_t n) const {return m_parameter_types[n].attributes;}
      /// \brief Get the return attributes
      const ParameterAttributes& result_attributes() const {return m_result_type.attributes;}

      static bool isa_impl(const Value& ptr) {return ptr.term_type() == term_function_type;}

    private:
      CallingConvention m_calling_convention;
      std::vector<ParameterType> m_parameter_types;
      unsigned m_n_phantom;
      bool m_sret;
      ParameterType m_result_type;
    };

    /**
     * \brief Type which implements the notion of unknown or partially known types.
     *
     * Used to implement virtual function calls with a type safe derived parameter.
     *
     * \note This is implemented next to FunctionType because they work in a
     * similar way, not because they are particularly conceptually related.
     */
    class PSI_TVM_EXPORT_DEBUG Exists : public HashableValue {
      PSI_TVM_HASHABLE_DECL(Exists)

    public:
      Exists(const ValuePtr<>& result, const std::vector<ValuePtr<> >& parameter_types, const SourceLocation& location);

      const ValuePtr<>& result() const {return m_result;}
      /// \brief Get the vector parameter types.
      const std::vector<ValuePtr<> >& parameter_types() const {return m_parameter_types;}

      ValuePtr<> parameter_type_after(const std::vector<ValuePtr<> >& previous);
      ValuePtr<> result_after(const std::vector<ValuePtr<> >& parameters);

      static bool isa_impl(const Value& ptr) {return ptr.term_type() == term_exists;}

    private:
      std::vector<ValuePtr<> > m_parameter_types;
      ValuePtr<> m_result;
    };

    /**
     * \brief Used to unwrap a value whose type is an exists term.
     */
    class PSI_TVM_EXPORT_DEBUG Unwrap : public FunctionalValue {
      PSI_TVM_FUNCTIONAL_DECL(Unwrap)

    public:
      Unwrap(const ValuePtr<>& value, const SourceLocation& location);

      /// \brief value must have an "exists" type
      const ValuePtr<>& value() const {return m_value;}

    private:
      ValuePtr<> m_value;
    };

    /**
     * \brief Used to replace exists parameters in unwrapped values.
     */
    class PSI_TVM_EXPORT_DEBUG UnwrapParameter : public FunctionalValue {
      PSI_TVM_FUNCTIONAL_DECL(UnwrapParameter)

    public:
      UnwrapParameter(const ValuePtr<>& value, unsigned index, const SourceLocation& location);

      /// \brief value must have an "exists" type
      const ValuePtr<>& value() const {return m_value;}
      /// \brief Index of exists parameter this corresponds to.
      unsigned index() const {return m_index;}

      friend void hashable_check_source_hook(UnwrapParameter& self, CheckSourceParameter& parameter);

    private:
      ValuePtr<> m_value;
      unsigned m_index;
    };

    /**
     * \brief Introduce exists quantification to a value.
     */
    class PSI_TVM_EXPORT_DEBUG IntroduceExists : public FunctionalValue {
      PSI_TVM_FUNCTIONAL_DECL(IntroduceExists)

    public:
      IntroduceExists(const ValuePtr<>& exists_type, const ValuePtr<>& value, const SourceLocation& location);

      /// \brief Get the expected type of this term
      const ValuePtr<>& exists_type() const {return m_exists_type;}
      /// \brief Get the value of this term
      const ValuePtr<>& value() const {return m_value;}

    private:
      ValuePtr<> m_exists_type;
      ValuePtr<> m_value;
    };

    /**
     * \brief Placeholder used for parameters during type setup.
     *
     * This is used by function type, recursive and exists.
     */
    class PSI_TVM_EXPORT_DEBUG ParameterPlaceholder : public Value {
      PSI_TVM_VALUE_DECL(ParameterPlaceholder);
    private:
      friend class Context;
      ParameterPlaceholder(Context& context, const ValuePtr<>& type, const SourceLocation& location);
      ValuePtr<> m_parameter_type;
      virtual void check_source_hook(CheckSourceParameter& parameter);
    public:
      static bool isa_impl(const Value& ptr) {return ptr.term_type() == term_parameter_placeholder;}
      template<typename V> static void visit(V& v);
      Value* disassembler_source();
    };

    /**
     * Helper class for inserting instructions into blocks.
     */
    class PSI_TVM_EXPORT_DEBUG InstructionInsertPoint {
      ValuePtr<Block> m_block;
      ValuePtr<Instruction> m_instruction;

    public:
      /**
       * Constructs an invalid inserter.
       */
      InstructionInsertPoint() : m_block(0), m_instruction(0) {}

      /**
       * Construct an inserter which inserts instructions at the end of
       * the specified block.
       *
       * \param insert_at_end Block to append instructions to.
       */
      explicit InstructionInsertPoint(const ValuePtr<Block>& insert_at_end)
      : m_block(insert_at_end), m_instruction(0) {}

      /**
       * Construct an inserter which inserts instructions in the same
       * block as the specified instruction, just before it.
       *
       * \param insert_before Instruction to insert created instructions
       * before.
       */
      explicit InstructionInsertPoint(const ValuePtr<Instruction>& insert_before)
      : m_block(insert_before->block()), m_instruction(insert_before) {}

      static InstructionInsertPoint after_source(const ValuePtr<>& source);

      void insert(const ValuePtr<Instruction>& instruction);

      /// \brief Block to insert instructions into
      const ValuePtr<Block>& block() const {return m_block;}

      /**
       * \brief Instruction to insert new instructions before
       *
       * If this is NULL, instructions will be inserted at the end of the block.
       */
      const ValuePtr<Instruction>& instruction() const {return m_instruction;}
    };
  }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
    die('You are not allowed to access this file.');
}

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');

$baseDir = realpath(__DIR__ . '/../..');

require($baseDir . '/backend-app/credentials.php');
require($baseDir . '/env.php');

require($baseDir . '/vendor/autoload.php');
require($baseDir . '/vendor/yiisoft/yii2/Yii.php');

require($baseDir . '/common/config/bootstrap.php');
require($baseDir . '/backend-app/config/bootstrap.php');

\cookyii\Config::requireGlobals($baseDir);

$config = require($baseDir . '/backend-app/tests/_config/acceptance.php');

(new yii\web\Application($config))
    ->run();


text:
// INScrollView.h
//
// Copyright (c) 2014 Sven Korset
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/**
 A UIScrollView subclass which adds the feature to cancel touches on certain view objects or on views of specific class names when dragging.

 This class overrides touchesShouldCancelInContentView: and uses the properties classesToCancelTouchesOn and viewsToCancelTouchesOn to determine if a touch should be cancelled when dragging.
 */
@interface INScrollView : UIScrollView

/**
 Array with NSString objects of the class names to cancel touches on when dragging.

 Normally a scroll view will not cancel touches on buttons, though by adding the class name of UIButton to this list will do this.
 The method touchesShouldCancelInContentView: will return true if the touch is on a class which is listed in this array.

 Example of creating the array:

    scrollView.classesToCancelTouchesOn = @[NSStringFromClass([UIButton class])];

 This list may be used in conjunction with viewsToCancelTouchesOn and offers the possibility to cancel all types of objects at once.
 The string will be compared with the string of the view's class name, so there won't be an exception if the given class name doesn't exist.

 @see viewsToCancelTouchesOn
 */
@property (nonatomic, strong) NSArray *classesToCancelTouchesOn;

/**
 Array with UIView objects which to cancel touches on when dragging.

 Normally a scroll view will not cancel touches on buttons, though by adding the object to this list will do this.
 The method touchesShouldCancelInContentView: will return true if the touch is on a view which is listed in this array.

 Example of creating the array:

    scrollView.viewsToCancelTouchesOn = @[myButton];

 This list may be used in conjunction with classesToCancelTouchesOn and offers the possibility to precisely exclude certain objects.
 Both view's, in the list an on the scroll view are compared with isEqual:.

 @see classesToCancelTouchesOn
 */
@property (nonatomic, strong) NSArray *viewsToCancelTouchesOn;

@end


text:
package org.infinispan.configuration.global;

abstract class AbstractGlobalConfigurationBuilder<T> implements GlobalConfigurationChildBuilder {

   private final GlobalConfigurationBuilder globalConfig;

   protected AbstractGlobalConfigurationBuilder(GlobalConfigurationBuilder globalConfig) {
      this.globalConfig = globalConfig;
   }

   protected GlobalConfigurationBuilder getGlobalConfig() {
      return globalConfig;
   }

   @Override
   public TransportConfigurationBuilder transport() {
      return globalConfig.transport();
   }

   @Override
   public GlobalJmxStatisticsConfigurationBuilder globalJmxStatistics() {
      globalConfig.globalJmxStatistics().enable();
      return globalConfig.globalJmxStatistics();
   }

   @Override
   public SerializationConfigurationBuilder serialization() {
      return globalConfig.serialization();
   }

   @Override
   public ExecutorFactoryConfigurationBuilder asyncListenerExecutor() {

      return globalConfig.asyncListenerExecutor();
   }

   @Override
   public ExecutorFactoryConfigurationBuilder asyncTransportExecutor() {
      return globalConfig.asyncTransportExecutor();
   }

   @Override
   public ScheduledExecutorFactoryConfigurationBuilder evictionScheduledExecutor() {
      return globalConfig.evictionScheduledExecutor();
   }

   @Override
   public ScheduledExecutorFactoryConfigurationBuilder replicationQueueScheduledExecutor() {
      return globalConfig.replicationQueueScheduledExecutor();
   }

   @Override
   public ShutdownConfigurationBuilder shutdown() {
      return globalConfig.shutdown();
   }

   @Override
   public SiteConfigurationBuilder site() {
      return globalConfig.site();
   }

   @Override
   public GlobalConfiguration build() {
      return globalConfig.build();
   }

   abstract void validate();

   abstract T create();

   protected abstract GlobalConfigurationChildBuilder read(T template);

}


text:
package org.apache.synapse.core.axis2;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.ServerConfigurationInformation;
import org.apache.synapse.ServerConfigurationInformationFactory;
import org.apache.synapse.ServerManager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * When Synapse is deployed on a WAR container, this is the init servlet that kicks off the
 * Synapse instance, calling on the ServerManager
 */

public class SynapseStartUpServlet extends HttpServlet {

    private static Log log = LogFactory.getLog(SynapseStartUpServlet.class);
    private static final String ALREADY_INITED = "synapseAlreadyInited";

    public static final String SYNAPSE_SERVER_MANAGER = "synapse.server.manager";

    public void init() throws ServletException {
        ServletConfig servletConfig = getServletConfig();
        ServletContext servletContext = servletConfig.getServletContext();
        if (Boolean.TRUE.equals(servletContext.getAttribute(ALREADY_INITED))) {
            return;
        }
        ServerManager serverManager = new ServerManager();
        ServerConfigurationInformation information =
                ServerConfigurationInformationFactory.
                        createServerConfigurationInformation(servletConfig);
        serverManager.init(information, null);
        serverManager.start();
        servletContext.setAttribute(ALREADY_INITED, Boolean.TRUE);

        servletContext.setAttribute(SYNAPSE_SERVER_MANAGER, serverManager);
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
    }

    public void destroy() {
        try {
            Object o = getServletConfig().getServletContext().getAttribute(SYNAPSE_SERVER_MANAGER);
            if (o != null && o instanceof ServerManager) {
                ServerManager serverManager = (ServerManager) o;
                serverManager.stop();
                serverManager.shutdown();
                getServletContext().removeAttribute(ALREADY_INITED);
            }
        } catch (Exception e) {
            log.error("Error stopping the Synapse listener manager", e);
        }
    }
}


text:
const char *vertexShader = STRINGIFY(
uniform float pointRadius;  // point size in world space
uniform float pointScale;   // scale to calculate size in pixels
uniform float densityScale;
uniform float densityOffset;
void main()
{
    // calculate window-space point size
    vec3 posEye = vec3(gl_ModelViewMatrix * vec4(gl_Vertex.xyz, 1.0));
    float dist = length(posEye);
    gl_PointSize = pointRadius * (pointScale / dist);

    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = gl_ModelViewProjectionMatrix * vec4(gl_Vertex.xyz, 1.0);

    gl_FrontColor = gl_Color;
}
);

// pixel shader for rendering points as shaded spheres
const char *spherePixelShader = STRINGIFY(
void main()
{
    const vec3 lightDir = vec3(0.577, 0.577, 0.577);

    // calculate normal from texture coordinates
    vec3 N;
    N.xy = gl_TexCoord[0].xy*vec2(2.0, -2.0) + vec2(-1.0, 1.0);
    float mag = dot(N.xy, N.xy);
    if (mag > 1.0) discard;   // kill pixels outside circle
    N.z = sqrt(1.0-mag);

    // calculate lighting
    float diffuse = max(0.0, dot(lightDir, N));

    gl_FragColor = gl_Color * diffuse;
}
);


text:
package net.npg.abattle.client.commands;

import com.google.common.base.Objects;
import java.util.Collection;
import net.npg.abattle.client.ClientConstants;
import net.npg.abattle.common.component.ComponentLookup;
import net.npg.abattle.common.error.ErrorComponent;
import net.npg.abattle.common.i18n.I18N;
import net.npg.abattle.common.model.client.ClientGame;
import net.npg.abattle.common.model.client.ClientPlayer;
import net.npg.abattle.common.model.client.impl.ClientPlayerImpl;
import net.npg.abattle.common.model.impl.ColorImpl;
import net.npg.abattle.common.utils.Validate;
import net.npg.abattle.communication.command.data.PlayerData;
import org.eclipse.xtext.xbase.lib.Conversions;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;

@SuppressWarnings("all")
public class UpdatePlayerList {
  protected static void update(final PlayerData[] players, final ClientGame game) {
    try {
      Validate.notNull(players);
      int _length = players.length;
      String _plus = ("Players joined:" + Integer.valueOf(_length));
      ClientConstants.LOG.info(_plus);
      for (final PlayerData player : players) {
        {
          ColorImpl color = new ColorImpl(player.r, player.g, player.b);
          Collection<ClientPlayer> _players = game.getPlayers();
          final Function1<ClientPlayer, Boolean> _function = new Function1<ClientPlayer, Boolean>() {
            @Override
            public Boolean apply(final ClientPlayer it) {
              int _id = it.getId();
              return Boolean.valueOf((_id == player.playerId));
            }
          };
          ClientPlayer exisitingPlayer = IterableExtensions.<ClientPlayer>findFirst(_players, _function);
          boolean _equals = Objects.equal(exisitingPlayer, null);
          if (_equals) {
            final ClientPlayerImpl newPlayer = new ClientPlayerImpl(player.playerName, player.playerId, color);
            game.addPlayer(newPlayer);
          } else {
            exisitingPlayer.setColor(color);
          }
        }
      }
      Collection<ClientPlayer> _players = game.getPlayers();
      final Function1<ClientPlayer, Boolean> _function = new Function1<ClientPlayer, Boolean>() {
        @Override
        public Boolean apply(final ClientPlayer existingPlayer) {
          final Function1<PlayerData, Boolean> _function = new Function1<PlayerData, Boolean>() {
            @Override
            public Boolean apply(final PlayerData it) {
              int _id = existingPlayer.getId();
              return Boolean.valueOf((it.playerId == _id));
            }
          };
          PlayerData _findFirst = IterableExtensions.<PlayerData>findFirst(((Iterable<PlayerData>)Conversions.doWrapArray(players)), _function);
          return Boolean.valueOf(Objects.equal(_findFirst, null));
        }
      };
      Iterable<ClientPlayer> _filter = IterableExtensions.<ClientPlayer>filter(_players, _function);
      final Procedure1<ClientPlayer> _function_1 = new Procedure1<ClientPlayer>() {
        @Override
        public void apply(final ClientPlayer it) {
          UpdatePlayerList.removePlayer(game, it);
        }
      };
      IterableExtensions.<ClientPlayer>forEach(_filter, _function_1);
    } catch (Throwable _e) {
      throw Exceptions.sneakyThrow(_e);
    }
  }

  public static void removePlayer(final ClientGame game, final ClientPlayer player) {
    game.removePlayer(player);
    ComponentLookup _instance = ComponentLookup.getInstance();
    ErrorComponent _component = _instance.<ErrorComponent>getComponent(ErrorComponent.class);
    String _name = player.getName();
    String _format = I18N.format("player_left", _name);
    _component.addError(_format, false);
  }

  public static void remove(final PlayerData data, final ClientGame game) {
    Collection<ClientPlayer> _players = game.getPlayers();
    final Function1<ClientPlayer, Boolean> _function = new Function1<ClientPlayer, Boolean>() {
      @Override
      public Boolean apply(final ClientPlayer it) {
        int _id = it.getId();
        return Boolean.valueOf((_id == data.playerId));
      }
    };
    final ClientPlayer player = IterableExtensions.<ClientPlayer>findFirst(_players, _function);
    ComponentLookup _instance = ComponentLookup.getInstance();
    ErrorComponent _component = _instance.<ErrorComponent>getComponent(ErrorComponent.class);
    String _name = player.getName();
    String _format = I18N.format("player_left", _name);
    _component.addError(_format, false);
  }
}


text:
/* ====================================================================
 * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com). */

#ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
#define OPENSSL_HEADER_CRYPTO_INTERNAL_H

#include <openssl/ex_data.h>
#include <openssl/thread.h>

#if defined(_MSC_VER)
#if !defined(__cplusplus) || _MSC_VER < 1900
#define alignas(x) __declspec(align(x))
#define alignof __alignof
#endif
#else
#include <stdalign.h>
#endif

#if defined(OPENSSL_NO_THREADS)
#elif defined(OPENSSL_WINDOWS)
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <windows.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#else
#include <pthread.h>
#endif

#if defined(__cplusplus)
extern "C" {
#endif

#if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \
    defined(OPENSSL_AARCH64)
/* OPENSSL_cpuid_setup initializes OPENSSL_ia32cap_P. */
void OPENSSL_cpuid_setup(void);
#endif

#if !defined(_MSC_VER) && defined(OPENSSL_64_BIT)
typedef __int128_t int128_t;
typedef __uint128_t uint128_t;
#endif

/* buffers_alias returns one if |a| and |b| alias and zero otherwise. */
static inline int buffers_alias(const uint8_t *a, size_t a_len,
                                const uint8_t *b, size_t b_len) {
  /* Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
   * objects are undefined whereas pointer to integer conversions are merely
   * implementation-defined. We assume the implementation defined it in a sane
   * way. */
  uintptr_t a_u = (uintptr_t)a;
  uintptr_t b_u = (uintptr_t)b;
  return a_u + a_len > b_u && b_u + b_len > a_u;
}

/* Constant-time utility functions.
 *
 * The following methods return a bitmask of all ones (0xff...f) for true and 0
 * for false. This is useful for choosing a value based on the result of a
 * conditional in constant time. For example,
 *
 * if (a < b) {
 *   c = a;
 * } else {
 *   c = b;
 * }
 *
 * can be written as
 *
 * unsigned int lt = constant_time_lt(a, b);
 * c = constant_time_select(lt, a, b); */

/* constant_time_msb returns the given value with the MSB copied to all the
 * other bits. */
static inline unsigned int constant_time_msb(unsigned int a) {
  return (unsigned int)((int)(a) >> (sizeof(int) * 8 - 1));
}

/* constant_time_lt returns 0xff..f if a < b and 0 otherwise. */
static inline unsigned int constant_time_lt(unsigned int a, unsigned int b) {
  /* Consider the two cases of the problem:
   *   msb(a) == msb(b): a < b iff the MSB of a - b is set.
   *   msb(a) != msb(b): a < b iff the MSB of b is set.
   *
   * If msb(a) == msb(b) then the following evaluates as:
   *   msb(a^((a^b)|((a-b)^a))) ==
   *   msb(a^((a-b) ^ a))       ==   (because msb(a^b) == 0)
   *   msb(a^a^(a-b))           ==   (rearranging)
   *   msb(a-b)                      (because ∀x. x^x == 0)
   *
   * Else, if msb(a) != msb(b) then the following evaluates as:
   *   msb(a^((a^b)|((a-b)^a))) ==
   *   msb(a^(𝟙 | ((a-b)^a)))   ==   (because msb(a^b) == 1 and 𝟙
   *                                  represents a value s.t. msb(𝟙) = 1)
   *   msb(a^𝟙)                 ==   (because ORing with 1 results in 1)
   *   msb(b)
   *
   *
   * Here is an SMT-LIB verification of this formula:
   *
   * (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
   *   (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
   * )
   *
   * (declare-fun a () (_ BitVec 32))
   * (declare-fun b () (_ BitVec 32))
   *
   * (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
   * (check-sat)
   * (get-model)
   */
  return constant_time_msb(a^((a^b)|((a-b)^a)));
}

/* constant_time_lt_8 acts like |constant_time_lt| but returns an 8-bit mask. */
static inline uint8_t constant_time_lt_8(unsigned int a, unsigned int b) {
  return (uint8_t)(constant_time_lt(a, b));
}

/* constant_time_gt returns 0xff..f if a >= b and 0 otherwise. */
static inline unsigned int constant_time_ge(unsigned int a, unsigned int b) {
  return ~constant_time_lt(a, b);
}

/* constant_time_ge_8 acts like |constant_time_ge| but returns an 8-bit mask. */
static inline uint8_t constant_time_ge_8(unsigned int a, unsigned int b) {
  return (uint8_t)(constant_time_ge(a, b));
}

/* constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise. */
static inline unsigned int constant_time_is_zero(unsigned int a) {
  /* Here is an SMT-LIB verification of this formula:
   *
   * (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
   *   (bvand (bvnot a) (bvsub a #x00000001))
   * )
   *
   * (declare-fun a () (_ BitVec 32))
   *
   * (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
   * (check-sat)
   * (get-model)
   */
  return constant_time_msb(~a & (a - 1));
}

/* constant_time_is_zero_8 acts like constant_time_is_zero but returns an 8-bit
 * mask. */
static inline uint8_t constant_time_is_zero_8(unsigned int a) {
  return (uint8_t)(constant_time_is_zero(a));
}

/* constant_time_eq returns 0xff..f if a == b and 0 otherwise. */
static inline unsigned int constant_time_eq(unsigned int a, unsigned int b) {
  return constant_time_is_zero(a ^ b);
}

/* constant_time_eq_8 acts like |constant_time_eq| but returns an 8-bit mask. */
static inline uint8_t constant_time_eq_8(unsigned int a, unsigned int b) {
  return (uint8_t)(constant_time_eq(a, b));
}

/* constant_time_eq_int acts like |constant_time_eq| but works on int values. */
static inline unsigned int constant_time_eq_int(int a, int b) {
  return constant_time_eq((unsigned)(a), (unsigned)(b));
}

/* constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
 * mask. */
static inline uint8_t constant_time_eq_int_8(int a, int b) {
  return constant_time_eq_8((unsigned)(a), (unsigned)(b));
}

/* constant_time_select returns (mask & a) | (~mask & b). When |mask| is all 1s
 * or all 0s (as returned by the methods above), the select methods return
 * either |a| (if |mask| is nonzero) or |b| (if |mask| is zero). */
static inline unsigned int constant_time_select(unsigned int mask,
                                                unsigned int a, unsigned int b) {
  return (mask & a) | (~mask & b);
}

/* constant_time_select_8 acts like |constant_time_select| but operates on
 * 8-bit values. */
static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
                                             uint8_t b) {
  return (uint8_t)(constant_time_select(mask, a, b));
}

/* constant_time_select_int acts like |constant_time_select| but operates on
 * ints. */
static inline int constant_time_select_int(unsigned int mask, int a, int b) {
  return (int)(constant_time_select(mask, (unsigned)(a), (unsigned)(b)));
}

/* Thread-safe initialisation. */

/* Android's mingw-w64 has some prototypes for INIT_ONCE, but is missing
 * others. Work around the missing ones.
 *
 * TODO(davidben): Remove this once Android's mingw-w64 is upgraded. See
 * b/26523949. */
#if defined(__MINGW32__) && !defined(INIT_ONCE_STATIC_INIT)
typedef RTL_RUN_ONCE INIT_ONCE;
#define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT
#endif

#if defined(OPENSSL_NO_THREADS)
typedef uint32_t CRYPTO_once_t;
#define CRYPTO_ONCE_INIT 0
#elif defined(OPENSSL_WINDOWS)
typedef INIT_ONCE CRYPTO_once_t;
#define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
#else
typedef pthread_once_t CRYPTO_once_t;
#define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
#endif

/* CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
 * concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
 * then they will block until |init| completes, but |init| will have only been
 * called once.
 *
 * The |once| argument must be a |CRYPTO_once_t| that has been initialised with
 * the value |CRYPTO_ONCE_INIT|. */
OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));

/* Reference counting. */

/* CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates. */
#define CRYPTO_REFCOUNT_MAX 0xffffffff

/* CRYPTO_refcount_inc atomically increments the value at |*count| unless the
 * value would overflow. It's safe for multiple threads to concurrently call
 * this or |CRYPTO_refcount_dec_and_test_zero| on the same
 * |CRYPTO_refcount_t|. */
OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);

/* CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
 *   if it's zero, it crashes the address space.
 *   if it's the maximum value, it returns zero.
 *   otherwise, it atomically decrements it and returns one iff the resulting
 *       value is zero.
 *
 * It's safe for multiple threads to concurrently call this or
 * |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|. */
OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);

/* Locks.
 *
 * Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
 * structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
 * a global lock. A global lock must be initialised to the value
 * |CRYPTO_STATIC_MUTEX_INIT|.
 *
 * |CRYPTO_MUTEX| can appear in public structures and so is defined in
 * thread.h as a structure large enough to fit the real type. The global lock is
 * a different type so it may be initialized with platform initializer macros.*/

#if defined(OPENSSL_NO_THREADS)
struct CRYPTO_STATIC_MUTEX {
  char padding;  /* Empty structs have different sizes in C and C++. */
};
#define CRYPTO_STATIC_MUTEX_INIT { 0 }
#elif defined(OPENSSL_WINDOWS)
struct CRYPTO_STATIC_MUTEX {
  SRWLOCK lock;
};
#define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
#else
struct CRYPTO_STATIC_MUTEX {
  pthread_rwlock_t lock;
};
#define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
#endif

/* CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
 * |CRYPTO_STATIC_MUTEX|. */
OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);

/* CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
 * read lock, but none may have a write lock. */
OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);

/* CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
 * of lock on it. */
OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);

/* CRYPTO_MUTEX_unlock_read unlocks |lock| for reading. */
OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);

/* CRYPTO_MUTEX_unlock_write unlocks |lock| for writing. */
OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);

/* CRYPTO_MUTEX_cleanup releases all resources held by |lock|. */
OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);

/* CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
 * have a read lock, but none may have a write lock. The |lock| variable does
 * not need to be initialised by any function, but must have been statically
 * initialised with |CRYPTO_STATIC_MUTEX_INIT|. */
OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
    struct CRYPTO_STATIC_MUTEX *lock);

/* CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
 * any type of lock on it.  The |lock| variable does not need to be initialised
 * by any function, but must have been statically initialised with
 * |CRYPTO_STATIC_MUTEX_INIT|. */
OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
    struct CRYPTO_STATIC_MUTEX *lock);

/* CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading. */
OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
    struct CRYPTO_STATIC_MUTEX *lock);

/* CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing. */
OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
    struct CRYPTO_STATIC_MUTEX *lock);

/* Thread local storage. */

/* thread_local_data_t enumerates the types of thread-local data that can be
 * stored. */
typedef enum {
  OPENSSL_THREAD_LOCAL_ERR = 0,
  OPENSSL_THREAD_LOCAL_RAND,
  OPENSSL_THREAD_LOCAL_URANDOM_BUF,
  OPENSSL_THREAD_LOCAL_TEST,
  NUM_OPENSSL_THREAD_LOCALS,
} thread_local_data_t;

/* thread_local_destructor_t is the type of a destructor function that will be
 * called when a thread exits and its thread-local storage needs to be freed. */
typedef void (*thread_local_destructor_t)(void *);

/* CRYPTO_get_thread_local gets the pointer value that is stored for the
 * current thread for the given index, or NULL if none has been set. */
OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);

/* CRYPTO_set_thread_local sets a pointer value for the current thread at the
 * given index. This function should only be called once per thread for a given
 * |index|: rather than update the pointer value itself, update the data that
 * is pointed to.
 *
 * The destructor function will be called when a thread exits to free this
 * thread-local data. All calls to |CRYPTO_set_thread_local| with the same
 * |index| should have the same |destructor| argument. The destructor may be
 * called with a NULL argument if a thread that never set a thread-local
 * pointer for |index|, exits. The destructor may be called concurrently with
 * different arguments.
 *
 * This function returns one on success or zero on error. If it returns zero
 * then |destructor| has been called with |value| already. */
OPENSSL_EXPORT int CRYPTO_set_thread_local(
    thread_local_data_t index, void *value,
    thread_local_destructor_t destructor);

/* ex_data */

typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;

/* CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
 * supports ex_data. It should defined as a static global within the module
 * which defines that type. */
typedef struct {
  struct CRYPTO_STATIC_MUTEX lock;
  STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
  /* num_reserved is one if the ex_data index zero is reserved for legacy
   * |TYPE_get_app_data| functions. */
  uint8_t num_reserved;
} CRYPTO_EX_DATA_CLASS;

#define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
#define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
    {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}

/* CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
 * it to |*out_index|. Each class of object should provide a wrapper function
 * that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
 * zero otherwise. */
OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
                                           int *out_index, long argl,
                                           void *argp, CRYPTO_EX_dup *dup_func,
                                           CRYPTO_EX_free *free_func);

/* CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
 * of object should provide a wrapper function. */
OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);

/* CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
 * if no such index exists. Each class of object should provide a wrapper
 * function. */
OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);

/* CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|. */
OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);

/* CRYPTO_dup_ex_data duplicates |from| into a freshly allocated
 * |CRYPTO_EX_DATA|, |to|. Both of which are inside objects of the given
 * class. It returns one on success and zero otherwise. */
OPENSSL_EXPORT int CRYPTO_dup_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
                                      CRYPTO_EX_DATA *to,
                                      const CRYPTO_EX_DATA *from);

/* CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
 * object of the given class. */
OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
                                        void *obj, CRYPTO_EX_DATA *ad);

#if defined(__cplusplus)
}  /* extern C */
#endif

#endif  /* OPENSSL_HEADER_CRYPTO_INTERNAL_H */


text:
package block

import (
	"context"
	"fmt"
	"io"
	"math/rand"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/ltick/tick-framework/config"
)

var (
	errNotExist error = fmt.Errorf("block: key not exist")
)

const (
	FilenameSuffixInSecond string = "20060102150405"
	FilenameBlockIndex     string = "blockIndex"
	FilenameBlockIndexTemp string = "blockIndexTemp"
)

type Block struct {
	tempDir       string
	maxSize       int64
	contentMutex  *sync.Mutex
	contentWriter ContentWriter     // 只有一个写句柄
	indexTable    map[string]*Index // 内存index信息
	indexMutex    *sync.RWMutex
	indexWriter   IndexWriter
}

func NewFileBlockHandler() BlockHandler {
	return &Block{
		contentMutex: new(sync.Mutex),
		indexTable:   make(map[string]*Index),
		indexMutex:   new(sync.RWMutex),
	}
}

func (b *Block) Initiate(ctx context.Context, conf *config.Config) (err error) {
	var (
		tempDir      string        = conf.GetString("FILESYSTEM_BLOCK_DIR")
		maxSize      int64         = conf.GetInt64("FILESYSTEM_BLOCK_CONTENT_SIZE")
		dumpInterval time.Duration = conf.GetDuration("FILESYSTEM_BLOCK_INDEX_SAVE_INTERVAL")
	)
	if err = os.MkdirAll(tempDir, os.FileMode(0755)); err != nil {
		return
	}
	b.tempDir = tempDir
	b.maxSize = maxSize

	// 初始化 将上次退出时的文件句柄传入
	if err = filepath.Walk(b.tempDir, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		if f.Name() == FilenameBlockIndex || f.Name() == FilenameBlockIndexTemp {
			return nil
		}
		var blockWriter ContentWriter
		if blockWriter, err = NewContentWriter(filepath.Join(b.tempDir, f.Name()), b.tempDir); err != nil {
			return err
		}
		if b.maxSize > 0 && blockWriter.Size() >= b.maxSize {
			blockWriter.Close()
			return nil
		}
		b.contentMutex.Lock()
		if b.contentWriter != nil {
			b.contentWriter.Close()
		}
		b.contentWriter = blockWriter
		b.contentMutex.Unlock()
		return nil
	}); err != nil {
		return
	}
	// 初始化 index句柄
	if b.indexWriter, err = NewIndexWriter(filepath.Join(b.tempDir, FilenameBlockIndex), false); err != nil {
		return
	}
	// 初始化 内存index
	b.loadIndex()
	go func() {
		for range time.Tick(dumpInterval) {
			b.dumpIndex()
		}
	}()
	return
}

func (b *Block) loadIndex() (err error) {
	var indexTable map[string]*Index
	if indexTable, err = LoadIndexFromFile(filepath.Join(b.tempDir, FilenameBlockIndex)); err != nil {
		return
	}
	b.indexMutex.Lock()
	defer b.indexMutex.Unlock()
	var (
		key   string
		index *Index
	)
	for key, index = range indexTable {
		b.indexTable[key] = index
	}
	return
}

func (b *Block) dumpIndex() (err error) {
	// 打开Buffer
	b.indexMutex.Lock()
	b.indexWriter.WriteAndBuffered()
	b.indexMutex.Unlock()

	// 打开原来的index文件, 然后整理合并完key数据后, 再重命名, 切换句柄
	// 不影响内存中原有的map
	var indexTable map[string]*Index
	if indexTable, err = LoadIndexFromFile(filepath.Join(b.tempDir, FilenameBlockIndex)); err != nil {
		return
	}
	var (
		key         string
		index       *Index
		indexWriter *indexWriter
	)
	if indexWriter, err = NewIndexWriter(filepath.Join(b.tempDir, FilenameBlockIndexTemp), true); err != nil {
		return
	}
	for key, index = range indexTable {
		if err = indexWriter.Write(key, index); err != nil {
			continue
		}
	}
	// buff写回, 重命名, 再切换句柄
	b.indexMutex.Lock()
	if _, err = b.indexWriter.BufferWriteTo(indexWriter); err != nil {
		b.indexMutex.Unlock()
		return
	}
	b.indexWriter.Close()
	os.Rename(filepath.Join(b.tempDir, FilenameBlockIndexTemp), filepath.Join(b.tempDir, FilenameBlockIndex))
	b.indexWriter = indexWriter
	b.indexMutex.Unlock()
	return
}

func (b *Block) updateContentWriter() (err error) {
	if b.contentWriter == nil {
		goto update
	}
	// 文件大小超过限制,切换文件句柄
	if b.maxSize > 0 && b.contentWriter.Size() >= b.maxSize {
		b.contentWriter.Close()
		goto update
	}
	return
update:
	var filename string = filepath.Join(b.tempDir, fmt.Sprintf("%s.%d", time.Now().Format(FilenameSuffixInSecond), rand.Uint64()))
	if b.contentWriter, err = NewContentWriter(filename, b.tempDir); err != nil {
		return
	}
	return
}

func (b *Block) Set(key string, value []byte) (err error) {
	var index *Index
	if index, err = b.writeContent([]byte(key), value); err != nil {
		return
	}
	if err = b.writeIndex(key, index); err != nil {
		return
	}
	return
}

func (b *Block) writeContent(key, value []byte) (index *Index, err error) {
	b.contentMutex.Lock()
	defer b.contentMutex.Unlock()
	if err = b.updateContentWriter(); err != nil {
		return
	}
	if index, err = b.contentWriter.Write(key, value); err != nil {
		return
	}
	return
}

func (b *Block) writeIndex(key string, index *Index) (err error) {
	b.indexMutex.Lock()
	defer b.indexMutex.Unlock()

	if err = b.indexWriter.Write(key, index); err != nil { // 同步写文件
		return
	}
	b.indexTable[key] = index
	return
}

func (b *Block) Get(key string) (value []byte, err error) {
	var index *Index
	if index, err = b.readIndex(key); err != nil {
		return
	}
	if value, err = b.readContent(index); err != nil {
		return
	}
	return
}

func (b *Block) readIndex(key string) (index *Index, err error) {
	var ok bool
	b.indexMutex.RLock()
	index, ok = b.indexTable[key]
	b.indexMutex.RUnlock()
	if !ok {
		err = errNotExist
		return
	}
	return
}

func (b *Block) readContent(index *Index) (value []byte, err error) {
	var r ContentReader
	if r, err = NewContentReader(filepath.Join(b.tempDir, index.Filename()), b.tempDir); err != nil {
		return
	}
	defer r.Close()
	return r.Read(index.offset, index.length)
}

func (b *Block) Del(key string) (err error) {
	b.indexMutex.Lock()
	defer b.indexMutex.Unlock()

	if err = b.indexWriter.Write(key, NewDelIndex()); err != nil {
		return
	}
	delete(b.indexTable, key)
	return
}

// content整理
// set相同key的时候, 之前key的index会更新, 但是旧content还保留着
// 删除key时, content还保留着
func (b *Block) DefragContent(defragDuration time.Duration) (err error) {
	var defragTimestamp time.Time = time.Now().Add(-defragDuration)
	if err = filepath.Walk(b.tempDir, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		if f.Name() == FilenameBlockIndex || f.Name() == FilenameBlockIndexTemp {
			return nil
		}
		if f.Size() < b.maxSize {
			return nil
		}
		if f.ModTime().After(defragTimestamp) { // 一段时间之内的vlog不整理
			return nil
		}

		// 开始整理文件
		var (
			filename      string = filepath.Join(b.tempDir, f.Name())
			contentReader ContentReader
		)
		if contentReader, err = NewContentReader(filename, b.tempDir); err != nil {
			return nil
		}
	loop:
		for {
			var (
				key   string
				index *Index
				err   error
			)
			if key, index, err = contentReader.SequentialRead(); err != nil {
				if err == io.EOF {
					break loop
				} else {
					continue
				}
			}
			// 重建索引
			b.rebuildIndex(key, index)
		}
		contentReader.Close()
		os.Remove(filename)
		return nil
	}); err != nil {
		return
	}
	return
}

func (b *Block) rebuildIndex(key string, index *Index) {
	var (
		latestIndex *Index
		latestValue []byte
		err         error
	)
	if latestIndex, err = b.readIndex(key); err != nil {
		return
	}
	if !latestIndex.Same(index) {
		return
	}
	if latestValue, err = b.readContent(index); err != nil {
		return
	}
	b.Set(key, latestValue)
}

func (b *Block) Range(doFunc func(key string, exist bool)) (err error) {
	return RangeIndexFromFile(filepath.Join(b.tempDir, FilenameBlockIndex), func(key string, index *Index) {
		doFunc(key, !index.IsDel())
	})
}


text:
import argparse
import logging.config
import lib.worker
from lib.connection import Connection
from lib.s3 import S3
from lib.dynamodb import DynamoDB

LOG_PATH = "/tmp/abc.log"

def s3_checker(key):
    """THREAD METHOD - check result_set is all in DynamoDB
    """
    global db, db_table
    if db:
        table = db.get_storage_set(db_table)
        item = db.get_item(table, hash_key=key.name)
        return None if item else key.name

def dynamodb_checker(key):
    """THREAD METHOD - check result_set is all in S3
    """
    #TODO - merge with s3_checker
    key = key['FileKey']
    global s3, s3_bucket
    if s3:
        bucket = s3.get_storage_set(s3_bucket)
        s3obj = s3.get_item(bucket, key)
        return None if s3obj else key

def nonsync_logging(request, key):
    """non-sync item will be logged here
    """
    if key:
        logger.info("Not Sync object - " + key)

def get_result_set(region, bucket, table, base):
    """get result set from storage object
    """
    connection = Connection(base, region)
    base = base.lower()
    storage_obj = None

    if base == "s3":
        storage_obj = S3(connection=connection.new_connection())
        storage_obj.set_storage_set_name(bucket)
    elif base == "dynamodb":
        storage_obj = DynamoDB(connection=connection.new_connection())
        storage_obj.set_storage_set_name(table)
    storage_set = storage_obj.get_storage_set()
    result_set = storage_obj.list(storage_set) if storage_set else None

    return result_set

def main(region, bucket, table, base, threadcnt):
    logger.info("Start to process as base %s, bucket=%s, table=%s" % (base, bucket, table))
    print base
    result_set = get_result_set(region, bucket, table, base)
    function = globals()[base + "_checker"]
    pool = lib.worker.ThreadPool(int(threadcnt))
    reqs = lib.worker.makeRequests(function, result_set, nonsync_logging)
    [pool.putRequest(req) for req in reqs]
    pool.wait()
    logger.info("End of process with base %s, bucket=%s, table=%s" % (base, bucket, table))

if __name__ == '__main__':
    # args
    parser = argparse.ArgumentParser(description='Central Storage S3 & DynamoDB verification tool')
    parser.add_argument("-r", "--region", type=str, help="target AWS region", required=True)
    parser.add_argument("-b", "--bucket", type=str, help="S3 bucket name", required=True)
    parser.add_argument("-t", "--table", type=str, help="DynamoDB table name", required=True)
    parser.add_argument("-c", "--threadcount", type=str, help="thread count", default="1", required=False)
    parser.add_argument("-a", "--base", type=str, help="s3 | dynamodb", default="s3", required=False)

    # logging
    logging.config.fileConfig('logging.ini', disable_existing_loggers=False, defaults={'logfilename': LOG_PATH})
    logger = logging.getLogger(__name__)

    # FIXME - file logging
    fh = logging.FileHandler(LOG_PATH)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    # parse args
    args = parser.parse_args()
    db_connection = Connection("dynamodb", args.region)
    db_table = args.table
    db = DynamoDB(connection=db_connection.new_connection())
    s3_connection = Connection("s3", args.region)
    s3_bucket = args.bucket
    s3 = S3(connection=s3_connection.new_connection())
    if db and s3:
        main(args.region, args.bucket, args.table, args.base, args.threadcount)
    else:
        raise ImportError("No DB connection")


text:
import { initializeTestEnvironment } from './tests.config';
import { Product, Brand } from '../src/pdm';

describe('Empiria Async Data Services', () => {

  beforeAll(() => {
    initializeTestEnvironment();
  });

  afterEach(function (done) {
    console.log('afterEach');
    done();
  });

  it('Should connect async to get a list of brands', function (done) {
    let observer = Brand.getListAsync();

    observer.subscribe(value => {
      console.log('This is the list of brands:\n' + JSON.stringify(value));
      expect(value).toBeTruthy();
    },
    error => console.log('error ' + error),
    () => done());
  });

  it('Should connect async to get a list of products', function (done) {
    let observer = Product.getListAsync('balata delantera ar');
    observer.subscribe(value => {
      console.log('This is the list of products:\n' + JSON.stringify(value));
      expect(value).toBeTruthy();
    },
    error => console.log('error ' + error),
    () => done());
  });

});  // describe


text:
from pysqlite2 import dbapi2 as sqlite
import re
import math

def getwords(doc):
  splitter=re.compile('\\W*')
  print doc
  # Split the words by non-alpha characters
  words=[s.lower() for s in splitter.split(doc)
          if len(s)>2 and len(s)<20]

  # Return the unique set of words only
  return dict([(w,1) for w in words])

class classifier:
  def __init__(self,getfeatures,filename=None):
    # Counts of feature/category combinations
    self.fc={}
    # Counts of documents in each category
    self.cc={}
    self.getfeatures=getfeatures

  def setdb(self,dbfile):
    self.con=sqlite.connect(dbfile)
    self.con.execute('create table if not exists fc(feature,category,count)')
    self.con.execute('create table if not exists cc(category,count)')

  def incf(self,f,cat):
    count=self.fcount(f,cat)
    if count==0:
      self.con.execute("insert into fc values ('%s','%s',1)"
                       % (f,cat))
    else:
      self.con.execute(
        "update fc set count=%d where feature='%s' and category='%s'"
        % (count+1,f,cat))

  def fcount(self,f,cat):
    res=self.con.execute(
      'select count from fc where feature="%s" and category="%s"'
      %(f,cat)).fetchone()
    if res==None: return 0
    else: return float(res[0])

  def incc(self,cat):
    count=self.catcount(cat)
    if count==0:
      self.con.execute("insert into cc values ('%s',1)" % (cat))
    else:
      self.con.execute("update cc set count=%d where category='%s'"
                       % (count+1,cat))

  def catcount(self,cat):
    res=self.con.execute('select count from cc where category="%s"'
                         %(cat)).fetchone()
    if res==None: return 0
    else: return float(res[0])

  def categories(self):
    cur=self.con.execute('select category from cc');
    return [d[0] for d in cur]

  def totalcount(self):
    res=self.con.execute('select sum(count) from cc').fetchone();
    if res==None: return 0
    return res[0]

  def train(self,item,cat):
    features=self.getfeatures(item)
    # Increment the count for every feature with this category
    for f in features:
      self.incf(f,cat)

    # Increment the count for this category
    self.incc(cat)
    self.con.commit()

  def fprob(self,f,cat):
    if self.catcount(cat)==0: return 0

    # The total number of times this feature appeared in this
    # category divided by the total number of items in this category
    return self.fcount(f,cat)/self.catcount(cat)

  def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):
    # Calculate current probability
    basicprob=prf(f,cat)

    # Count the number of times this feature has appeared in
    # all categories
    totals=sum([self.fcount(f,c) for c in self.categories()])

    # Calculate the weighted average
    bp=((weight*ap)+(totals*basicprob))/(weight+totals)
    return bp

class naivebayes(classifier):

  def __init__(self,getfeatures):
    classifier.__init__(self,getfeatures)
    self.thresholds={}

  def docprob(self,item,cat):
    features=self.getfeatures(item)

    # Multiply the probabilities of all the features together
    p=1
    for f in features: p*=self.weightedprob(f,cat,self.fprob)
    return p

  def prob(self,item,cat):
    catprob=self.catcount(cat)/self.totalcount()
    docprob=self.docprob(item,cat)
    return docprob*catprob

  def setthreshold(self,cat,t):
    self.thresholds[cat]=t

  def getthreshold(self,cat):
    if cat not in self.thresholds: return 1.0
    return self.thresholds[cat]

  def classify(self,item,default=None):
    probs={}
    # Find the category with the highest probability
    max=0.0
    for cat in self.categories():
      probs[cat]=self.prob(item,cat)
      if probs[cat]>max:
        max=probs[cat]
        best=cat

    # Make sure the probability exceeds threshold*next best
    for cat in probs:
      if cat==best: continue
      if probs[cat]*self.getthreshold(best)>probs[best]: return default
    return best

class fisherclassifier(classifier):
  def cprob(self,f,cat):
    # The frequency of this feature in this category
    clf=self.fprob(f,cat)
    if clf==0: return 0

    # The frequency of this feature in all the categories
    freqsum=sum([self.fprob(f,c) for c in self.categories()])

    # The probability is the frequency in this category divided by
    # the overall frequency
    p=clf/(freqsum)

    return p
  def fisherprob(self,item,cat):
    # Multiply all the probabilities together
    p=1
    features=self.getfeatures(item)
    for f in features:
      p*=(self.weightedprob(f,cat,self.cprob))

    # Take the natural log and multiply by -2
    fscore=-2*math.log(p)

    # Use the inverse chi2 function to get a probability
    return self.invchi2(fscore,len(features)*2)
  def invchi2(self,chi, df):
    m = chi / 2.0
    sum = term = math.exp(-m)
    for i in range(1, df//2):
        term *= m / i
        sum += term
    return min(sum, 1.0)
  def __init__(self,getfeatures):
    classifier.__init__(self,getfeatures)
    self.minimums={}

  def setminimum(self,cat,min):
    self.minimums[cat]=min

  def getminimum(self,cat):
    if cat not in self.minimums: return 0
    return self.minimums[cat]
  def classify(self,item,default=None):
    # Loop through looking for the best result
    best=default
    max=0.0
    for c in self.categories():
      p=self.fisherprob(item,c)
      # Make sure it exceeds its minimum
      if p>self.getminimum(c) and p>max:
        best=c
        max=p
    return best

def sampletrain(cl):
  cl.train('Nobody owns the water.','good')
  cl.train('the quick rabbit jumps fences','good')
  cl.train('buy pharmaceuticals now','bad')
  cl.train('make quick money at the online casino','bad')
  cl.train('the quick brown fox jumps','good')


text:
from models import storage
from models.base_model import BaseModel

print(BaseModel.__name__)
all_objs = storage.all()
print("-- Reloaded objects --")
for obj_id in all_objs.keys():
    obj = all_objs[obj_id]
    print(obj)

print("-- Create a new object --")
my_model = BaseModel()
my_model.name = "Holberton"
my_model.my_number = 89
my_model.save()
print(my_model)


text:
require 'spec_helper'

describe SmartIoC::BeanFileLoader do
  before :all do
    SmartIoC.clear

    dir_path = File.join(File.expand_path(File.dirname(__FILE__)), 'example/admins')
    SmartIoC.find_package_beans(:admins, dir_path)

    dir_path = File.join(File.expand_path(File.dirname(__FILE__)), 'example/utils')
    SmartIoC.find_package_beans(:utils, dir_path)

    dir_path = File.join(File.expand_path(File.dirname(__FILE__)), 'example/users')
    SmartIoC.find_package_beans(:users, dir_path)

    @container = SmartIoC.container
  end

  it 'sets load proc' do
    $location_loaded = false

    @container.set_load_proc do |location|
      $location_loaded = true
      load(location)
    end

    @container.get_bean(:users_creator)
    expect($location_loaded).to eq(true)
  end

  it 'requires beans only once' do
    repository = @container.get_bean(:repository, package: :admins, context: :test)
    repository = @container.get_bean(:repository, package: :admins, context: :test)
    expect(repository.get(1)).to eq(nil)
  end
end


text:
Spartan
=======

Spartan QMS (Quality Management System) - test automation and data management software.

Several of the submodules of this repository are not open source software and
must be obtained from their publishers/authors before the source for Spartan QMS
will build.  Please find references to obtain the required submodule source code
in the respective README files.

---
Contact Information

Kaelus, Inc.
12503 E. Euclid Dr.
Suite 7
Centennial, CO 80111
U.S.A.

(303) 768-8080
www.kaelus.com


text:
export default (params) => {
  params.mainWindow.on('focus', () => {
    params.mainWindow.webContents.send('isWindowFocused', true);
  });

  params.mainWindow.on('blur', () => {
    params.mainWindow.webContents.send('isWindowFocused', false);
  });
};


text:
<!DOCTYPE html>

    <title>Todo Item Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">

Hello, world!


text:
require 'open_weather_map/version'
require 'open_weather_map/base'

module OpenWeatherMap
  class City < Base
    def initialize(country, city)
      params = { q: "#{country},#{city}" }
      @response = request params
    end

  end

  class Geocode < Base
    def initialize(lat, lon)
      params = { lat: lat, lon: lon }
      @response = request params
    end

  end
end