text:
use syn::{self, aster};
use quote::Tokens;

use bound;
use internals::ast::{Body, Field, Item, Style, Variant};
use internals::{self, attr};

use std::iter;

pub fn expand_derive_deserialize(item: &syn::MacroInput) -> Result<Tokens, String> {
    let item = {
        let ctxt = internals::Ctxt::new();
        let item = Item::from_ast(&ctxt, item);
        check_no_str(&ctxt, &item);
        try!(ctxt.check());
        item
    };

    let impl_generics = build_impl_generics(&item);

    let ty = aster::ty().path()
        .segment(item.ident.clone()).with_generics(impl_generics.clone()).build()
        .build();

    let body = deserialize_body(&item,
                                &impl_generics,
                                ty.clone());

    let where_clause = &impl_generics.where_clause;

    let dummy_const = aster::id(format!("_IMPL_DESERIALIZE_FOR_{}", item.ident));

    Ok(quote! {
        #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
        const #dummy_const: () = {
            extern crate serde as _serde;
            #[automatically_derived]
            impl #impl_generics _serde::Deserialize for #ty #where_clause {
                fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<#ty, __D::Error>
                    where __D: _serde::Deserializer
                #body
            }
        };
    })
}

// All the generics in the input, plus a bound `T: Deserialize` for each generic
// field type that will be deserialized by us, plus a bound `T: Default` for
// each generic field type that will be set to a default value.
fn build_impl_generics(item: &Item) -> syn::Generics {
    let generics = bound::without_defaults(item.generics);

    let generics = bound::with_where_predicates_from_fields(
        item, &generics,
        |attrs| attrs.de_bound());

    match item.attrs.de_bound() {
        Some(predicates) => {
            bound::with_where_predicates(&generics, predicates)
        }
        None => {
            let generics = bound::with_bound(item, &generics,
                needs_deserialize_bound,
                &aster::path().ids(&["_serde", "de", "Deserialize"]).build());
            bound::with_bound(item, &generics,
                requires_default,
                &aster::path().global().ids(&["std", "default", "Default"]).build())
        }
    }
}

// Fields with a `skip_deserializing` or `deserialize_with` attribute are not
// deserialized by us so we do not generate a bound. Fields with a `bound`
// attribute specify their own bound so we do not generate one. All other fields
// may need a `T: Deserialize` bound where T is the type of the field.
fn needs_deserialize_bound(attrs: &attr::Field) -> bool {
    !attrs.skip_deserializing()
        && attrs.deserialize_with().is_none()
        && attrs.de_bound().is_none()
}

// Fields with a `default` attribute (not `default=...`), and fields with a
// `skip_deserializing` attribute that do not also have `default=...`.
fn requires_default(attrs: &attr::Field) -> bool {
    attrs.default() == &attr::FieldDefault::Default
}

fn deserialize_body(
    item: &Item,
    impl_generics: &syn::Generics,
    ty: syn::Ty,
) -> Tokens {
    match item.body {
        Body::Enum(ref variants) => {
            deserialize_item_enum(
                &item.ident,
                impl_generics,
                ty,
                variants,
                &item.attrs)
        }
        Body::Struct(Style::Struct, ref fields) => {
            if fields.iter().any(|field| field.ident.is_none()) {
                panic!("struct has unnamed fields");
            }

            deserialize_struct(
                &item.ident,
                None,
                impl_generics,
                ty,
                fields,
                &item.attrs)
        }
        Body::Struct(Style::Tuple, ref fields) |
        Body::Struct(Style::Newtype, ref fields) => {
            if fields.iter().any(|field| field.ident.is_some()) {
                panic!("tuple struct has named fields");
            }

            deserialize_tuple(
                &item.ident,
                None,
                impl_generics,
                ty,
                fields,
                &item.attrs)
        }
        Body::Struct(Style::Unit, _) => {
            deserialize_unit_struct(
                &item.ident,
                &item.attrs)
        }
    }
}

// Build `__Visitor<A, B, ...>(PhantomData<A>, PhantomData<B>, ...)`
//
// Returns:
//
//     1. the struct declaration
//     2. the visitor type, including generics
//     3. the expression for instantiating the visitor
fn deserialize_visitor(generics: &syn::Generics) -> (Tokens, Tokens, Tokens) {
    if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
        (
            quote! {
                struct __Visitor;
            },
            quote!(__Visitor),
            quote!(__Visitor),
        )
    } else {
        let where_clause = &generics.where_clause;

        let num_phantoms = generics.lifetimes.len() + generics.ty_params.len();

        let phantom_types = generics.lifetimes.iter()
            .map(|lifetime_def| {
                let lifetime = &lifetime_def.lifetime;
                quote!(::std::marker::PhantomData<& #lifetime ()>)
            }).chain(generics.ty_params.iter()
                .map(|ty_param| {
                    let ident = &ty_param.ident;
                    quote!(::std::marker::PhantomData<#ident>)
                }));

        let all_params = generics.lifetimes.iter()
            .map(|lifetime_def| {
                let lifetime = &lifetime_def.lifetime;
                quote!(#lifetime)
            }).chain(generics.ty_params.iter()
                .map(|ty_param| {
                    let ident = &ty_param.ident;
                    quote!(#ident)
                }));

        let ty_param_idents: Vec<_> = generics.ty_params.iter()
            .map(|t| {
                let ident = &t.ident;
                quote!(#ident)
            })
            .collect();

        let ty_param_idents = if ty_param_idents.is_empty() {
            None
        } else {
            Some(quote!(::<#(#ty_param_idents),*>))
        };

        let phantom_exprs = iter::repeat(quote!(::std::marker::PhantomData)).take(num_phantoms);

        (
            quote! {
                struct __Visitor #generics ( #(#phantom_types),* ) #where_clause;
            },
            quote!(__Visitor <#(#all_params),*> ),
            quote!(__Visitor #ty_param_idents ( #(#phantom_exprs),* )),
        )
    }
}

fn deserialize_unit_struct(
    type_ident: &syn::Ident,
    item_attrs: &attr::Item,
) -> Tokens {
    let type_name = item_attrs.name().deserialize_name();

    quote!({
        struct __Visitor;

        impl _serde::de::Visitor for __Visitor {
            type Value = #type_ident;

            #[inline]
            fn visit_unit<__E>(&mut self) -> ::std::result::Result<#type_ident, __E>
                where __E: _serde::de::Error,
            {
                Ok(#type_ident)
            }

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#type_ident, __V::Error>
                where __V: _serde::de::SeqVisitor,
            {
                try!(visitor.end());
                self.visit_unit()
            }
        }

        deserializer.deserialize_unit_struct(#type_name, __Visitor)
    })
}

fn deserialize_tuple(
    type_ident: &syn::Ident,
    variant_ident: Option<&syn::Ident>,
    impl_generics: &syn::Generics,
    ty: syn::Ty,
    fields: &[Field],
    item_attrs: &attr::Item,
) -> Tokens {
    let where_clause = &impl_generics.where_clause;

    let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);

    let is_enum = variant_ident.is_some();
    let type_path = match variant_ident {
        Some(variant_ident) => quote!(#type_ident::#variant_ident),
        None => quote!(#type_ident),
    };

    let nfields = fields.len();

    let visit_newtype_struct = if !is_enum && nfields == 1 {
        Some(deserialize_newtype_struct(
            type_ident,
            &type_path,
            impl_generics,
            &fields[0],
        ))
    } else {
        None
    };

    let visit_seq = deserialize_seq(
        type_ident,
        &type_path,
        impl_generics,
        fields,
        false,
    );

    let dispatch = if is_enum {
        quote!(visitor.visit_tuple(#nfields, #visitor_expr))
    } else if nfields == 1 {
        let type_name = item_attrs.name().deserialize_name();
        quote!(deserializer.deserialize_newtype_struct(#type_name, #visitor_expr))
    } else {
        let type_name = item_attrs.name().deserialize_name();
        quote!(deserializer.deserialize_tuple_struct(#type_name, #nfields, #visitor_expr))
    };

    quote!({
        #visitor_item

        impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
            type Value = #ty;

            #visit_newtype_struct

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
                where __V: _serde::de::SeqVisitor
            {
                #visit_seq
            }
        }

        #dispatch
    })
}

fn deserialize_seq(
    type_ident: &syn::Ident,
    type_path: &Tokens,
    impl_generics: &syn::Generics,
    fields: &[Field],
    is_struct: bool,
) -> Tokens {
    let mut index_in_seq = 0usize;
    let let_values: Vec<_> = fields.iter()
        .enumerate()
        .map(|(i, field)| {
            let name = aster::id(format!("__field{}", i));
            if field.attrs.skip_deserializing() {
                let default = expr_is_missing(&field.attrs);
                quote! {
                    let #name = #default;
                }
            } else {
                let visit = match field.attrs.deserialize_with() {
                    None => {
                        let field_ty = &field.ty;
                        quote!(try!(visitor.visit::<#field_ty>()))
                    }
                    Some(path) => {
                        let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                            type_ident, impl_generics, field.ty, path);
                        quote!({
                            #wrapper
                            #wrapper_impl
                            try!(visitor.visit::<#wrapper_ty>()).map(|wrap| wrap.value)
                        })
                    }
                };
                let assign = quote! {
                    let #name = match #visit {
                        Some(value) => { value },
                        None => {
                            try!(visitor.end());
                            return Err(_serde::de::Error::invalid_length(#index_in_seq));
                        }
                    };
                };
                index_in_seq += 1;
                assign
            }
        })
        .collect();

    let result = if is_struct {
        let args = fields.iter()
            .enumerate()
            .map(|(i, field)| {
                let ident = field.ident.clone().expect("struct contains unnamed fields");
                let value = aster::id(format!("__field{}", i));
                quote!(#ident: #value)
            });
        quote! {
            #type_path { #(#args),* }
        }
    } else {
        let args = (0..fields.len()).map(|i| aster::id(format!("__field{}", i)));
        quote! {
            #type_path ( #(#args),* )
        }
    };

    quote! {
        #(#let_values)*

        try!(visitor.end());

        Ok(#result)
    }
}

fn deserialize_newtype_struct(
    type_ident: &syn::Ident,
    type_path: &Tokens,
    impl_generics: &syn::Generics,
    field: &Field,
) -> Tokens {
    let value = match field.attrs.deserialize_with() {
        None => {
            let field_ty = &field.ty;
            quote! {
                try!(<#field_ty as _serde::Deserialize>::deserialize(__e))
            }
        }
        Some(path) => {
            let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                type_ident, impl_generics, field.ty, path);
            quote!({
                #wrapper
                #wrapper_impl
                try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value
            })
        }
    };
    quote! {
        #[inline]
        fn visit_newtype_struct<__E>(&mut self, __e: &mut __E) -> ::std::result::Result<Self::Value, __E::Error>
            where __E: _serde::Deserializer,
        {
            Ok(#type_path(#value))
        }
    }
}

fn deserialize_struct(
    type_ident: &syn::Ident,
    variant_ident: Option<&syn::Ident>,
    impl_generics: &syn::Generics,
    ty: syn::Ty,
    fields: &[Field],
    item_attrs: &attr::Item,
) -> Tokens {
    let where_clause = &impl_generics.where_clause;

    let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);

    let type_path = match variant_ident {
        Some(variant_ident) => quote!(#type_ident::#variant_ident),
        None => quote!(#type_ident),
    };

    let visit_seq = deserialize_seq(
        type_ident,
        &type_path,
        impl_generics,
        fields,
        true,
    );

    let (field_visitor, fields_stmt, visit_map) = deserialize_struct_visitor(
        type_ident,
        type_path,
        impl_generics,
        fields,
        item_attrs,
    );

    let is_enum = variant_ident.is_some();
    let dispatch = if is_enum {
        quote! {
            visitor.visit_struct(FIELDS, #visitor_expr)
        }
    } else {
        let type_name = item_attrs.name().deserialize_name();
        quote! {
            deserializer.deserialize_struct(#type_name, FIELDS, #visitor_expr)
        }
    };

    quote!({
        #field_visitor

        #visitor_item

        impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
            type Value = #ty;

            #[inline]
            fn visit_seq<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
                where __V: _serde::de::SeqVisitor
            {
                #visit_seq
            }

            #[inline]
            fn visit_map<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
                where __V: _serde::de::MapVisitor
            {
                #visit_map
            }
        }

        #fields_stmt

        #dispatch
    })
}

fn deserialize_item_enum(
    type_ident: &syn::Ident,
    impl_generics: &syn::Generics,
    ty: syn::Ty,
    variants: &[Variant],
    item_attrs: &attr::Item
) -> Tokens {
    let where_clause = &impl_generics.where_clause;

    let type_name = item_attrs.name().deserialize_name();

    let variant_visitor = deserialize_field_visitor(
        variants.iter()
            .filter(|variant| !variant.attrs.skip_deserializing())
            .map(|variant| variant.attrs.name().deserialize_name())
            .collect(),
        item_attrs,
        true,
    );

    let variant_names = variants.iter().map(|variant| variant.ident.to_string());

    let variants_stmt = quote! {
        const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ];
    };

    // Match arms to extract a variant from a string
    let mut variant_arms = vec![];
    for (i, variant) in variants.iter().filter(|variant| !variant.attrs.skip_deserializing()).enumerate() {
        let variant_name = aster::id(format!("__field{}", i));
        let variant_name = quote!(__Field::#variant_name);

        let block = deserialize_variant(
            type_ident,
            impl_generics,
            ty.clone(),
            variant,
            item_attrs,
        );

        let arm = quote! {
            #variant_name => #block
        };
        variant_arms.push(arm);
    }

    let match_variant = if variant_arms.is_empty() {
        // This is an empty enum like `enum Impossible {}` or an enum in which
        // all variants have `#[serde(skip_deserializing)]`.
        quote! {
            // FIXME: Once we drop support for Rust 1.15:
            // let Err(err) = visitor.visit_variant::<__Field>();
            // Err(err)
            visitor.visit_variant::<__Field>().map(|impossible| match impossible {})
        }
    } else {
        quote! {
            match try!(visitor.visit_variant()) {
                #(#variant_arms)*
            }
        }
    };

    let (visitor_item, visitor_ty, visitor_expr) = deserialize_visitor(impl_generics);

    quote!({
        #variant_visitor

        #visitor_item

        impl #impl_generics _serde::de::Visitor for #visitor_ty #where_clause {
            type Value = #ty;

            fn visit_enum<__V>(&mut self, mut visitor: __V) -> ::std::result::Result<#ty, __V::Error>
                where __V: _serde::de::VariantVisitor,
            {
                #match_variant
            }
        }

        #variants_stmt

        deserializer.deserialize_enum(#type_name, VARIANTS, #visitor_expr)
    })
}

fn deserialize_variant(
    type_ident: &syn::Ident,
    generics: &syn::Generics,
    ty: syn::Ty,
    variant: &Variant,
    item_attrs: &attr::Item,
) -> Tokens {
    let variant_ident = &variant.ident;

    match variant.style {
        Style::Unit => {
            quote!({
                try!(visitor.visit_unit());
                Ok(#type_ident::#variant_ident)
            })
        }
        Style::Newtype => {
            deserialize_newtype_variant(
                type_ident,
                variant_ident,
                generics,
                &variant.fields[0],
            )
        }
        Style::Tuple => {
            deserialize_tuple(
                type_ident,
                Some(variant_ident),
                generics,
                ty,
                &variant.fields,
                item_attrs,
            )
        }
        Style::Struct => {
            deserialize_struct(
                type_ident,
                Some(variant_ident),
                generics,
                ty,
                &variant.fields,
                item_attrs,
            )
        }
    }
}

fn deserialize_newtype_variant(
    type_ident: &syn::Ident,
    variant_ident: &syn::Ident,
    impl_generics: &syn::Generics,
    field: &Field,
) -> Tokens {
    let visit = match field.attrs.deserialize_with() {
        None => {
            let field_ty = &field.ty;
            quote!(try!(visitor.visit_newtype::<#field_ty>()))
        }
        Some(path) => {
            let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                type_ident, impl_generics, field.ty, path);
            quote!({
                #wrapper
                #wrapper_impl
                try!(visitor.visit_newtype::<#wrapper_ty>()).value
            })
        }
    };
    quote! {
        Ok(#type_ident::#variant_ident(#visit)),
    }
}

fn deserialize_field_visitor(
    field_names: Vec<String>,
    item_attrs: &attr::Item,
    is_variant: bool,
) -> Tokens {
    // Create the field names for the fields.
    let field_idents: &Vec<_> = &(0 .. field_names.len())
        .map(|i| aster::id(format!("__field{}", i)))
        .collect();

    let ignore_variant = if is_variant || item_attrs.deny_unknown_fields() {
        None
    } else {
        Some(quote!(__ignore,))
    };

    let fallthrough_arm = if is_variant {
        quote! {
            Err(_serde::de::Error::unknown_variant(value))
        }
    } else if item_attrs.deny_unknown_fields() {
        quote! {
            Err(_serde::de::Error::unknown_field(value))
        }
    } else {
        quote! {
            Ok(__Field::__ignore)
        }
    };

    quote! {
        #[allow(non_camel_case_types)]
        enum __Field {
            #(#field_idents,)*
            #ignore_variant
        }

        impl _serde::Deserialize for __Field {
            #[inline]
            fn deserialize<__D>(deserializer: &mut __D) -> ::std::result::Result<__Field, __D::Error>
                where __D: _serde::Deserializer,
            {
                struct __FieldVisitor;

                impl _serde::de::Visitor for __FieldVisitor {
                    type Value = __Field;

                    fn visit_str<__E>(&mut self, value: &str) -> ::std::result::Result<__Field, __E>
                        where __E: _serde::de::Error
                    {
                        match value {
                            #(
                                #field_names => Ok(__Field::#field_idents),
                            )*
                            _ => #fallthrough_arm
                        }
                    }
                }

                deserializer.deserialize_struct_field(__FieldVisitor)
            }
        }
    }
}

fn deserialize_struct_visitor(
    type_ident: &syn::Ident,
    struct_path: Tokens,
    impl_generics: &syn::Generics,
    fields: &[Field],
    item_attrs: &attr::Item,
) -> (Tokens, Tokens, Tokens) {
    let field_exprs = fields.iter()
        .map(|field| field.attrs.name().deserialize_name())
        .collect();

    let field_visitor = deserialize_field_visitor(
        field_exprs,
        item_attrs,
        false,
    );

    let visit_map = deserialize_map(
        type_ident,
        struct_path,
        impl_generics,
        fields,
        item_attrs,
    );

    let field_names = fields.iter().map(|field| {
        field.ident.clone().expect("struct contains unnamed field").to_string()
    });

    let fields_stmt = quote! {
        const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
    };

    (field_visitor, fields_stmt, visit_map)
}

fn deserialize_map(
    type_ident: &syn::Ident,
    struct_path: Tokens,
    impl_generics: &syn::Generics,
    fields: &[Field],
    item_attrs: &attr::Item,
) -> Tokens {
    if fields.is_empty() && item_attrs.deny_unknown_fields() {
        return quote! {
            // FIXME: Once we drop support for Rust 1.15:
            // let None::<__Field> = try!(visitor.visit_key());
            try!(visitor.visit_key::<__Field>()).map(|impossible| match impossible {});
            try!(visitor.end());
            Ok(#struct_path {})
        };
    }

    // Create the field names for the fields.
    let fields_names = fields.iter()
        .enumerate()
        .map(|(i, field)|
             (field, aster::id(format!("__field{}", i))))
        .collect::<Vec<_>>();

    // Declare each field that will be deserialized.
    let let_values: Vec<_> = fields_names.iter()
        .filter(|&&(field, _)| !field.attrs.skip_deserializing())
        .map(|&(field, ref name)| {
            let field_ty = &field.ty;
            quote! {
                let mut #name: Option<#field_ty> = None;
            }
        })
        .collect();

    // Match arms to extract a value for a field.
    let value_arms = fields_names.iter()
        .filter(|&&(field, _)| !field.attrs.skip_deserializing())
        .map(|&(field, ref name)| {
            let deser_name = field.attrs.name().deserialize_name();

            let visit = match field.attrs.deserialize_with() {
                None => {
                    let field_ty = &field.ty;
                    quote! {
                        try!(visitor.visit_value::<#field_ty>())
                    }
                }
                Some(path) => {
                    let (wrapper, wrapper_impl, wrapper_ty) = wrap_deserialize_with(
                        type_ident, impl_generics, field.ty, path);
                    quote!({
                        #wrapper
                        #wrapper_impl
                        try!(visitor.visit_value::<#wrapper_ty>()).value
                    })
                }
            };
            quote! {
                __Field::#name => {
                    if #name.is_some() {
                        return Err(<__V::Error as _serde::de::Error>::duplicate_field(#deser_name));
                    }
                    #name = Some(#visit);
                }
            }
        })
        .collect::<Vec<_>>();

    // Match arms to ignore value for fields that have `skip_deserializing`.
    // Ignored even if `deny_unknown_fields` is set.
    let skipped_arms = fields_names.iter()
        .filter(|&&(field, _)| field.attrs.skip_deserializing())
        .map(|&(_, ref name)| {
            quote! {
                __Field::#name => {
                    let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>());
                }
            }
        })
        .collect::<Vec<_>>();

    // Visit ignored values to consume them
    let ignored_arm = if item_attrs.deny_unknown_fields() {
        None
    } else {
        Some(quote! {
            _ => { let _ = try!(visitor.visit_value::<_serde::de::impls::IgnoredAny>()); }
        })
    };

    let extract_values = fields_names.iter()
        .filter(|&&(field, _)| !field.attrs.skip_deserializing())
        .map(|&(field, ref name)| {
            let missing_expr = expr_is_missing(&field.attrs);

            quote! {
                let #name = match #name {
                    Some(#name) => #name,
                    None => #missing_expr
                };
            }
        })
        .collect::<Vec<_>>();

    let result = fields_names.iter()
        .map(|&(field, ref name)| {
            let ident = field.ident.clone().expect("struct contains unnamed fields");
            let value = if field.attrs.skip_deserializing() {
                expr_is_missing(&field.attrs)
            } else {
                quote!(#name)
            };
            quote!(#ident: #value)
        });

    quote! {
        #(#let_values)*

        while let Some(key) = try!(visitor.visit_key::<__Field>()) {
            match key {
                #(#value_arms)*
                #(#skipped_arms)*
                #ignored_arm
            }
        }

        try!(visitor.end());

        #(#extract_values)*

        Ok(#struct_path { #(#result),* })
    }
}

/// This function wraps the expression in `#[serde(deserialize_with="...")]` in
/// a trait to prevent it from accessing the internal `Deserialize` state.
fn wrap_deserialize_with(
    type_ident: &syn::Ident,
    impl_generics: &syn::Generics,
    field_ty: &syn::Ty,
    deserialize_with: &syn::Path,
) -> (Tokens, Tokens, syn::Path) {
    // Quasi-quoting doesn't do a great job of expanding generics into paths,
    // so manually build it.
    let wrapper_ty = aster::path()
        .segment("__SerdeDeserializeWithStruct")
            .with_generics(impl_generics.clone())
            .build()
        .build();

    let where_clause = &impl_generics.where_clause;

    let phantom_ty = aster::path()
        .segment(type_ident)
            .with_generics(aster::from_generics(impl_generics.clone())
                .strip_ty_params()
                .build())
            .build()
        .build();

    (
        quote! {
            struct __SerdeDeserializeWithStruct #impl_generics #where_clause {
                value: #field_ty,
                phantom: ::std::marker::PhantomData<#phantom_ty>,
            }
        },
        quote! {
            impl #impl_generics _serde::Deserialize for #wrapper_ty #where_clause {
                fn deserialize<__D>(__d: &mut __D) -> ::std::result::Result<Self, __D::Error>
                    where __D: _serde::Deserializer
                {
                    let value = try!(#deserialize_with(__d));
                    Ok(__SerdeDeserializeWithStruct {
                        value: value,
                        phantom: ::std::marker::PhantomData,
                    })
                }
            }
        },
        wrapper_ty,
    )
}

fn expr_is_missing(attrs: &attr::Field) -> Tokens {
    match *attrs.default() {
        attr::FieldDefault::Default => {
            return quote!(::std::default::Default::default());
        }
        attr::FieldDefault::Path(ref path) => {
            return quote!(#path());
        }
        attr::FieldDefault::None => { /* below */ }
    }

    let name = attrs.name().deserialize_name();
    match attrs.deserialize_with() {
        None => {
            quote! {
                try!(visitor.missing_field(#name))
            }
        }
        Some(_) => {
            quote! {
                return Err(<__V::Error as _serde::de::Error>::missing_field(#name))
            }
        }
    }
}

fn check_no_str(cx: &internals::Ctxt, item: &Item) {
    let fail = || {
        cx.error(
            "Serde does not support deserializing fields of type &str; \
             consider using String instead");
    };

    for field in item.body.all_fields() {
        if field.attrs.skip_deserializing()
            || field.attrs.deserialize_with().is_some() { continue }

        if let syn::Ty::Rptr(_, ref inner) = *field.ty {
            if let syn::Ty::Path(_, ref path) = inner.ty {
                if path.segments.len() == 1 && path.segments[0].ident == "str" {
                    fail();
                    return;
                }
            }
        }
    }
}


text:
import requests

import mavri

wiki = 'tr.wikipedia'
xx = mavri.login(wiki, 'Mavrikant')
user = '71.191.3.59'
usercontribs = requests.get(
    'https://tr.wikipedia.org/w/api.php?action=query&list=usercontribs&format=json&uclimit=500&ucuser=' + user,
    cookies=xx.cookies)

for cont in usercontribs.json()['query']['usercontribs']:
    diff = cont['revid']
    print mavri.review_diff('tr.wikipedia', diff, xx).text

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.rho.rhoelements.plugins;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.rho.rhoelements.Common;
import com.rho.rhoelements.LogEntry;
import com.rho.rhoelements.NavigateException;
import com.rho.rhoelements.PluginSetting;
import com.rho.rhoelements.Version;
import com.rho.rhoelements.graphics.BatteryIndicator;

/**
 * @author FPC843
 *
 */
public class BatteryPlugin extends Plugin
{

	//TODO: Has to be tested whether, when non in FG and stopped by Android, if Helium gets back
	//      to the FG if it reloads the meta tags (and then updating the indicator status).

	//TODO: In case asynchronorus doesn't work well, let's implement polling like for the SignalPlugin

	private static final String	PARAM_GRAPHPOSITION	= "graphposition";
	private static final String	PARAM_ICONPOSITION	= "iconposition";
	private static final String	PARAM_LAYOUT		= "layout";
	private static final String	VALUE_UP			= "up";
	private static final String	VALUE_DOWN			= "down";

	private static final short NORMALISATION = 10;

	/*
	 * We only have 3 values for the Battery Event
	 * 		AC Line Status
	 * 		Battery Life Percent
	 * 		Backup Battery life percent
	 */
	private static final short BATTERY_EVENT_VALUES = 3;

	/*
	 * No Backup battery for Android
	 */
	private static final String BACKUP_BATTERY_LIFE = "0";

	private String batteryUrl;
	private BatteryIndicator batteryIndicator;
	private int batteryLevel = -1;
	private boolean isPowerConnected = false;

	private static final String[] NAMES = new String[] {
		"acLineStatus",
		"batteryLifePercent",
	"backupBatteryLifePercent"};

	private String[] values = new String[BATTERY_EVENT_VALUES];

	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context arg0, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED))
			{
				batteryLevel = intent.getIntExtra("level", 0);
				if (intent.getIntExtra("plugged", 0) == 0)
					isPowerConnected = false;
				else
					isPowerConnected = true;
			}
			passValuesToEvent();
			redrawBatteryIndicator();
		}
	};

	/**
	 * @return The version of this plugin being built
	 */
	public static Version getVersion()
	{
		return new Version ("Battery");
	}

	public BatteryPlugin()
	{
		Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, null));
		//This value never changes as there is no backup battery
		values[2] = BACKUP_BATTERY_LIFE;

		// Get signal indicator via indicator panel
		this.batteryIndicator = Common.elementsCore.getIndicatorPanel().getBatteryIndicator();

		batteryIndicator.setVisible(false);
		batteryIndicator.setPaintColor("#000000");

		Common.mainActivity.registerReceiver(this.mBatInfoReceiver,
				new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		getBatteryProperties();
		batteryUrl = null;
	}

	/**************************************************************************/
	@Override
	public void onShutdown()
	{
		batteryIndicator.reset();
		Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, null));
		try
		{
		Common.mainActivity.unregisterReceiver(this.mBatInfoReceiver);
		}
		catch (IllegalArgumentException e)
		{
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_ERROR, "Battery Receiver wasn't registered"));
		}
	}

	/**************************************************************************/
	@Override
	public void onSetting(PluginSetting setting)
	{
		getBatteryProperties();
		if (setting.getValue().length() > 0)
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, String.format("'%s', '%s'", setting.getName(), setting.getValue())));
		else
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, setting.getName()));

		if (setting.getName().equalsIgnoreCase("batteryevent"))
		{
			batteryUrl = setting.getValue();
			if (batteryUrl.length() > 0)
				passValuesToEvent();
		}
		else if (setting.getName().equalsIgnoreCase("visibility"))
		{
			if(setting.getValue().equalsIgnoreCase("visible"))
			{
				batteryIndicator.setVisible(true);
				batteryIndicator.reDraw();
			}
			else if(setting.getValue().equalsIgnoreCase("hidden"))
			{
				batteryIndicator.setVisible(false);
				batteryIndicator.reDraw();
			}
			else
			{
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid visibility value '" + setting.getValue() + "'"));
			}
		}
		else if (setting.getName().equalsIgnoreCase("left"))
		{
			try
			{
				int xPosition = Integer.parseInt(setting.getValue());
				batteryIndicator.setxPosition(xPosition, true);
				batteryIndicator.reDraw();
			}
			catch(NumberFormatException e)
			{
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid left value: " + setting.getValue()));
			}
		}
		else if (setting.getName().equalsIgnoreCase("top"))
		{
			try
			{
				int yPosition = Integer.parseInt(setting.getValue());
				batteryIndicator.setyPosition(yPosition, true);
				batteryIndicator.reDraw();
			}
			catch(NumberFormatException e)
			{
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid top value: " + setting.getValue()));
			}
		}
/*		else if (setting.getName().equalsIgnoreCase("right"))
		{
			try
			{
				int xPosition = Integer.parseInt(setting.getValue());
				batteryIndicator.setxPosition(xPosition, false);
			}
			catch(NumberFormatException e)
			{
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid right value: " + setting.getValue()));
			}
		}
		else if (setting.getName().equalsIgnoreCase("bottom"))
		{
			try
			{
				int yPosition = Integer.parseInt(setting.getValue());
				batteryIndicator.setyPosition(yPosition, false);
			}
			catch(NumberFormatException e)
			{
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid bottom value: " + setting.getValue()));
			}
		}*/
		else if (setting.getName().equalsIgnoreCase(PARAM_ICONPOSITION))
		{
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, PARAM_ICONPOSITION + " is no longer supported. Please use " + PARAM_LAYOUT + " instead"));
		}
		else if (setting.getName().equalsIgnoreCase(PARAM_GRAPHPOSITION))
		{
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_INFO, PARAM_GRAPHPOSITION + " has been deprecated but is still usable. In the future please use \"" + PARAM_LAYOUT + "\"."));
			setLayout(setting.getValue());
		}
		else if (setting.getName().equalsIgnoreCase(PARAM_LAYOUT))
		{
			setLayout(setting.getValue());
		}
		else if (setting.getName().equalsIgnoreCase("color"))
			batteryIndicator.setPaintColor(setting.getValue()); //Validation checking for color is in Indicator class
		else
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Unknown setting '" + setting.getName() + "'"));

//		redrawBatteryIndicator();

		// TODO Add check interval property (extra to PB3)
	}

	/**
	 * Sets the layout of the battery indicator
	 * @param value the layout String: "up"/"down"/"left"/"right"/("top")/("bottom")
	 */
	private void setLayout(String value)
	{
		if (value.equalsIgnoreCase("left"))
		{
			batteryIndicator.setLayout(BatteryIndicator.LEFT);
			batteryIndicator.reDraw();
		}
		else if (value.equalsIgnoreCase("right"))
		{
			batteryIndicator.setLayout(BatteryIndicator.RIGHT);
			batteryIndicator.reDraw();
		}
		else if (value.equalsIgnoreCase("top") || value.equalsIgnoreCase(VALUE_UP))
		{
			batteryIndicator.setLayout(BatteryIndicator.UP);
			batteryIndicator.reDraw();
		}
		else if (value.equalsIgnoreCase("bottom") || value.equalsIgnoreCase(VALUE_DOWN))
		{
			batteryIndicator.setLayout(BatteryIndicator.DOWN);
			batteryIndicator.reDraw();
		}
		else
		{
			Common.logger.add(new LogEntry(LogEntry.PB_LOG_WARNING, "Invalid layout '" + value + "'"));
		}
	}

	@Override
	public void onPageStarted(String url)
	{
		batteryUrl = null;
	}

	private void getBatteryProperties()
	{
		Intent batteryIntent = Common.mainActivity.getApplicationContext().registerReceiver(null,
				new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		batteryLevel = batteryIntent.getIntExtra("level", -1);
		if (batteryIntent.getIntExtra("plugged", 0) == 0)
			isPowerConnected = false;
		else
			isPowerConnected = true;
	}

	private void redrawBatteryIndicator()
	{
		batteryIndicator.setValue(batteryLevel / NORMALISATION);
		batteryIndicator.setCharging(isPowerConnected);
		batteryIndicator.reDraw();
	}

	private void passValuesToEvent()
	{
		values[1] = String.valueOf(batteryLevel);
		if (isPowerConnected)
			values[0] = "1";
		else
			values[0] = "0";
		if(batteryUrl != null)
		{
			try
			{
				navigate(batteryUrl, NAMES, values);
			}
			catch (NavigateException e)
			{
				e.printStackTrace();
				Common.logger.add(new LogEntry(LogEntry.PB_LOG_ERROR, "Navigate Exception.. length is " + e.GetLength()));
			}
		}
	}
}


text:
<?php

namespace Backend\Modules\Blog\Actions;

use Backend\Core\Engine\Base\ActionDelete as BackendBaseActionDelete;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Blog\Engine\Model as BackendBlogModel;

/**
 * This action will delete a category
 *
 * @author Davy Hellemans <davy.hellemans@netlash.com>
 */
class DeleteCategory extends BackendBaseActionDelete
{
    /**
     * Execute the action
     */
    public function execute()
    {
        $this->id = $this->getParameter('id', 'int');

        // does the item exist
        if ($this->id !== null && BackendBlogModel::existsCategory($this->id)) {
            // get data
            $this->record = (array) BackendBlogModel::getCategory($this->id);

            // allowed to delete the category?
            if (BackendBlogModel::deleteCategoryAllowed($this->id)) {
                // call parent, this will probably add some general CSS/JS or other required files
                parent::execute();

                // delete item
                BackendBlogModel::deleteCategory($this->id);

                // trigger event
                BackendModel::triggerEvent($this->getModule(), 'after_delete_category', array('id' => $this->id));

                // category was deleted, so redirect
                $this->redirect(
                    BackendModel::createURLForAction('Categories') . '&report=deleted-category&var=' .
                    urlencode($this->record['title'])
                );
            } else {
                $this->redirect(
                    // delete category not allowed
                    BackendModel::createURLForAction('Categories') . '&error=delete-category-not-allowed&var=' .
                    urlencode($this->record['title'])
                );
            }
        } else {
            // something went wrong
            $this->redirect(BackendModel::createURLForAction('Categories') . '&error=non-existing');
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>gitcodePl</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

        <acme-navbar creationDate="main.creationDate" />

'Allo, 'Allo!

          Always a pleasure scaffolding your apps.

          <button type="button" class="btn btn-lg btn-success" ng-click="main.showToastr()">Splendid Toastr</button>

          With ♥ thanks to the contributions of<acme-malarkey extra-values="['Yeoman', 'Gulp', 'Angular']" />

{{ awesomeThing.title }}

{{ awesomeThing.description }}

{{ awesomeThing.url }}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hymenomyc. eur. (Upsaliae) 301 (1874)

#### Original name
Agaricus comtulus Fr., 1838

### Remarks
null


text:
package de.heikoseeberger.constructr

import akka.Done
import akka.actor.FSM.Failure
import akka.actor.{ Address, FSM, Props, Status }
import akka.cluster.Cluster
import akka.cluster.ClusterEvent.{ InitialStateAsEvents, MemberJoined, MemberUp }
import akka.pattern.pipe
import akka.stream.ActorMaterializer
import de.heikoseeberger.constructr.coordination.Coordination
import scala.concurrent.duration.{ Duration, FiniteDuration }

object ConstructrMachine {

  implicit class DurationOps(val duration: Duration) extends AnyVal {

    def toFinite: FiniteDuration =
      duration match {
        case Duration(n, unit) => Duration(n, unit)
        case _                 => throw new IllegalStateException("Infinite duration!")
      }
  }

  sealed trait State
  final object State {
    case object GettingNodes     extends State
    case object Locking          extends State
    case object Joining          extends State
    case object AddingSelf       extends State
    case object RefreshScheduled extends State
    case object Refreshing       extends State
    case object RetryScheduled   extends State
  }

  final case class Data(nodes: Set[Address], retryState: State, nrOfRetriesLeft: Int)

  final case class StateTimeoutException(state: State)
      extends RuntimeException(s"State timeout triggered in state $state!")

  final val Name = "constructr-machine"

  def props(
      selfNode: Address,
      coordination: Coordination,
      coordinationTimeout: FiniteDuration,
      coordinationRetries: Int,
      retryDelay: FiniteDuration,
      refreshInterval: FiniteDuration,
      ttlFactor: Double,
      maxNrOfSeedNodes: Int,
      joinTimeout: FiniteDuration,
      ignoreRefreshFailures: Boolean
  ): Props =
    Props(
      new ConstructrMachine(
        selfNode,
        coordination,
        coordinationTimeout,
        coordinationRetries,
        retryDelay,
        refreshInterval,
        ttlFactor,
        maxNrOfSeedNodes,
        joinTimeout,
        ignoreRefreshFailures
      )
    )
}

final class ConstructrMachine(
    val selfNode: Address,
    coordination: Coordination,
    coordinationTimeout: FiniteDuration,
    nrOfRetries: Int,
    retryDelay: FiniteDuration,
    refreshInterval: FiniteDuration,
    ttlFactor: Double,
    maxNrOfSeedNodes: Int,
    joinTimeout: FiniteDuration,
    ignoreRefreshFailures: Boolean
) extends FSM[ConstructrMachine.State, ConstructrMachine.Data] {
  import ConstructrMachine._
  import context.dispatcher

  require(maxNrOfSeedNodes > 0,
          s"max-nr-of-seed-nodes must be positive, but was $maxNrOfSeedNodes!")
  require(
    ttlFactor >= minTtlFactor,
    s"ttl-factor must be greater or equal 1 + ((coordination-timeout * (1 + nr-of-retries) + retry-delay * nr-of-retries)/ refresh-interval), i.e. $minTtlFactor, but was $ttlFactor!"
  )

  private implicit val mat = ActorMaterializer()
  private val cluster      = Cluster(context.system)

  startWith(State.GettingNodes, Data(Set.empty, State.GettingNodes, nrOfRetries))

  // Getting nodes

  onTransition {
    case _ -> State.GettingNodes =>
      log.debug("Transitioning to GettingNodes")
      coordination.getNodes().map { nodes =>
        if (nodes.contains(selfNode))
          log.warning(
            s"Selfnode received in list of nodes $nodes. Will filter to prevent forming an island."
          )

        nodes.filterNot(_ == selfNode)
      } pipeTo self
  }

  when(State.GettingNodes, coordinationTimeout) {
    case Event(nodes: Set[Address] @unchecked, _) if nodes.isEmpty =>
      log.debug("Received empty nodes, going to Locking")
      goto(State.Locking)
        .using(stateData.copy(nrOfRetriesLeft = nrOfRetries))

    case Event(nodes: Set[Address] @unchecked, _) =>
      log.debug(s"Received nodes $nodes, going to Joining")
      goto(State.Joining)
        .using(stateData.copy(nodes = nodes, nrOfRetriesLeft = nrOfRetries))

    case Event(Status.Failure(cause), _) =>
      log.warning(s"Failure in $stateName, going to GettingNodes: $cause")
      retry(State.GettingNodes)

    case Event(StateTimeout, _) =>
      log.warning(s"Timeout in $stateName, going to GettingNodes")
      retry(State.GettingNodes)
  }

  // Locking

  onTransition {
    case _ -> State.Locking =>
      log.debug("Transitioning to Locking")
      val ttl = (2 * maxCoordinationTimeout + joinTimeout) * ttlFactor // Keep lock until self added
      coordination.lock(selfNode, ttl.toFinite).pipeTo(self)
  }

  when(State.Locking, coordinationTimeout) {
    case Event(true, _) =>
      log.debug("Successfully locked, going to Joining")
      goto(State.Joining).using(
        stateData.copy(nodes = Set(selfNode), nrOfRetriesLeft = nrOfRetries)
      )

    case Event(false, _) =>
      log.warning("Couldn't acquire lock, going to GettingNodes")
      goto(State.GettingNodes)
        .using(stateData.copy(nrOfRetriesLeft = nrOfRetries))

    case Event(Status.Failure(cause), _) =>
      log.warning(s"Failure in $stateName, going to Locking: $cause")
      retry(State.Locking)

    case Event(StateTimeout, _) =>
      log.warning(s"Timeout in $stateName, going to Locking")
      retry(State.Locking)
  }

  // Joining

  onTransition {
    case _ -> State.Joining =>
      log.debug("Transitioning to Joining")
      cluster.joinSeedNodes(seedNodes(nextStateData.nodes)) // An existing seed node process would be stopped
      Cluster(context.system).subscribe(self,
                                        InitialStateAsEvents,
                                        classOf[MemberJoined],
                                        classOf[MemberUp])

  }

  when(State.Joining, joinTimeout) {
    case Event(MemberJoined(member), _) if member.address == selfNode =>
      goto(State.AddingSelf)

    case Event(MemberUp(member), _) if member.address == selfNode =>
      goto(State.AddingSelf)

    case Event(StateTimeout, _) =>
      stop(Failure("Timeout in Joining!"))
  }

  onTransition {
    case State.Joining -> _ =>
      log.debug("Transitioning out of Joining")
      cluster.unsubscribe(self)
  }

  private def seedNodes(nodes: Set[Address]) =
    nodes.take(maxNrOfSeedNodes).toVector

  // AddingSelf

  onTransition {
    case _ -> State.AddingSelf =>
      log.debug("Transitioning to AddingSelf")
      coordination
        .addSelf(selfNode, addingSelfOrRefreshingTtl.toFinite)
        .pipeTo(self)
  }

  when(State.AddingSelf, coordinationTimeout) {
    case Event(Done, data) =>
      log.debug("Successfully added self, going to RefreshScheduled")
      goto(State.RefreshScheduled)
        .using(data.copy(nrOfRetriesLeft = nrOfRetries))

    case Event(Status.Failure(cause), _) =>
      log.warning(s"Failure in $stateName, going to AddingSelf: $cause")
      retry(State.AddingSelf)

    case Event(StateTimeout, _) =>
      log.warning(s"Timeout in $stateName, going to AddingSelf")
      retry(State.AddingSelf)
  }

  // RefreshScheduled

  onTransition {
    case _ -> State.RefreshScheduled =>
      log.debug("Transitioning to RefreshScheduled")
  }

  when(State.RefreshScheduled, refreshInterval) {
    case Event(StateTimeout, _) =>
      log.debug(s"Waited for $refreshInterval, going to Refreshing")
      goto(State.Refreshing)
  }

  // Refreshing

  onTransition {
    case _ -> State.Refreshing =>
      log.debug(s"Transitioning to Refreshing")
      coordination
        .refresh(selfNode, addingSelfOrRefreshingTtl.toFinite)
        .pipeTo(self)
  }

  when(State.Refreshing, coordinationTimeout) {
    case Event(Done, _) =>
      log.debug("Successfully refreshed, going to RefreshScheduled")
      goto(State.RefreshScheduled)
        .using(stateData.copy(nrOfRetriesLeft = nrOfRetries))

    case Event(Status.Failure(cause), _) =>
      log.warning(s"Failure in $stateName, going to Refreshing: $cause")
      retryRefreshing()

    case Event(StateTimeout, _) =>
      log.warning(s"Timeout in $stateName, going to Refreshing")
      retryRefreshing()
  }

  // RetryScheduled

  onTransition {
    case state -> State.RetryScheduled =>
      log.debug(s"Transitioning from $state to RetryScheduled")
  }

  when(State.RetryScheduled, retryDelay) {
    case Event(StateTimeout, Data(_, retryState, _)) =>
      log.debug(s"Waited for $retryDelay, going to $retryState")
      goto(retryState)
  }

  // Unhandled events

  whenUnhandled {
    // Unsubscribe might be late
    case Event(MemberJoined(_) | MemberUp(_), _) => stay()
  }

  // Initialization

  initialize()

  // Helpers

  private def retry(retryState: ConstructrMachine.State) =
    if (stateData.nrOfRetriesLeft <= 0)
      stop(FSM.Failure(s"Number of retries exhausted in $stateName!"))
    else
      goto(State.RetryScheduled).using(
        stateData.copy(retryState = retryState, nrOfRetriesLeft = stateData.nrOfRetriesLeft - 1)
      )

  private def maxCoordinationTimeout =
    coordinationTimeout * (1 + nrOfRetries) + retryDelay * nrOfRetries

  private def minTtlFactor = 1 + maxCoordinationTimeout / refreshInterval

  private def addingSelfOrRefreshingTtl = refreshInterval * ttlFactor

  private def retryRefreshing() =
    if (ignoreRefreshFailures)
      goto(State.RetryScheduled).using(
        stateData.copy(retryState = State.Refreshing, nrOfRetriesLeft = nrOfRetries)
      )
    else
      retry(State.Refreshing)
}


text: export { default } from 'ember-ecusson/components/e-checkbox';


text:
"""Handling of the <include> element.
"""

from __future__ import print_function

import os

from grit import util
import grit.format.html_inline
import grit.format.rc
from grit.format import minifier
from grit.node import base

class IncludeNode(base.Node):
  """An <include> element."""

  def __init__(self):
    super(IncludeNode, self).__init__()

    # Cache flattened data so that we don't flatten the same file
    # multiple times.
    self._flattened_data = None
    # Also keep track of the last filename we flattened to, so we can
    # avoid doing it more than once.
    self._last_flat_filename = None

  def _IsValidChild(self, child):
    return False

  def _GetFlattenedData(
      self, allow_external_script=False, preprocess_only=False):
    if not self._flattened_data:
      filename = self.ToRealPath(self.GetInputPath())
      self._flattened_data = (
          grit.format.html_inline.InlineToString(filename, self,
              preprocess_only=preprocess_only,
              allow_external_script=allow_external_script))
    return self._flattened_data.encode('utf-8')

  def MandatoryAttributes(self):
    return ['name', 'type', 'file']

  def DefaultAttributes(self):
    """Attributes:
       translateable:         False if the node has contents that should not be
                              translated.
       resource_path:         If provided, is used to populate the |path|
                              property of the generated ResourcePath struct.
       preprocess:            Takes the same code path as flattenhtml, but it
                              disables any  processing/inlining outside of <if>
                              and <include>.
       compress:              The format to compress the data with, e.g. 'gzip'
                              or 'false' if data should not be compressed.
       skip_minify:           If true, skips minifying the node's contents.
       skip_in_resource_map:  If true, do not add to the resource map.
    """
    return {
        'translateable': 'true',
        'generateid': 'true',
        'filenameonly': 'false',
        'mkoutput': 'false',
        'preprocess': 'false',
        'flattenhtml': 'false',
        'compress': 'default',
        'allowexternalscript': 'false',
        'relativepath': 'false',
        'use_base_dir': 'true',
        'skip_minify': 'false',
        'skip_in_resource_map': 'false',
        'resource_path': '',
    }

  def GetInputPath(self):
    # Do not mess with absolute paths, that would make them invalid.
    if os.path.isabs(os.path.expandvars(self.attrs['file'])):
      return self.attrs['file']

    # We have no control over code that calls ToRealPath later, so convert
    # the path to be relative against our basedir.
    if self.attrs.get('use_base_dir', 'true') not in ['true', 'false']:
      if "${" not in self.attrs['file']:
        self.attrs['file'] = util.PathSearcher.LocatePath(
          os.path.join(self.attrs.get('use_base_dir', self.attrs['file'])))
      # Normalize the directory path to use the appropriate OS separator.
      # GetBaseDir() may return paths\like\this or paths/like/this, since it is
      # read from the base_dir attribute in the grd file.
      norm_base_dir = util.normpath(self.GetRoot().GetBaseDir())
      return os.path.relpath(self.attrs['file'], norm_base_dir)

    if "${" not in self.attrs['file']:
      self.attrs['file'] = util.PathSearcher.LocatePath(self.attrs['file'])

    return self.attrs['file']

  def FileForLanguage(self, lang, output_dir):
    """Returns the file for the specified language.  This allows us to return
    different files for different language variants of the include file.
    """
    input_path = self.GetInputPath()
    if input_path is None:
      return None

    return self.ToRealPath(input_path)

  def GetDataPackValue(self, lang, encoding):
    '''Returns bytes or a str represenation for a data_pack entry.'''
    filename = self.ToRealPath(self.GetInputPath())
    if self.attrs['flattenhtml'] == 'true':
      allow_external_script = self.attrs['allowexternalscript'] == 'true'
      data = self._GetFlattenedData(allow_external_script=allow_external_script)
    elif self.attrs['preprocess'] == 'true':
      data = self._GetFlattenedData(preprocess_only=True)
    else:
      data = util.ReadFile(filename, util.BINARY)

    if self.attrs['skip_minify'] != 'true':
      # Note that the minifier will only do anything if a minifier command
      # has been set in the command line.
      data = minifier.Minify(data, filename)

    # Include does not care about the encoding, because it only returns binary
    # data.
    return self.CompressDataIfNeeded(data)

  def Process(self, output_dir):
    """Rewrite file references to be base64 encoded data URLs.  The new file
    will be written to output_dir and the name of the new file is returned."""
    filename = self.ToRealPath(self.GetInputPath())
    flat_filename = os.path.join(output_dir,
        self.attrs['name'] + '_' + os.path.basename(filename))

    if self._last_flat_filename == flat_filename:
      return

    with open(flat_filename, 'wb') as outfile:
      outfile.write(self._GetFlattenedData())

    self._last_flat_filename = flat_filename
    return os.path.basename(flat_filename)

  def GetHtmlResourceFilenames(self):
    """Returns a set of all filenames inlined by this file."""
    allow_external_script = self.attrs['allowexternalscript'] == 'true'
    return grit.format.html_inline.GetResourceFilenames(
         self.ToRealPath(self.GetInputPath()),
         self,
         allow_external_script=allow_external_script)

  def IsResourceMapSource(self):
    skip = self.attrs.get('skip_in_resource_map', 'false') == 'true'
    return not skip

  @staticmethod
  def Construct(parent, name, type, file, translateable=True,
                filenameonly=False, mkoutput=False, relativepath=False):
    """Creates a new node which is a child of 'parent', with attributes set
    by parameters of the same name.
    """
    # Convert types to appropriate strings
    translateable = util.BoolToString(translateable)
    filenameonly = util.BoolToString(filenameonly)
    mkoutput = util.BoolToString(mkoutput)
    relativepath = util.BoolToString(relativepath)

    node = IncludeNode()
    node.StartParsing('include', parent)
    node.HandleAttribute('name', name)
    node.HandleAttribute('type', type)
    node.HandleAttribute('file', file)
    node.HandleAttribute('translateable', translateable)
    node.HandleAttribute('filenameonly', filenameonly)
    node.HandleAttribute('mkoutput', mkoutput)
    node.HandleAttribute('relativepath', relativepath)
    node.EndParsing()
    return node


text:
import { ClientOptions, convert } from './clientOptions'

export interface ImplicitConfig {
  id: string;
  uri: string;
}

function implicit({ id, uri }: ImplicitConfig, options: ClientOptions | string): string {
  return `${convert(options).apiHostname}/oauth/authorize?response_type=token&client_id=${encodeURIComponent(id)}&redirect_uri=${encodeURIComponent(uri)}`;
}

export default implicit


text:
<?php

namespace Zbox\UnifiedPush\Exception;

class ClientException extends \RuntimeException
{
}


text:
```Bash
$ raco pkg install [package path]
```


text:
package io.carml.rdfmapper;

import java.lang.reflect.Type;
import java.util.Set;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;

public interface TypeDecider {

  Set<Type> decide(Model model, Resource resource);

}


text:
package org.rediscli.api

object Implicits {
  implicit def long2String(l: Long): String = l.toString

  implicit def int2String(i: Int): String = i.toString

  implicit def float2String(f: Float): String = f.toString
}


text:
using System;

using AppKit;

namespace ExampleBrowser
{
    static class MainClass
    {
        static void Main (string[] args)
        {
            NSApplication.Init ();

            var application = NSApplication.SharedApplication;
            application.Delegate = new AppDelegate ();
            application.Run ();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Famoser.OfflineMedia.Business.Helpers.Text;
using Famoser.OfflineMedia.Business.Models;
using Famoser.OfflineMedia.Business.Models.NewsModel;
using Famoser.OfflineMedia.Business.Models.NewsModel.ContentModels;
using Famoser.OfflineMedia.Business.Newspapers.Blick.Models;
using Famoser.OfflineMedia.Business.Repositories.Interfaces;
using Newtonsoft.Json;

namespace Famoser.OfflineMedia.Business.Newspapers.Blick
{
    public class BlickHelper : BaseMediaSourceHelper
    {

        private ArticleModel FeedModelToArticleModel(feeditem item, FeedModel feedModel)
        {
            return ExecuteSafe(() =>
            {
                var am = ConstructArticleModel(feedModel);
                am.Title = item.title;
                am.LogicUri = item.targetUrl;
                am.PublicUri = item.targetUrl.Substring(0, item.targetUrl.IndexOf(".json", StringComparison.Ordinal)) + ".html";
                am.PublishDateTime = item.publicationDate;
                am.SubTitle = item.catchword;
                am.Teaser = item.lead;
                am.LeadImage = new ImageContentModel() {Url = item.img.src};
                return am;
            });
        }

        public async Task<bool> WriteProperties(articlefeeditem[] na, ArticleModel am)
        {
            if (na == null)
                return false;

            articlefeeditem category = na.FirstOrDefault(a => a.type == "metadata");
            if (category != null)
            {
                am.Themes.Clear();
                await AddThemesAsync(am, new[] { category.section });

                var auth = category.author as string;
                if (auth != null)
                    am.Author = auth;
            }

            if (string.IsNullOrWhiteSpace(am.Author))
                am.Author = am.Feed.Source.Name;

            articlefeeditem body = na.FirstOrDefault(a => a.type == "body");

            //clear content
            am.Content.Clear();
            if (body != null)
            {
                var htmlbody = body.items.Where(b => b.type == "text").ToList();
                var unsupportedWarned = false;
                for (var i = 0; i < htmlbody.Count(); i++)
                {
                    if (htmlbody[i].txt.StartsWith("
"))
                    {
                        var sponsorDiv = "
";
                        var start = htmlbody[i].txt.Substring(htmlbody[i].txt.IndexOf(sponsorDiv, StringComparison.Ordinal) + sponsorDiv.Length);
                        start = start.Substring(0, start.IndexOf("
", StringComparison.Ordinal));
                        am.Content.Add(TextHelper.TextToTextModel("Ein Beitrag von " + start));
                    }
                    else if (htmlbody[i].txt.StartsWith("
"))
                    {
                        if (htmlbody[i].txt == "

") //empty special content, god knows why
                            continue;
                        if (!unsupportedWarned)
                        {
                            am.Content.Add(TextHelper.TextToTextModel(
                                    "Dieser Artikel enthält an dieser Stelle Inhalt der nicht unterstützt wird. Sehen Sie sich den Artikel im Web am, um alles anzuzeigen"));
                            unsupportedWarned = true;
                        }
                    }
                    else
                    {
                        var p = HtmlConverter.CreateOnce(am.Feed.Source.PublicBaseUrl).HtmlToParagraph(htmlbody[i].txt);
                        if (p != null && p.Count > 0)
                            am.Content.Add(new TextContentModel()
                            {
                                Content = p
                            });
                        else
                        {
                            "ha".ToString();
                        }
                    }
                }
            }
            if (!am.Content.Any())
            {
                am.Content.Add(TextHelper.TextToTextModel(
                                  "Dieser Artikel enthält Inhalt der nicht unterstützt wird. Sehen Sie sich den Artikel im Web am, um alles anzuzeigen"));
            }

            articlefeeditem headline = na.FirstOrDefault(a => a.type == "headline");
            if (headline != null && headline.author != null && headline.author.GetType() == typeof(articlefeeditem))
            {
                articlefeeditem author = headline.author as articlefeeditem;
                if (author != null)
                    am.Author = author.firstName;
            }

            return true;
        }

        public BlickHelper(IThemeRepository themeRepository) : base(themeRepository)
        {
        }

        public override Task<List<ArticleModel>> EvaluateFeed(FeedModel feedModel)
        {
            return ExecuteSafe(async () =>
            {
                var feed = await DownloadAsync(feedModel);

                var articlelist = new List<ArticleModel>();
                if (feed == null) return articlelist;

                var f = JsonConvert.DeserializeObject<feed[]>(feed);
                feed articlefeed = f.FirstOrDefault(i => i.type == "teaser");
                if (articlefeed != null)
                {
                    articlelist.AddRange(articlefeed.items.Where(i => i.type == "teaser")
                        .Select(i => FeedModelToArticleModel(i, feedModel))
                        .Where(am => am != null));
                }

                return articlelist;
            });
        }

        public override Task<bool> EvaluateArticle(ArticleModel articleModel)
        {
            return ExecuteSafe(async () =>
            {
                var article = await DownloadAsync(articleModel);

                var a = JsonConvert.DeserializeObject<articlefeeditem[]>(article);

                return await WriteProperties(a, articleModel);
            });
        }
    }
}


text:
package java.lang

import scala.scalajs.js

class ClassLoader protected (parent: ClassLoader) {
  def this() = this(null)
}


text:
namespace arangodb {
namespace application_features {
class ApplicationServer;
}
namespace basics {
class StringBuffer;
}
namespace httpclient {
class SimpleHttpClient;
class SimpleHttpResult;
}  // namespace httpclient

namespace import {
struct ImportStatistics;

class SenderThread final : public arangodb::Thread {
 private:
  SenderThread(SenderThread const&) = delete;
  SenderThread& operator=(SenderThread const&) = delete;

 public:
  explicit SenderThread(application_features::ApplicationServer& server,
                        std::unique_ptr<httpclient::SimpleHttpClient>,
                        ImportStatistics* stats, std::function<void()> const& wakeup);

  ~SenderThread();

  //////////////////////////////////////////////////////////////////////////////
  /// @brief imports a delimited file
  //////////////////////////////////////////////////////////////////////////////

  void sendData(std::string const& url, basics::StringBuffer* sender,
                size_t lowLine = 0, size_t highLine = 0);

  bool hasError();
  /// Ready to start sending
  bool isReady();
  /// Currently not sending data
  bool isIdle();
  bool isDone();

  std::string const& errorMessage() const { return _errorMessage; }

  void beginShutdown() override;

 protected:
  void run() override;

 private:
  basics::ConditionVariable _condition;
  std::unique_ptr<httpclient::SimpleHttpClient> _client;
  std::function<void()> _wakeup;
  std::string _url;
  basics::StringBuffer _data;
  bool _hasError;
  bool _idle;
  bool _ready;
  size_t _lowLineNumber;
  size_t _highLineNumber;

  ImportStatistics* _stats;
  std::string _errorMessage;
  void handleResult(httpclient::SimpleHttpResult* result);
};
}  // namespace import
}  // namespace arangodb


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

    <!-- From: file:/home/fer/Downloads/NotiNexusFimeUanl/app/src/main/res/values/color.xml -->
    <eat-comment />

    <color name="blanco">#FFFFFF</color>
    <!-- From: file:/home/fer/Downloads/NotiNexusFimeUanl/app/src/main/res/values/dimens.xml -->
    <eat-comment />

    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <!-- From: file:/home/fer/Downloads/NotiNexusFimeUanl/app/src/main/res/values/strings.xml -->
    <eat-comment />

    <string name="Login">Login</string>
    <string name="action_settings">Configuraciones</string>
    <string name="app_name">NotiNexus Fime</string>
    <string name="attempts">Intentos restantes:</string>
    <string name="hello_world">NotiNexus</string>
    <string name="password">Contraseña:</string>
    <string name="title_activity_my_activity2">Materias</string>
    <string name="username">Usuario:</string>
    <!-- From: file:/home/fer/Downloads/NotiNexusFimeUanl/app/src/main/res/values/styles.xml -->
    <eat-comment />

    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>


text:
require 'spec_helper'

describe Gitlab::Database::ShaAttribute do
  let(:sha) do
    '9a573a369a5bfbb9a4a36e98852c21af8a44ea8b'
  end

  let(:binary_sha) do
    [sha].pack('H*')
  end

  let(:binary_from_db) do
    if Gitlab::Database.postgresql?
      "\\x#{sha}"
    else
      binary_sha
    end
  end

  let(:attribute) { described_class.new }

  describe '#type_cast_from_database' do
    it 'converts the binary SHA to a String' do
      expect(attribute.type_cast_from_database(binary_from_db)).to eq(sha)
    end
  end

  describe '#type_cast_for_database' do
    it 'converts a SHA String to binary data' do
      expect(attribute.type_cast_for_database(sha).to_s).to eq(binary_sha)
    end
  end
end


text:
require_relative 'implement_binary_search_tree'
# Problem: Write a program to delete an element from a Binary Search Tree.

# See algorithm at https://en.wikipedia.org/wiki/Binary_search_tree#Deletion

# PSEUDOCODE
# We have 3 cases to consider for the node to be deleted: it has no children, has only 1 child, or both children
# Case 1: If the node to be deleted has no children, just remove the node from the tree
# case 2: If the node to be deleted has only 1 child, remove the node and replace it with its child
# case 3: If the node to be deleted has both left and right children, do the followings:
# i) Replace the key of the node with the largest element in the left subtree ( that is with the inorder predecessor node).
# The largest node cannot have a right child; it has atmost 1 child (left child).
# ii) Delete this largest element by replacing it with its child (if any) (case 1 or 2)

def delete(root, data)
# puts "Value = *** #{root.value} ****,  data = #{data}"
  if !root
    puts "The tree or a subtree is empty!"
    return nil
  elsif data < root.value
    root.left_child = delete(root.left_child, data)
  elsif data > root.value
    root.right_child = delete(root.right_child, data)
  else # we found the value the node to be deleted
    if root.left_child && root.right_child # if both left and right children exists
      inorder_predecessor = find_max(root.left_child)
      # replace root's value with that of inorder_predecessor
      root.value = inorder_predecessor.value
      # now replace root's left by delete inorder_predecessor's node
      root.left_child = delete(root.left_child, root.value)
    else # root has at most 1 child; replace it with its child if any
      if !root.left_child && !root.right_child # if root has no children
        root = nil
      elsif root.left_child # if root has a left child, replace it but that child
        root = root.left_child
      else # root has right child, therefore replace it by that child
        root = root.right_child
      end
    end
  end
  root
end

def find_max(root)
  return nil if !root
  while root.right_child
    root = root.right_child
  end
  root
end

# TEST DRIVE
#      4
#    /    \
#   2      6
#  / \    / \
# 1   3  5   7

d = Node.new(1)
e = Node.new(3)
f = Node.new(5)
g = Node.new(7)

b = Node.new(2, d, e)
c = Node.new(6, f, g)

a = Node.new(4, b, c)

root = a

delete(root, 3) # the tree should now look like below:
#      3
#    /    \
#   2      6
#  /      / \
# 1      5   7

p root


text:
#include "nsconfig.h"
#include <string.h>
#include "ethernet_mac_api.h"
#include "eventOS_event.h"
#include "nsdynmemLIB.h"
#include "common_functions.h"
#include "MAC/rf_driver_storage.h"

typedef struct eth_mac_internal_s {
    eth_mac_api_t *mac_api;
    arm_device_driver_list_s *dev_driver;
    uint8_t *mtu_ptr;
    uint16_t mtu_size;
    uint8_t mac48_iid64[8];
    bool active_data_request;
    int8_t tasklet_id;
    //linked list link
} eth_mac_internal_t;

static eth_mac_internal_t mac_store = { //Hack only at this point, later put into linked list
    .tasklet_id = -1
};

#define ETH_INIT_EVENT 0
#define ETH_DATA_IND_EVENT 1
#define ETH_DATA_CNF_EVENT 2

#define ETHERNET_HDROFF_DST_ADDR    0
#define ETHERNET_HDROFF_SRC_ADDR    6
#define ETHERNET_HDROFF_TYPE        12
#define ETHERNET_HDRLEN             14

static int8_t eth_mac_api_init(eth_mac_api_t *api, eth_mac_data_confirm *conf_cb, eth_mac_data_indication *ind_cb, uint8_t parent_id);
static void data_req(const eth_mac_api_t *api, const eth_data_req_t *data);
static int8_t mac48_address_set(const eth_mac_api_t *api, const uint8_t *mac48);
static int8_t mac48_address_get(const eth_mac_api_t *api, uint8_t *mac48_buf);
static int8_t iid64_address_set(const eth_mac_api_t *api, const uint8_t *iid64);
static int8_t iid64_address_get(const eth_mac_api_t *api, uint8_t *iid64_buf);

static int8_t eth_mac_net_phy_rx(const uint8_t *data_ptr, uint16_t data_len, uint8_t link_quality, int8_t dbm, int8_t driver_id);
static int8_t eth_mac_net_phy_tx_done(int8_t driver_id, uint8_t tx_handle, phy_link_tx_status_e status, uint8_t cca_retry, uint8_t tx_retry);
static void ethernet_mac_tasklet(arm_event_s *event);

int8_t ethernet_mac_destroy(eth_mac_api_t *mac_api)
{
    if (!mac_api || mac_store.mac_api != mac_api) {
        return -1;
    }

    mac_store.active_data_request = false;
    ns_dyn_mem_free(mac_store.mac_api);
    mac_store.mac_api = NULL;
    mac_store.dev_driver = NULL;
    ns_dyn_mem_free(mac_store.mtu_ptr);
    mac_store.mtu_ptr = NULL;
    mac_store.mtu_size = 0;
    return 0;
}

eth_mac_api_t *ethernet_mac_create(int8_t driver_id)
{
    //TODO: Refactor this away, Drivers should be stored in MAC layer in future
    arm_device_driver_list_s *driver = arm_net_phy_driver_pointer(driver_id);
    if (!driver || !driver->phy_driver) {
        return NULL;
    }

    //Accept to return same mac if mac is generated and driver is same
    if (mac_store.mac_api) {
        if (mac_store.dev_driver == driver) {
            return mac_store.mac_api;
        }
        return NULL;
    }

    uint8_t *buffer_ptr = NULL;
    uint16_t buffer_length = 0;
    bool address_resolution_needed = true;

    switch (driver->phy_driver->link_type) {

        case PHY_LINK_SLIP:
        case PHY_LINK_PPP:
            //Do not Allocate
            address_resolution_needed = false;
            buffer_length = 0;
            break;

        case PHY_LINK_TUN:
            address_resolution_needed = false;
            buffer_length = 1500 + 4;
            break;
        case PHY_LINK_ETHERNET_TYPE:

            buffer_length = 1500 + ETHERNET_HDRLEN;

            break;

        default:
            return NULL;
    }
    if (buffer_length) {
        buffer_ptr = ns_dyn_mem_alloc(buffer_length);
        if (!buffer_ptr) {
            return NULL;
        }
    }

    eth_mac_api_t *this = ns_dyn_mem_alloc(sizeof(eth_mac_api_t));
    if (!this) {
        ns_dyn_mem_free(buffer_ptr);
        return NULL;
    }
    memset(this, 0, sizeof(eth_mac_api_t));
    this->mac_initialize = &eth_mac_api_init;
    this->data_req = &data_req;

    if (driver->phy_driver->link_type == PHY_LINK_PPP) {
        this->iid64_get = &iid64_address_get;
        this->iid64_set = &iid64_address_set;
    } else {
        this->mac48_get = &mac48_address_get;
        this->mac48_set = &mac48_address_set;
    }

    this->address_resolution_needed = address_resolution_needed;

    memset(&mac_store.mac48_iid64, 0, 8);
    mac_store.active_data_request = false;
    mac_store.mac_api = this;
    mac_store.dev_driver = driver;
    mac_store.mtu_ptr = buffer_ptr;
    mac_store.mtu_size = buffer_length;

    if (driver->phy_driver->link_type == PHY_LINK_PPP) {
        memcpy(&mac_store.mac48_iid64, mac_store.dev_driver->phy_driver->PHY_MAC, 8);
    } else {
        memcpy(&mac_store.mac48_iid64, mac_store.dev_driver->phy_driver->PHY_MAC, 6);
    }
    if (mac_store.tasklet_id == -1) {
        mac_store.tasklet_id = eventOS_event_handler_create(&ethernet_mac_tasklet, ETH_INIT_EVENT);
    }
    arm_net_phy_init(driver->phy_driver, &eth_mac_net_phy_rx, &eth_mac_net_phy_tx_done);

    return this;
}

static void ethernet_mac_tasklet(arm_event_s *event)
{
    uint8_t event_type = event->event_type;

    switch (event_type) {
        case ETH_DATA_IND_EVENT: {
            eth_data_ind_t *data_ind = event->data_ptr;
            mac_store.mac_api->data_ind_cb(mac_store.mac_api, data_ind);
            ns_dyn_mem_free(((eth_data_ind_t *)event->data_ptr)->msdu);
            ns_dyn_mem_free(event->data_ptr);
            break;
        }
        case ETH_DATA_CNF_EVENT: {
            eth_data_conf_t *data_conf = event->data_ptr;
            mac_store.mac_api->data_conf_cb(mac_store.mac_api, data_conf);
            ns_dyn_mem_free(event->data_ptr);
            mac_store.active_data_request = false;
            break;
        }
        case ETH_INIT_EVENT:
        default: {
            break;
        }
    }
}

static int8_t eth_mac_api_init(eth_mac_api_t *api, eth_mac_data_confirm *conf_cb, eth_mac_data_indication *ind_cb, uint8_t parent_id)
{
    if (mac_store.mac_api != api) {
        return -1;
    }
    eth_mac_api_t *cur = mac_store.mac_api;
    cur->data_conf_cb = conf_cb;
    cur->data_ind_cb = ind_cb;
    cur->parent_id = parent_id;

    return 0;
}

static void data_req(const eth_mac_api_t *api, const eth_data_req_t *data)
{
    if (mac_store.mac_api != api || !mac_store.dev_driver->phy_driver || !data  || !data->msduLength) {
        return;
    }

    uint8_t *data_ptr;
    uint16_t data_length;

    //Build header
    switch (mac_store.dev_driver->phy_driver->link_type) {
        case PHY_LINK_ETHERNET_TYPE:

            if (data->msduLength + ETHERNET_HDRLEN > mac_store.mtu_size || !data->dstAddress || !data->srcAddress) {
                return;
            }

            data_ptr = mac_store.mtu_ptr;
            data_length = data->msduLength + ETHERNET_HDRLEN;
            memcpy(data_ptr + ETHERNET_HDROFF_DST_ADDR, data->dstAddress, 6);
            memcpy(data_ptr + ETHERNET_HDROFF_SRC_ADDR, data->srcAddress, 6);
            common_write_16_bit(data->etehernet_type, data_ptr + ETHERNET_HDROFF_TYPE);
            memcpy(data_ptr + ETHERNET_HDRLEN, data->msdu, data->msduLength);
            break;

        case PHY_LINK_TUN:
            if (data->msduLength + 4 > mac_store.mtu_size) {
                return;
            }
            data_ptr = mac_store.mtu_ptr;
            /* TUN header
             * [ TUN FLAGS 2B | PROTOCOL 2B | PAYLOAD ]
             * Tun flags may be 0, and protocol is same as in ether-type field, so
             * replace flags with e.g. IFF_TUN and packet is converted to TUN frame
             */
            common_write_16_bit(0, data_ptr);
            common_write_16_bit(data->etehernet_type, data_ptr + 2);
            memcpy(data_ptr + 4, data->msdu, data->msduLength);
            data_length = data->msduLength + 4;
            break;

        default: //SLIP
            data_ptr = data->msdu;
            data_length = data->msduLength;
            break;
    }

    mac_store.active_data_request = true;
    mac_store.dev_driver->phy_driver->tx(data_ptr, data_length, 0, PHY_LAYER_PAYLOAD);
}

static int8_t eth_mac_net_phy_rx(const uint8_t *data_ptr, uint16_t data_len, uint8_t link_quality, int8_t dbm, int8_t driver_id)
{
    arm_device_driver_list_s *driver = arm_net_phy_driver_pointer(driver_id);
    if (!data_ptr || !driver || driver != mac_store.dev_driver) {
        return -1;
    }

    if (data_len == 0) {
        return -1;
    }

    eth_data_ind_t *data_ind = ns_dyn_mem_temporary_alloc(sizeof(eth_data_ind_t));
    if (!data_ind) {
        return -1;
    }
    memset(data_ind, 0, sizeof(eth_data_ind_t));

    if (driver->phy_driver->link_type == PHY_LINK_ETHERNET_TYPE) {
        if (data_len < ETHERNET_HDRLEN + 1) {
            ns_dyn_mem_free(data_ind);
            return -1;
        }

        memcpy(data_ind->dstAddress, data_ptr +  ETHERNET_HDROFF_DST_ADDR, 6);
        memcpy(data_ind->srcAddress, data_ptr +  ETHERNET_HDROFF_SRC_ADDR, 6);

        data_ind->etehernet_type = common_read_16_bit(data_ptr + ETHERNET_HDROFF_TYPE);

        data_ptr += ETHERNET_HDRLEN;
        data_len -= ETHERNET_HDRLEN;

    } else if (driver->phy_driver->link_type == PHY_LINK_TUN) {
        if (data_len < 5) {
            ns_dyn_mem_free(data_ind);
            return -1;
        }
        /* TUN header
         * [ TUN FLAGS 2B | PROTOCOL 2B | PAYLOAD ]
         * Protocol is ether-type id.
         */
        data_ind->etehernet_type = common_read_16_bit(data_ptr + 2);

        data_len -= 4;
        data_ptr += 4;
    } else if (driver->phy_driver->link_type == PHY_LINK_SLIP || driver->phy_driver->link_type == PHY_LINK_PPP) {
        data_ind->etehernet_type = ETHERTYPE_IPV6;
    }

    data_ind->msdu = ns_dyn_mem_temporary_alloc(data_len);
    if (!data_ind->msdu) {
        ns_dyn_mem_free(data_ind);
        return -1;
    }
    memcpy(data_ind->msdu, data_ptr, data_len);
    data_ind->msduLength = data_len;
    data_ind->dbm = dbm;
    data_ind->link_quality = link_quality;

    arm_event_s event = {
        .receiver = mac_store.tasklet_id,
        .sender = 0,
        .event_id = 0,
        .data_ptr = data_ind,
        .event_type = ETH_DATA_IND_EVENT,
        .priority = ARM_LIB_HIGH_PRIORITY_EVENT,
    };

    if (eventOS_event_send(&event)) {
        ns_dyn_mem_free(data_ind->msdu);
        ns_dyn_mem_free(data_ind);
        return -1;
    }

    return 0;
}

static int8_t eth_mac_net_phy_tx_done(int8_t driver_id, uint8_t tx_handle, phy_link_tx_status_e status, uint8_t cca_retry, uint8_t tx_retry)
{
    (void)tx_handle;
    (void)cca_retry;
    (void)tx_retry;
    arm_device_driver_list_s *driver = arm_net_phy_driver_pointer(driver_id);
    if (!driver) {
        return -1;
    }

    if (mac_store.active_data_request) {
        mac_store.active_data_request = false;
        eth_data_conf_t *data_conf = ns_dyn_mem_temporary_alloc(sizeof(eth_data_conf_t));
        if (!data_conf) {
            return -1;
        }
        data_conf->status = status;
        arm_event_s event = {
            .receiver = mac_store.tasklet_id,
            .sender = 0,
            .event_id = 0,
            .data_ptr = data_conf,
            .event_type = ETH_DATA_CNF_EVENT,
            .priority = ARM_LIB_HIGH_PRIORITY_EVENT,
        };

        return eventOS_event_send(&event);
    }
    return 0;
}

static int8_t mac48_address_set(const eth_mac_api_t *api, const uint8_t *mac48)
{
    if (!mac48 || !api || mac_store.mac_api != api) {
        return -1;
    }
    memcpy(mac_store.mac48_iid64, mac48, 6);
    phy_device_driver_s *driver = mac_store.dev_driver->phy_driver;
    if (driver->address_write) {
        driver->address_write(PHY_MAC_48BIT, mac_store.mac48_iid64);
    }
    return 0;
}

static int8_t mac48_address_get(const eth_mac_api_t *api, uint8_t *mac48_buf)
{
    if (!mac48_buf || !api || mac_store.mac_api != api) {
        return -1;
    }
    memcpy(&mac_store.mac48_iid64, mac_store.dev_driver->phy_driver->PHY_MAC, 6);
    memcpy(mac48_buf, mac_store.mac48_iid64, 6);
    return 0;
}

static int8_t iid64_address_set(const eth_mac_api_t *api, const uint8_t *iid64)
{
    if (!iid64 || !api || mac_store.mac_api != api) {
        return -1;
    }
    memcpy(mac_store.mac48_iid64, iid64, 8);
    phy_device_driver_s *driver = mac_store.dev_driver->phy_driver;
    if (driver->address_write) {
        driver->address_write(PHY_MAC_48BIT, mac_store.mac48_iid64);
    }
    return 0;
}

static int8_t iid64_address_get(const eth_mac_api_t *api, uint8_t *iid64_buf)
{
    if (!iid64_buf || !api || mac_store.mac_api != api) {
        return -1;
    }
    memcpy(&mac_store.mac48_iid64, mac_store.dev_driver->phy_driver->PHY_MAC, 8);
    memcpy(iid64_buf, mac_store.mac48_iid64, 8);
    return 0;
}


text:
class CreateEntries < ActiveRecord::Migration
  def change
    create_table :entries do |t|
      t.string :title
      t.string :url
      t.string :author
      t.text :summary
      t.text :content
      t.datetime :published
      t.references :feed, index: true

      t.timestamps
    end
  end
end


text:
import re
#from blockcypher import api
from .utils import parse_addr_args

def unspent(*addrs, coin_symbol=None, api_key=None, **kwargs):

    if len(addrs) == 0:
        return []

    addrs = parse_addr_args(*addrs)

    if len(addrs) == 1:
        txs = api.get_address_details(addrs[0], coin_symbol=coin_symbol, unspent_only=True, **kwargs)['txrefs']
        for tx in txs:
            tx['output'] = "%s:%s" % (tx['tx_hash'], tx['tx_output_n'])
        return txs
    result = api.get_addresses_details(addrs, coin_symbol=coin_symbol, api_key=None, unspent_only=True, **kwargs)['txrefs']
    return result

def pushtx(tx, coin_symbol=None, api_key=None):
    if not re.match('^[0-9a-fA-F]*$', tx):
        tx = tx.encode('hex')
    return api.pushtx(tx, coin_symbol=coin_symbol, api_key=None)

# Gets the transaction output history of an address,
# including whether or not they have been spent
def history(addr, coin_symbol=None, api_key=None, **kwargs):
    return api.get_address_full(addr, coin_symbol=coin_symbol, api_key=None, **kwargs)


text:
START TRANSACTION;

  CREATE TABLE auth_schema_version (
      version_key VARCHAR(32) NOT NULL,
      version_value VARCHAR(255) NOT NULL
  );
  INSERT INTO auth_schema_version (version_key, version_value) VALUES ('schema_patch', '2');

  CREATE SEQUENCE auth_hibernate_sequence START WITH 1 INCREMENT BY 1;

  CREATE FUNCTION copy_sequence_value (from_name text, to_name text)
    RETURNS bigint AS $$
    BEGIN
      IF ((SELECT COUNT(c.relname) FROM pg_class c WHERE c.relkind = 'S' AND c.relname = from_name) > 0) THEN
        RETURN setval(to_name, nextval(from_name));
      END IF;
      RETURN 1;
    END
  $$ LANGUAGE plpgsql;
  SELECT copy_sequence_value('hibernate_sequence', 'auth_hibernate_sequence');
  DROP FUNCTION copy_sequence_value (from_name text, to_name text);

  DROP SEQUENCE IF EXISTS hibernate_sequence;

COMMIT;


text:
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(function(require)
{

  var BaseClientRouter = require('rendr/client/router');

  var Router = function Router(options) {
    BaseClientRouter.call(this, options);
  };

  /**
   * Set up inheritance.
   */
  Router.prototype = Object.create(BaseClientRouter.prototype);
  Router.prototype.constructor = BaseClientRouter;

  Router.prototype.postInitialize = function() {
    this.on('action:start', this.trackImpression, this);
  };

  Router.prototype.trackImpression = function() {
    if (window._gaq) {
      _gaq.push(['_trackPageview']);
    }
  };

  return Router;

});


text:
<?php $assets = $this->assets; $url = $this->url ?>
<!doctype html>

    <title>{{= (empty($this->config->get('title')))?'HOME':$this->config->get('title') }} | Home</title>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="Margo - Responsive HTML5 Template">
    <meta name="author" content="iThemesLab">

    @css

    @js

 House-54/A, London, UK

 info@yourcompany.com

 +12 345 678 000

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                        </button>

                        <a class="navbar-brand" href="<?php $url->to('') ?>">
                            <img alt="" src="<?php echo $assets->images('margo.png') ?>">

                                <form autocomplete="off" role="search" method="get" class="searchform" action="#">
                                    <input type="text" value="" name="s" id="s" placeholder="Search the site...">
                                </form>

                        <?php require_once("sections/menu.php") ?>

        @response

        <?php require_once("sections/footer.php") ?>

    <?php require_once("sections/style_switcher.php") ?>


text:
<ion-view view-title="Cofrem Assessment">
    <ion-content>
            <ion-list>
                <ion-item ng-repeat="item in tests" ng-click="goToTest($index)">
                    {{item.name}}
                </ion-item>
                <ion-item ui-sref="results">
                    Results
                </ion-item>
            </ion-list>
    </ion-content>
</ion-view>


text:
> Curried function which takes a map of `RegExp` string keys which when successfully matched given string, resolves to mapped value.

[![Build Status](http://img.shields.io/travis/wilmoore/regexp-map.js.svg)](https://travis-ci.org/wilmoore/regexp-map.js) [![Code Climate](https://codeclimate.com/github/wilmoore/regexp-map.js/badges/gpa.svg)](https://codeclimate.com/github/wilmoore/regexp-map.js) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)

```shell
npm install regexp-map --save
```

> You can also use Duo, Bower or [download the files manually](https://github.com/wilmoore/regexp-map.js/releases).

###### npm stats

[![npm](https://img.shields.io/npm/v/regexp-map.svg)](https://www.npmjs.org/package/regexp-map) [![NPM downloads](http://img.shields.io/npm/dm/regexp-map.svg)](https://www.npmjs.org/package/regexp-map) [![David](https://img.shields.io/david/wilmoore/regexp-map.js.svg)](https://david-dm.org/wilmoore/regexp-map.js)

## API Example

```js
var remap = require('regexp-map')
var makes = remap({
  '^toyota': 'Toyota',
  '^ford': 'Ford',
  '^dodge': 'Dodge'
})

makes('Toyota RAV4')
//=> 'Toyota'
```

## API

### `remap(map, str)`

###### arguments

 - `map (Object.<string, string>)` Map of `RegExp` strings which when matched against string successfully, resolves to mapped value.
 - `str (String)` String to search.

###### returns

 - `(String)` When matched returns corresponding mapped value; otherwise, an empty string.

## Contributing

> SEE: [contributing.md](contributing.md)

## Licenses

[![GitHub license](https://img.shields.io/github/license/wilmoore/regexp-map.js.svg)](https://github.com/wilmoore/regexp-map.js/blob/master/license)

[regexp-map]: https://www.npmjs.com/package/regexp-map


text:
int
main(int argc, char **argv)
{
	// check number of arguments
	if (argc != 4)
	{
		cerr << "usage: tqueen rows cols nqueens" << endl;
		return(2);
	}

	// get number of columns and rows
	int nrows = atoi(argv[1]);
	int ncols = atoi(argv[2]);

	// get number of queens
	int nqueens = atoi(argv[3]);

	// start state
	NQueenNode start(nqueens, nrows, ncols);

	// best-first search
	int unique, expanded;
	if (BestFirst_Astar_Check(start, unique, expanded) == OK)
	{
		cout << "SOLUTION FOUND ..." << endl;
	}
	else
	{
		cout << "NO SOLUTION FOUND ..." << endl;
	}
	cout << "Unique nodes ... " << unique << endl;
	cout << "Expanded nodes ... " << expanded << endl;

	// all done
	return(0);
}


text:
using UnityEngine;
using System;
using System.Collections;

public abstract class AbstractTweenProperty
{
	protected bool _isInitialized;
	public bool isInitialized { get { return _isInitialized; } }

	protected bool _isRelative;
	protected GoTween _ownerTween;

	protected Func<float, float, float, float, float> _easeFunction;

	public AbstractTweenProperty( bool isRelative = false )
	{
		_isRelative = isRelative;
	}

	public override int GetHashCode()
	{
		return base.GetHashCode();
	}

	/// <summary>
	/// checks to see if a TweenProperty matches another. checks propertyNames of IGenericPropertys first then
	/// resorts to direct type checking
	/// </summary>
	public override bool Equals( object obj )
	{
		// null check first
		if( obj == null )
			return false;

		// handle IGenericProperty comparisons which just have the property name checked
		if( this is IGenericProperty && obj is IGenericProperty )
			return ((IGenericProperty)this).propertyName == ((IGenericProperty)obj).propertyName;

		// check for the same types
		if( obj.GetType() == this.GetType() )
			return true;

		return base.Equals( obj );
	}

	/// <summary>
	/// called by a Tween just after this property is validated and added to the Tweens property list
	/// </summary>
	public virtual void init( GoTween owner )
	{
		_isInitialized = true;
		_ownerTween = owner;

		// if we dont have an easeFunction use the owners type
		if( _easeFunction == null )
			setEaseType( owner.easeType );
	}

	/// <summary>
	/// clones the instance
	/// </summary>
    public AbstractTweenProperty clone()
    {
		var clone = MemberwiseClone() as AbstractTweenProperty;
		clone._ownerTween = null;
		clone._isInitialized = false;
		clone._easeFunction = null;

		return clone;
    }

	/// <summary>
	/// sets the ease type for this tween property
	/// technically, this should be an internal method
	/// </summary>
	public void setEaseType( GoEaseType easeType )
	{
		_easeFunction = GoTweenUtils.easeFunctionForType( easeType );
	}

    /// <summary>
    /// each TweenProperty should override this to ensure the object is the correct type
    /// </summary>
    public virtual bool validateTarget( object target )
    {
        return true;
    }

	/// <summary>
	/// subclasses should get the eased time then set the new value on the object
	/// </summary>
	public abstract void tick( float totalElapsedTime );

	/// <summary>
	/// called when a Tween is initially started.
	/// subclasses should strongly type the start/end/target and handle isFrom with
	/// regard to setting the proper start/end values
	/// </summary>
	public abstract void prepareForUse();

}


text:
package org.spongepowered.common.data.processor.common;

import static com.google.common.base.Preconditions.checkNotNull;

import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.merge.MergeFunction;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.data.util.DataUtil;

import java.util.Optional;

public abstract class AbstractSingleDataSingleTargetProcessor<Holder, T, V extends BaseValue<T>, M extends DataManipulator<M, I>, I extends ImmutableDataManipulator<I, M>> extends AbstractSingleDataProcessor<T, V, M, I> {

    protected final Class<Holder> holderClass;

    protected AbstractSingleDataSingleTargetProcessor(Key<V> key, Class<Holder> holderClass) {
        super(key);
        this.holderClass = checkNotNull(holderClass);
    }

    protected boolean supports(Holder dataHolder) {
        return true;
    }

    protected abstract boolean set(Holder dataHolder, T value);

    protected abstract Optional<T> getVal(Holder dataHolder);

    protected abstract ImmutableValue<T> constructImmutableValue(T value);

    @SuppressWarnings("unchecked")
    @Override
    public boolean supports(DataHolder dataHolder) {
        return this.holderClass.isInstance(dataHolder) && supports((Holder) dataHolder);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public DataTransactionResult set(DataHolder dataHolder, M manipulator, MergeFunction function) {
        if (supports(dataHolder)) {
            final DataTransactionResult.Builder builder = DataTransactionResult.builder();
            final Optional<M> old = from(dataHolder);
            final M merged = checkNotNull(function).merge(old.orElse(null), manipulator);
            final T newValue = merged.get(this.key).get();
            final V immutableValue = (V) ((Value) merged.getValue(this.key).get()).asImmutable();
            try {
                if (set((Holder) dataHolder, newValue)) {
                    if (old.isPresent()) {
                        builder.replace(old.get().getValues());
                    }
                    return builder.result(DataTransactionResult.Type.SUCCESS).success((ImmutableValue<?>) immutableValue).build();
                } else {
                    return builder.result(DataTransactionResult.Type.FAILURE).reject((ImmutableValue<?>) immutableValue).build();
                }
            } catch (Exception e) {
                SpongeImpl.getLogger().debug("An exception occurred when setting data: ", e);
                return builder.result(DataTransactionResult.Type.ERROR).reject((ImmutableValue<?>) immutableValue).build();
            }
        }
        return DataTransactionResult.failResult(manipulator.getValues());
    }

    @Override
    public Optional<M> fill(DataHolder dataHolder, M manipulator, MergeFunction overlap) {
        if (!supports(dataHolder)) {
            return Optional.empty();
        } else {
            final M merged = checkNotNull(overlap).merge(manipulator.copy(), from(dataHolder).orElse(null));
            return Optional.of(manipulator.set(this.key, merged.get(this.key).get()));
        }
    }

    @Override
    public Optional<M> fill(DataContainer container, M m) {
        m.set(this.key, DataUtil.getData(container, this.key));
        return Optional.of(m);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Optional<I> with(Key<? extends BaseValue<?>> key, Object value, I immutable) {
        if (immutable.supports(key)) {
            return Optional.of(immutable.asMutable().set(this.key, (T) value).asImmutable());
        }
        return Optional.empty();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Optional<M> from(DataHolder dataHolder) {
        if (!supports(dataHolder)) {
            return Optional.empty();
        } else {
            final Optional<T> optional = getVal((Holder) dataHolder);
            if (optional.isPresent()) {
                return Optional.of(createManipulator().set(this.key, optional.get()));
            }
        }
        return Optional.empty();
    }

}