text:
import logging
import json
from django.conf import settings
import traceback
from datetime import datetime

from django.template.loader import render_to_string
from django.db.models.aggregates import Sum

from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.core.mail import send_mail
from django.db import transaction
from django.forms import ChoiceField, ModelForm, Form, EmailField, BooleanField
from django.forms import ModelChoiceField, CharField, Textarea, HiddenInput, FileField
from django.forms.models import model_to_dict
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseServerError
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from django.views.generic.list import ListView
from services.models import Alias, Service, ServiceType

from membership.templatetags.sorturl import lookup_sort
from membership.decorators import trusted_host_required
from membership.forms import PersonApplicationForm, OrganizationApplicationForm, PersonContactForm, ServiceForm, \
    ContactForm
from membership.utils import log_change, serializable_membership_info, admtool_membership_details, \
    get_client_ip, bake_log_entries
from membership.public_memberlist import public_memberlist_data
from membership.unpaid_members import unpaid_members_data
from membership.management.commands.csvbills import process_op_csv, process_procountor_csv
from membership.models import Contact, Membership, MEMBER_TYPES_DICT, Bill, BillingCycle, Payment, ApplicationPoll, \
    MembershipAlreadyStatus
from services.views import check_alias_availability, validate_alias

logger = logging.getLogger("membership.views")

ENTRIES_PER_PAGE = settings.ENTRIES_PER_PAGE

# Class based views

class SortListView(ListView):
    """ListView with search query parameter"""
    search_query = ''
    sort = None
    header = ''
    disable_duplicates_header = ''

    def get_context_data(self, **kwargs):
        context = super(SortListView, self).get_context_data(**kwargs)
        context['querystring'] = self.request.GET
        context['header'] = self.header
        context['disable_duplicates_header'] = self.disable_duplicates_header
        return context

    def get_queryset(self):
        qs = super(SortListView, self).get_queryset()
        ordering = lookup_sort(self.request.GET.get('sort'))
        if ordering is not None:
            return qs.order_by(ordering)
        else:
            return qs

# Public access
def new_application(request, template_name='membership/choose_membership_type.html'):
    return render_to_response(template_name, {},
                              context_instance=RequestContext(request))

# Public access
def person_application(request, template_name='membership/new_person_application.html'):
    if settings.MAINTENANCE_MESSAGE != None:
        return redirect('frontpage')
    chosen_email_forward = None
    if request.method != 'POST':
        application_form = PersonApplicationForm()
    elif request.method == 'POST':
        application_form = PersonApplicationForm(request.POST)

        if not application_form.is_valid():
            try:
                chosen_email_forward = application_form.fields['email_forward'].clean(application_form.data['email_forward'])
            except:
                pass
        else:
            f = application_form.cleaned_data
            with transaction.atomic():
                # Separate a contact dict from the other fields
                contact_dict = {}
                for k, v in f.items():
                    if k not in ['nationality', 'municipality',
                                 'public_memberlist', 'email_forward',
                                 'unix_login', 'extra_info',
                                 'mysql_database', 'postgresql_database',
                                 'login_vhost', 'poll', 'poll_other',
                                 'birth_year']:
                        contact_dict[k] = v

                person = Contact(**contact_dict)
                person.save()
                if (datetime.now().year - int(f['birth_year'])) < 21:
                    membership_type = 'J'
                else:
                    membership_type = 'P'
                membership = Membership(type=membership_type, status='N',
                                        person=person,
                                        nationality=f['nationality'],
                                        municipality=f['municipality'],
                                        public_memberlist=f['public_memberlist'],
                                        birth_year=f['birth_year'],
                                        extra_info=f['extra_info'])
                membership.save()

                # Service handling
                services = []

                login_alias = Alias(owner=membership, name=f['unix_login'], account=True)
                login_alias.save()
                unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'),
                                               alias=login_alias, owner=membership, data=f['unix_login'])
                unix_account_service.save()
                services.append(unix_account_service)

                if f['email_forward'] != 'no' and f['email_forward'] != f['unix_login']:
                    forward_alias = Alias(owner=membership, name=f['email_forward'])
                    forward_alias.save()
                    forward_alias_service = Service(servicetype=ServiceType.objects.get(servicetype='Email alias'),
                                                    alias=forward_alias, owner=membership, data=f['unix_login'])
                    forward_alias_service.save()
                    services.append(forward_alias_service)

                if f['mysql_database'] == True:
                    mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'),
                                            alias=login_alias, owner=membership, data=f['unix_login'].replace('-', '_'))
                    mysql_service.save()
                    services.append(mysql_service)
                if f['postgresql_database'] == True:
                    postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'),
                                                 alias=login_alias, owner=membership, data=f['unix_login'])
                    postgresql_service.save()
                    services.append(postgresql_service)
                if f['login_vhost'] == True:
                    login_vhost_service = Service(servicetype=ServiceType.objects.get(servicetype='WWW vhost'),
                                                  alias=login_alias, owner=membership, data=f['unix_login'])
                    login_vhost_service.save()
                    services.append(login_vhost_service)

                logger.debug("Attempting to save with the following services: %s." % ", ".join((str(service) for service in services)))
                # End of services

                if f['poll'] is not None:
                    answer = f['poll']
                    if answer == 'other':
                        answer = '%s: %s' % (answer, f['poll_other'])
                    pollanswer = ApplicationPoll(membership=membership,
                                                 answer=answer)
                    pollanswer.save()

                logger.info("New application {person} from {ip}:.".format(person=person, ip=get_client_ip(request)))
                send_mail(_('Membership application received'),
                          render_to_string('membership/application_confirmation.txt',
                                           { 'membership': membership,
                                             'membership_type': MEMBER_TYPES_DICT[membership.type],
                                             'person': membership.person,
                                             'billing_contact': membership.billing_contact,
                                             'tech_contact': membership.tech_contact,
                                             'ip': get_client_ip(request),
                                             'services': services}),
                          settings.FROM_EMAIL,
                          [membership.email_to()], fail_silently=False)
                return redirect('new_person_application_success')

    return render_to_response(template_name, {"form": application_form,
                                "chosen_email_forward": chosen_email_forward,
                                "title": _("Person member application")},
                                context_instance=RequestContext(request))

# Public access
def organization_application(request, template_name='membership/new_organization_application.html'):
    if settings.MAINTENANCE_MESSAGE != None:
        return redirect('frontpage')
    if request.method == 'POST':
        form = OrganizationApplicationForm(request.POST)

        if form.is_valid():
            f = form.cleaned_data

            d = {}
            for k, v in f.items():
                if k not in ['nationality', 'municipality', 'extra_info',
                'public_memberlist', 'organization_registration_number']:
                    d[k] = v

            organization = Contact(**d)
            membership = Membership(type='O', status='N',
                                    nationality=f['nationality'],
                                    municipality=f['municipality'],
                                    extra_info=f['extra_info'],
                                    organization_registration_number=f['organization_registration_number'],
                                    public_memberlist=f['public_memberlist'])

            request.session.set_expiry(0) # make this expire when the browser exits
            request.session['membership'] = model_to_dict(membership)

            organization_dict = model_to_dict(organization)
            request.session['organization'] = organization_dict
            return redirect('organization_application_add_contact', 'billing_contact')
    else:
        form = OrganizationApplicationForm()
    return render_to_response(template_name, {"form": form,
                                              "title": _('Organization application')},
                              context_instance=RequestContext(request))

# Public access
def organization_application_add_contact(request, contact_type,
                                         template_name='membership/new_organization_application_add_contact.html'):
    forms = ['billing_contact', 'tech_contact']
    if contact_type not in forms:
        return HttpResponseForbidden("Access denied")

    if contact_type == 'billing_contact':
        type_text = unicode(_('Billing contact'))
    elif contact_type == 'tech_contact':
        type_text = unicode(_('Technical contact'))

    if request.method == 'POST':
        form = PersonContactForm(request.POST)

        if (form.is_valid() or                 # contact is actually filled
            len(form.changed_data) == 0 or     # form is empty
            form.changed_data == ['country']): # only the country field is filled (this comes from form defaults)

            if form.is_valid():
                f = form.cleaned_data
                contact = Contact(**f)
                contact_dict = model_to_dict(contact)
                request.session[contact_type] = contact_dict
            else:
                request.session[contact_type] = None

            next_idx = forms.index(contact_type) + 1
            if next_idx == len(forms):
                return redirect('organization_application_services')
            return redirect('organization_application_add_contact', forms[next_idx])
    else:
        if request.session.has_key(contact_type):
            form = PersonContactForm(request.session[contact_type])
        else:
            form = PersonContactForm()
    return render_to_response(template_name, {"form": form, "contact_type": type_text,
                                              "step_number": forms.index(contact_type) + 2,
                                              "title": _('Organization application') + ' - ' + type_text},
                              context_instance=RequestContext(request))

# Public access
def organization_application_services(request, template_name='membership/new_organization_application_services.html'):
    if request.session.has_key('services'):
        form = ServiceForm({'mysql_database': request.session.get('mysql', ''),
                            'postgresql_database': request.session.get('postgresql', ''),
                            'login_vhost': request.session.get('login_vhost', ''),
                            'unix_login': request.session.get('unix_login', '')})
    else:
        form = ServiceForm()

    if request.method == 'POST':
        form = ServiceForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data

            services = {'unix_login': f['unix_login']}

            if f['mysql_database'] != False:
                services['mysql_database'] = f['unix_login']
            elif services.has_key('mysql_database'):
                del services['mysql_database']
            if f['postgresql_database'] != False:
                services['postgresql_database'] = f['unix_login']
            elif services.has_key('postgresql'):
                del services['postgresql']
            if f['login_vhost'] != False:
                services['login_vhost'] = f['unix_login']
            elif services.has_key('login_vhost'):
                del services['login_vhost']

            request.session['services'] = services
            return redirect('organization_application_review')
        else:
            if request.session.has_key('services'):
                del request.session['services']

    return render_to_response(template_name, {"form": form,
                                              "title": unicode(_('Choose services'))},
                              context_instance=RequestContext(request))

# Public access
def organization_application_review(request, template_name='membership/new_organization_application_review.html'):
    # Maybe submitting form again after already submitting?
    if request.session.get('membership') is None:
        messages.error(request, _("Required data missing. Maybe attempted to submit application twice?"))
        return redirect('organization_application')

    forms = []
    combo_dict = request.session['membership']
    for k, v in request.session['organization'].items():
        combo_dict[k] = v
    forms.append(OrganizationApplicationForm(combo_dict))
    if request.session.get('billing_contact') is not None:
        forms.append(PersonContactForm(request.session['billing_contact']))
        forms[-1].name = _("Billing contact")
    if request.session.get('tech_contact') is not None:
        forms.append(PersonContactForm(request.session['tech_contact']))
        forms[-1].name = _("Technical contact")
    return render_to_response(template_name, {"forms": forms, "services": request.session['services'],
                                              "title": unicode(_('Organization application')) + ' - ' + unicode(_('Review'))},
                              context_instance=RequestContext(request))

# Public access
def organization_application_save(request):
    # Maybe submitting form again after already submitting?
    if request.session.get('membership') is None:
        messages.error(request, _("Required data missing. Maybe attempted to submit application twice?"))
        return redirect('organization_application')

    with transaction.atomic():
        membership = Membership(type='O', status='N',
                                nationality=request.session['membership']['nationality'],
                                municipality=request.session['membership']['municipality'],
                                extra_info=request.session['membership']['extra_info'],
                                organization_registration_number=request.session['membership']['organization_registration_number'])

        organization = Contact(**request.session['organization'])
        organization.save()
        membership.organization = organization

        if request.session.get('billing_contact') is not None:
            billing_contact = Contact(**request.session['billing_contact'])
            billing_contact.save()
            membership.billing_contact = billing_contact

        if request.session.get('tech_contact') is not None:
            tech_contact = Contact(**request.session['tech_contact'])
            tech_contact.save()
            membership.tech_contact = tech_contact

        membership.save()

        services = []
        services_request = request.session['services']
        login_alias = Alias(owner=membership, name=services_request['unix_login'], account=True)
        login_alias.save()
        unix_account_service = Service(servicetype=ServiceType.objects.get(servicetype='UNIX account'),
                                       alias=login_alias, owner=membership, data=services_request['unix_login'])
        unix_account_service.save()
        services.append(unix_account_service)
        if 'mysql_database' in services_request:
            mysql_service = Service(servicetype=ServiceType.objects.get(servicetype='MySQL database'),
                                    alias=login_alias, owner=membership,
                                    data=services_request['mysql_database'].replace('-', '_'))
            mysql_service.save()
            services.append(mysql_service)
        if 'postgresql_database' in services_request:
            postgresql_service = Service(servicetype=ServiceType.objects.get(servicetype='PostgreSQL database'),
                                         alias=login_alias, owner=membership,
                                         data=services_request['postgresql_database'])
            postgresql_service.save()
            services.append(postgresql_service)
        if 'login_vhost' in services_request:
            login_vhost_service = Service(servicetype=ServiceType.objects.get(servicetype='WWW vhost'),
                                          alias=login_alias, owner=membership,
                                          data=services_request['login_vhost'])
            login_vhost_service.save()
            services.append(login_vhost_service)

        send_mail(_('Membership application received'),
                  render_to_string('membership/application_confirmation.txt',
                                   { 'membership': membership,
                                     'membership_type': MEMBER_TYPES_DICT[membership.type],
                                     'organization': membership.organization,
                                     'billing_contact': membership.billing_contact,
                                     'tech_contact': membership.tech_contact,
                                     'ip': get_client_ip(request),
                                     'services': services}),
                  settings.FROM_EMAIL,
                  [membership.email_to()], fail_silently=False)

        logger.info("New application {organization} from {ip}:.".format(organization=organization, ip=get_client_ip(request)))
        request.session.set_expiry(0)  # make this expire when the browser exits
        for i in ['membership', 'billing_contact', 'tech_contact', 'services']:
            if i in request.session:
                del request.session[i]
        return redirect('new_organization_application_success')

@permission_required('membership.manage_members')
def contact_add(request, contact_type, memberid, template_name='membership/entity_edit.html'):
    membership = get_object_or_404(Membership, id=memberid)
    forms = ['billing_contact', 'tech_contact']

    if contact_type not in forms:
        return HttpResponseForbidden("Access denied")

    if contact_type == 'billing_contact' and membership.billing_contact:
        return redirect('contact_edit',membership.billing_contact.id)
    elif contact_type == 'tech_contact' and membership.tech_contact:
        return redirect('contact_edit',membership.tech_contact.id)

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = Contact(**form.cleaned_data)
            contact.save()
            if contact_type == 'billing_contact':
                membership.billing_contact = contact
            elif contact_type == 'tech_contact':
                membership.tech_contact = contact
            membership.save()
            messages.success(request,
                             unicode(_("Added contact %s.") %
                             contact))
            return redirect('contact_edit', contact.id)
        else:
            messages.error(request,
                           unicode(_("New contact not saved.")))
    else:
        form = ContactForm()
    return render_to_response(template_name,
                             {"form": form, 'memberid': memberid},
                             context_instance=RequestContext(request))

@permission_required('membership.read_members')
def contact_edit(request, id, template_name='membership/entity_edit.html'):
    contact = get_object_or_404(Contact, id=id)

    before = model_to_dict(contact)  # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        if not request.user.has_perm('membership.manage_members'):
            messages.error(request, unicode(_("You are not authorized to modify memberships.")))
            return redirect('contact_edit', id)

        form = ContactForm(request.POST, instance=contact)

        if form.is_valid():
            form.save()
            after = model_to_dict(contact)
            log_change(contact, request.user, before, after)
            messages.success(request, unicode(_("Changes to contact %s saved.") % contact))
            return redirect('contact_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to contact %s not saved.") % contact))
    else:
        form = ContactForm(instance=contact)
    logentries = bake_log_entries(contact.logs.all())
    return render_to_response(template_name, {'form': form, 'contact': contact,
        'logentries': logentries, 'memberid': contact.find_memberid()},
        context_instance=RequestContext(request))

@permission_required('membership.manage_bills')
def bill_edit(request, id, template_name='membership/entity_edit.html'):
    bill = get_object_or_404(Bill, id=id)

    class Form(ModelForm):
        class Meta:
            model = Bill
            exclude = ('billingcycle', 'reminder_count', 'pdf_file')

        def __init__(self, *args, **kwargs):
            super(Form, self).__init__(*args, **kwargs)
            instance = getattr(self, 'instance', None)
            if instance and instance.pk:
                self.fields['type'].widget.attrs['readonly'] = True

        def clean_type(self):
            instance = getattr(self, 'instance', None)
            if instance and instance.pk:
                return instance.type
            else:
                return self.cleaned_data['type']

    before = model_to_dict(bill) # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        form = Form(request.POST, instance=bill)
        if form.is_valid():
            form.save()
            after = model_to_dict(bill)
            log_change(bill, request.user, before, after)
            messages.success(request, unicode(_("Changes to bill %s saved.") % bill))
            return redirect('bill_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to bill %s not saved.") % bill))
    else:
        form =  Form(instance=bill)
    logentries = bake_log_entries(bill.logs.all())
    return render_to_response(template_name, {'form': form, 'bill': bill,
        'logentries': logentries,'memberid': bill.billingcycle.membership.id},
        context_instance=RequestContext(request))

@permission_required('membership.read_bills')
def bill_pdf(request, bill_id):
    output_messages = []

    bill = get_object_or_404(Bill, id=bill_id)
    try:
        pdf = bill.generate_pdf()
        if pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = 'inline; filename=bill_%s.pdf' % bill.id
            return response
    except Exception as e:
        logger.exception("Failed to generate pdf for bill %s" % bill.id)
    response = HttpResponseServerError("Failed to generate pdf", content_type='plain/text', )
    return response

@permission_required('membership.manage_bills')
def billingcycle_connect_payment(request, id, template_name='membership/billingcycle_connect_payment.html'):
    billingcycle = get_object_or_404(BillingCycle, id=id)

    class SpeciallyLabeledModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return u"%s, %s, %s, %s" % (obj.payer_name, obj.reference_number, obj.amount, obj.payment_day)

    class PaymentForm(Form):
        qs = Payment.objects.filter(billingcycle__exact=None, ignore=False).order_by("payer_name")
        payment = SpeciallyLabeledModelChoiceField(queryset=qs,
                                                   empty_label=_("None chosen"), required=True)

    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            payment = f['payment']
            before = model_to_dict(payment)
            oldcycle = payment.billingcycle
            if oldcycle:
                oldcycle_before = model_to_dict(oldcycle)
                payment.detach_from_cycle(user=request.user)
                oldcycle_after = model_to_dict(oldcycle)
                log_change(oldcycle, request.user, oldcycle_before, oldcycle_after)

            newcycle = billingcycle
            newcycle_before = model_to_dict(newcycle)
            payment.attach_to_cycle(newcycle)
            newcycle_after = model_to_dict(newcycle)
            after = model_to_dict(payment)
            log_change(payment, request.user, before, after)
            log_change(newcycle, request.user, newcycle_before, newcycle_after)
            messages.success(request, unicode(_("Changes to payment %s saved.") % payment))
            return redirect('billingcycle_edit', id)
        else:
            messages.error(request, unicode(_("Changes to BillingCycle %s not saved.") % billingcycle))
    else:
        form =  PaymentForm()
    logentries = bake_log_entries(billingcycle.logs.all())
    return render_to_response(template_name, {'form': form, 'cycle': billingcycle,
                                              'logentries': logentries},
                              context_instance=RequestContext(request))

@permission_required('membership.can_import_payments')
def import_payments(request, template_name='membership/import_payments.html'):
    import_messages = []
    class PaymentCSVForm(Form):
        csv = FileField(label=_('CSV File'),
                         help_text=_('Choose CSV file to upload'))
        format = ChoiceField(choices=(('op', 'Osuuspankki'), ('procountor', 'Procountor')),
                           help_text=_("File type"))

    if request.method == 'POST':
        form = PaymentCSVForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                in_memory_file = request.FILES['csv']
                logger.info("Beginning payment import.")
                if form.cleaned_data['format'] == 'op':
                    import_messages = process_op_csv(in_memory_file, user=request.user)
                elif form.cleaned_data['format'] == 'procountor':
                    import_messages = process_procountor_csv(in_memory_file, user=request.user)
                messages.success(request, unicode(_("Payment import succeeded!")))
            except:
                  logger.error("%s" % traceback.format_exc())
                  logger.error("Payment CSV import failed.")
                  messages.error(request, unicode(_("Payment import failed.")))
        else:
            messages.error(request, unicode(_("Payment import failed.")))
    else:
        form = PaymentCSVForm()

    return render_to_response(template_name, {'title': _("Import payments"),
                                              'form': form,
                                              'import_messages': import_messages},
                              context_instance=RequestContext(request))

@permission_required('membership.read_bills')
def print_reminders(request, **kwargs):
    output_messages = []
    if request.method == 'POST':
        try:
            if 'marksent' in request.POST:
                for billing_cycle in BillingCycle.get_reminder_billingcycles().all():
                    bill = Bill(billingcycle=billing_cycle, type='P')
                    bill.reminder_count = billing_cycle.bill_set.count()
                    bill.save()
                    bill.generate_pdf()
                output_messages.append(_('Reminders marked as sent'))
            else:
                pdf = BillingCycle.get_pdf_reminders()
                if pdf:
                    response = HttpResponse(pdf, content_type='application/pdf')
                    response['Content-Disposition'] = 'attachment; filename=reminders.pdf'
                    return response
                else:
                    output_messages.append(_('Error processing PDF'))
        except RuntimeError:
            output_messages.append(_('Error processing PDF'))
        except IOError:
            output_messages.append(_('Cannot open PDF file'))
    return render_to_response('membership/print_reminders.html',
    {'title': _("Print paper reminders"),
     'output_messages': output_messages,
     'count': BillingCycle.get_reminder_billingcycles().count()},
     context_instance=RequestContext(request))

@permission_required('membership.manage_bills')
def billingcycle_edit(request, id, template_name='membership/entity_edit.html'):
    cycle = get_object_or_404(BillingCycle, id=id)

    class Form(ModelForm):
        is_paid_forced = False
        class Meta:
            model = BillingCycle
            exclude = ('membership', 'start', 'end', 'sum', 'reference_number')

        def disable_fields(self):
            self.fields['is_paid'].required = False
            if cycle.amount_paid() >= cycle.sum and cycle.is_paid:
                self.fields['is_paid'].widget.attrs['readonly'] = 'readonly'
                self.is_paid_forced = True

        def clean_is_paid(self):
            if self.is_paid_forced:
                return cycle.is_paid
            else:
                return self.cleaned_data['is_paid']

    before = model_to_dict(cycle) # Otherwise save() (or valid?) will change the dict, needs to be here
    if request.method == 'POST':
        form = Form(request.POST, instance=cycle)
        form.disable_fields()
        if form.is_valid():
            form.save()
            after = model_to_dict(cycle)
            log_change(cycle, request.user, before, after)
            messages.success(request, unicode(_("Changes to billing cycle %s saved.") % cycle))
            return redirect('billingcycle_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to bill %s not saved.") % cycle))
    else:
        form =  Form(instance=cycle)
        form.disable_fields()
    logentries = bake_log_entries(cycle.logs.all())
    return render_to_response(template_name,
                              {'form': form, 'cycle': cycle,
                               'logentries': logentries,
                               'memberid': cycle.membership.id},
        context_instance=RequestContext(request))

@permission_required('membership.manage_bills')
def payment_edit(request, id, template_name='membership/entity_edit.html'):
    payment = get_object_or_404(Payment, id=id)

    class SpeciallyLabeledModelChoiceField(ModelChoiceField):
        def label_from_instance(self, obj):
            return u"%s, %s" % (obj.membership, unicode(obj))

    class Form(ModelForm):
        class Meta:
            model = Payment
            fields = '__all__'

        billingcycle = CharField(widget=HiddenInput(), required=False)
        message = CharField(widget=Textarea(attrs={'rows': 5, 'cols': 60}))

        def disable_fields(self):
            if payment.billingcycle:
                self.fields['ignore'].required = False
                self.fields['ignore'].widget.attrs['readonly'] = 'readonly'
            self.fields['billingcycle'].required = False
            self.fields['billingcycle'].widget.attrs['readonly'] = 'readonly'
            self.fields['reference_number'].required = False
            self.fields['reference_number'].widget.attrs['readonly'] = 'readonly'
            self.fields['message'].required = False
            self.fields['message'].widget.attrs['readonly'] = 'readonly'
            self.fields['transaction_id'].required = False
            self.fields['transaction_id'].widget.attrs['readonly'] = 'readonly'
            self.fields['payment_day'].required = False
            self.fields['payment_day'].widget.attrs['readonly'] = 'readonly'
            self.fields['amount'].required = False
            self.fields['amount'].widget.attrs['readonly'] = 'readonly'
            self.fields['type'].required = False
            self.fields['type'].widget.attrs['readonly'] = 'readonly'
            self.fields['payer_name'].required = False
            self.fields['payer_name'].widget.attrs['readonly'] = 'readonly'
            self.fields['comment'].required = False

        def clean_ignore(self):
            if payment.billingcycle:
                return False
            else:
                return self.cleaned_data['ignore']
        def clean_billingcycle(self):
            return payment.billingcycle
        def clean_reference_number(self):
            return payment.reference_number
        def clean_message(self):
            return payment.message
        def clean_transaction_id(self):
            return payment.transaction_id
        def clean_payment_day(self):
            return payment.payment_day
        def clean_amount(self):
            return payment.amount
        def clean_type(self):
            return payment.type
        def clean_payer_name(self):
            return payment.payer_name

    before = model_to_dict(payment) # Otherwise save() (or valid?) will change the dict, needs to be here
    oldcycle = payment.billingcycle
    if request.method == 'POST':
        form = Form(request.POST, instance=payment)
        form.disable_fields()
        if form.is_valid():
            form.save()
            newcycle = payment.billingcycle
            if oldcycle != newcycle:
                if oldcycle:
                    oldcycle.update_is_paid()
            if newcycle:
              newcycle.update_is_paid()
            after = model_to_dict(payment)
            log_change(payment, request.user, before, after)
            messages.success(request, unicode(_("Changes to payment %s saved.") % payment))
            return redirect('payment_edit', id) # form stays as POST otherwise if someone refreshes
        else:
            messages.error(request, unicode(_("Changes to payment %s not saved.") % payment))
            return redirect('payment_edit', id) # form clears otherwise, this is a borderline acceptable hack
    else:
        form = Form(instance=payment)
        form.disable_fields()

    logentries = bake_log_entries(payment.logs.all())
    if payment.billingcycle:
            memberid = payment.billingcycle.membership.id
    else:
            memberid = None

    return render_to_response(template_name, {'form': form, 'payment': payment,
        'logentries': logentries, 'memberid': memberid},
        context_instance=RequestContext(request))

@permission_required('membership.manage_bills')
def send_duplicate_notification(request, payment, **kwargs):
    payment = get_object_or_404(Payment, id=payment)
    payment.send_duplicate_payment_notice(request.user)
    return redirect('payment_edit', payment.id)

@permission_required('membership.read_members')
def membership_edit(request, id, template_name='membership/membership_edit.html'):
    membership = get_object_or_404(Membership, id=id)

    class Form(ModelForm):
        class Meta:
            model = Membership
            exclude = ('person', 'billing_contact', 'tech_contact', 'organization')

        def clean_status(self):
            return membership.status
        def clean_approved(self):
            return membership.approved

        def disable_fields(self):
            self.fields['status'].required = False
            self.fields['status'].widget.attrs['disabled'] = 'disabled'
            self.fields['status'].widget.attrs['readonly'] = 'readonly'
            self.fields['approved'].required = False
            self.fields['approved'].widget.attrs['readonly'] = 'readonly'
            instance = getattr(self, 'instance', None)
            if instance and instance.type == 'O':
                self.fields["birth_year"].widget = HiddenInput()
                self.fields['birth_year'].required = False

    if request.method == 'POST':
        if not request.user.has_perm('membership.manage_members'):
            return HttpResponseForbidden(_("Permission manage required"))
        form = Form(request.POST, instance=membership)
        before = model_to_dict(membership)
        form.disable_fields()
        if form.is_valid():
            form.save()
            after = model_to_dict(membership)
            log_change(membership, request.user, before, after)
            return redirect('membership_edit', id) # form stays as POST otherwise if someone refreshes
    else:
        form = Form(instance=membership)
        form.disable_fields()
    # Pretty print log entries for template
    logentries = bake_log_entries(membership.logs.all())
    return render_to_response(template_name, {'form': form,
        'membership': membership, 'logentries': logentries},
        context_instance=RequestContext(request))

@permission_required('membership.read_members')
def membership_duplicates(request, id):
    membership = get_object_or_404(Membership, id=id)

    view_params = {'queryset': membership.duplicates(),
                   'template_name': 'membership/membership_list.html',
                   'context_object_name': 'member_list',
                   'header':  _(u"List duplicates for member #%(mid)i %(membership)s" % {"mid":membership.id,
                                                                               "membership":unicode(membership)}),
                   'disable_duplicates_header': True,
                   'paginate_by': ENTRIES_PER_PAGE}

    return member_object_list(request, **view_params)

@permission_required('membership.read_members')
def unpaid_paper_reminded(request):
    view_params = {'queryset': Membership.paper_reminder_sent_unpaid_after(),
                   'template_name': 'membership/membership_list.html',
                   'context_object_name': 'member_list',
                   'paginate_by': ENTRIES_PER_PAGE
                   }

    return member_object_list(request, **view_params)

@permission_required('membership.read_members')
def unpaid_paper_reminded_plain(request):
    view_params = {'queryset': Membership.paper_reminder_sent_unpaid_after().order_by('id'),
                   'template_name': 'membership/membership_list_plaintext.html',
                   'context_object_name': 'member_list'
                   }

    return member_object_list(request, **view_params)

@permission_required('membership.delete_members')
def membership_delete(request, id, template_name='membership/membership_delete.html'):
    membership = get_object_or_404(Membership, id=id)
    class ConfirmForm(Form):
        confirm = BooleanField(label=_('To confirm deletion, you must check this box:'),
                               required=True)

    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            membership_str = unicode(membership)
            membership.delete_membership(request.user)
            messages.success(request, unicode(_('Member %s successfully deleted.') % membership_str))
            logger.info("User %s deleted member %s." % (request.user.username, membership))
            return redirect('membership_edit', membership.id)
    else:
        form = ConfirmForm()

    return render_to_response(template_name,
                              {'form': form,
                               'membership': membership },
                              context_instance=RequestContext(request))

@permission_required('membership.dissociate_members')
def membership_dissociate(request, id, template_name='membership/membership_dissociate.html'):
    membership = get_object_or_404(Membership, id=id)
    class ConfirmForm(Form):
        confirm = BooleanField(label=_('To confirm dissociation, you must check this box:'),
                               required=True)

    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            membership_str = unicode(membership)
            membership.dissociate(request.user)
            messages.success(request, unicode(_('Member %s successfully dissociated.') % membership_str))
            logger.info("User %s dissociated member %s." % (request.user.username, membership))
            return redirect('membership_edit', membership.id)
    else:
        form = ConfirmForm()

    return render_to_response(template_name,
                              {'form': form,
                               'membership': membership },
                              context_instance=RequestContext(request))

@permission_required('membership.request_dissociation_for_member')
def membership_request_dissociation(request, id, template_name='membership/membership_request_dissociation.html'):
    membership = get_object_or_404(Membership, id=id)
    class ConfirmForm(Form):
        confirm = BooleanField(label=_('To confirm state change, you must check this box:'),
                               required=True)

    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            membership_str = unicode(membership)
            membership.request_dissociation(request.user)
            messages.success(request, unicode(_('Member %s successfully transferred to requested dissociation state.') % membership_str))
            logger.info("User %s requested dissociation for member %s." % (request.user.username, membership))
            return redirect('membership_edit', membership.id)
    else:
        form = ConfirmForm()

    return render_to_response(template_name,
                              {'form': form,
                               'membership': membership },
                              context_instance=RequestContext(request))

@permission_required('membership.request_dissociation_for_member')
def membership_cancel_dissociation_request(request, id, template_name='membership/membership_cancel_dissociation_request.html'):
    membership = get_object_or_404(Membership, id=id)
    class ConfirmForm(Form):
        confirm = BooleanField(label=_('To confirm state change, you must check this box:'),
                               required=True)

    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            membership_str = unicode(membership)
            membership.cancel_dissociation_request(request.user)
            messages.success(request, unicode(_('Member %s successfully transferred back to approved state.') % membership_str))
            logger.info("User %s requested dissociation for member %s." % (request.user.username, membership))
            return redirect('membership_edit', membership.id)
    else:
        form = ConfirmForm()

    return render_to_response(template_name,
                              {'form': form,
                               'membership': membership },
                              context_instance=RequestContext(request))

@permission_required('membership.manage_members')
def membership_convert_to_organization(request, id, template_name='membership/membership_convert_to_organization.html'):
    membership = get_object_or_404(Membership, id=id)
    class ConfirmForm(Form):
        confirm = BooleanField(label=_('To confirm conversion, you must check this box:'),
                               required=True)

    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
            membership.type = 'O'
            contact = membership.person
            membership.person = None
            membership.organization = contact
            membership.save()
            log_change(membership, request.user, change_message="Converted to an organization")
            messages.success(request, unicode(_('Member %s successfully converted to an organization.') % membership))
            logger.info("User %s converted member %s to an organization." % (request.user.username, membership))
            return redirect('membership_edit', membership.id)
    else:
        form = ConfirmForm()

    return render_to_response(template_name,
                              {'form': form,
                               'membership': membership },
                              context_instance=RequestContext(request))

@permission_required('membership.manage_members')
def membership_preapprove_json(request, id):
    m = get_object_or_404(Membership, id=id)
    try:
        m.preapprove(request.user)
    except MembershipAlreadyStatus:
        pass  # Success if we didn't do anything
    return HttpResponse(id, content_type='text/plain')

@permission_required('membership.manage_members')
def membership_approve_json(request, id):
    m = get_object_or_404(Membership, id=id)
    try:
        m.approve(request.user)
    except MembershipAlreadyStatus:
        pass  # Success if we didn't do anything
    return HttpResponse(id, content_type='text/plain')

@permission_required('membership.read_members')
def membership_detail_json(request, id):
    membership = get_object_or_404(Membership, id=id)
    json_obj = serializable_membership_info(membership)
    return HttpResponse(json.dumps(json_obj, sort_keys=True, indent=4),
                        content_type='application/json')

# Public access
def handle_json(request):
    logger.debug("RAW POST DATA: %s" % request.body)
    msg = json.loads(request.body)
    funcs = {'PREAPPROVE': membership_preapprove_json,
             'APPROVE': membership_approve_json,
             'MEMBERSHIP_DETAIL': membership_detail_json,
             'ALIAS_AVAILABLE': check_alias_availability,
             'VALIDATE_ALIAS': validate_alias}
    if not funcs.has_key(msg['requestType']):
        raise NotImplementedError()
    logger.debug("AJAX call %s, payload: %s" % (msg['requestType'],
                                                 unicode(msg['payload'])))
    try:
        return funcs[msg['requestType']](request, msg['payload'])
    except Exception as e:
        logger.critical("%s" % traceback.format_exc())
        raise e

@login_required
def test_email(request, template_name='membership/test_email.html'):
    class RecipientForm(Form):
        recipient = EmailField(label=_('Recipient e-mail address'))

    if request.method == 'POST':
        form = RecipientForm(request.POST)
        if form.is_valid():
            f = form.cleaned_data
        else:
            return render_to_response(template_name, {'form': form},
                                      context_instance=RequestContext(request))

        body = render_to_string('membership/test_email.txt', { "user": request.user })
        send_mail(u"Testisähköposti", body,
                  settings.FROM_EMAIL,
#                  request.user.email,
                  [f["recipient"]], fail_silently=False)
        logger.info("Sent a test e-mail to %s" % f["recipient"])

    return render_to_response(template_name, {'form': RecipientForm()},
                              context_instance=RequestContext(request))

@trusted_host_required
def membership_metrics(request):
    unpaid_cycles = BillingCycle.objects.filter(membership__status='A', is_paid=False)
    unpaid_sum = unpaid_cycles.aggregate(Sum("sum"))['sum__sum']
    if unpaid_sum == None:
        unpaid_sum = "0.0"
    d = {'memberships':
         {'new': Membership.objects.filter(status='N').count(),
          'preapproved': Membership.objects.filter(status='P').count(),
          'approved': Membership.objects.filter(status='A').count(),
          'deleted': Membership.objects.filter(status='D').count(),
          },
         'bills':
         {'unpaid_count': unpaid_cycles.count(),
          'unpaid_sum': float(unpaid_sum),
          },
         }
    return HttpResponse(json.dumps(d, sort_keys=True, indent=4),
                        content_type='application/json')

@trusted_host_required
def public_memberlist(request):
    template_name = 'membership/public_memberlist.xml'
    data = public_memberlist_data()
    return render_to_response(template_name, data, content_type='text/xml')

@trusted_host_required
def unpaid_members(request):
    json_obj = unpaid_members_data()
    return HttpResponse(json.dumps(json_obj, sort_keys=True, indent=4),
                        content_type='application/json')

@trusted_host_required
def admtool_membership_detail_json(request, id):
    membership = get_object_or_404(Membership, id=id)
    json_obj = admtool_membership_details(membership)
    return HttpResponse(json.dumps(json_obj, sort_keys=True, indent=4),
                        content_type='application/json')

@trusted_host_required
def admtool_lookup_alias_json(request, alias):
    aliases = Alias.objects.filter(name__iexact=alias)
    if len(aliases) == 1:
        return HttpResponse(aliases[0].owner.id, content_type='text/plain')
    elif not aliases:
        return HttpResponse("No match", content_type='text/plain')
    return HttpResponse("Too many matches", content_type='text/plain')

@permission_required('membership.read_members')
def member_object_list(request, **kwargs):
    return SortListView.as_view(**kwargs)(request)

@permission_required('membership.read_bills')
def billing_object_list(request, **kwargs):
    return SortListView.as_view(**kwargs)(request)

# This should list any bills/cycles that were forcefully set as paid even
# though insufficient payments were paid.
# @permission_required('membership.read_bills')
# def forced_paid_cycles_list(*args, **kwargs):
#     paid_q = Q(is_paid__exact=True)
#     payments_sum_q = Q(payment_set.aggregate(Sum('amount'))__lt=sum)
#     qs = BillingCycle.objects.filter(paid_q, payments_sum_q)
#     return ListView.as_view(**kwargs, queryset=qs)(request))

@permission_required('membership.read_members')
def search(request, **kwargs):
    query = request.GET.get('query', '')

    # Shorthand for viewing a membership by giving # and the id
    if query.startswith("#"):
        try:
            return redirect('membership_edit', int(query.lstrip("#")))
        except ValueError as ve:
            pass

    qs = Membership.search(query)

    if qs.count() == 1:
        return redirect('membership_edit', qs[0].id)

    kwargs['queryset'] = qs.order_by("organization__organization_name",
                     "person__last_name",
                     "person__first_name")
    kwargs['search_query'] = query
    return SortListView.as_view(**kwargs)(request)


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _Message = require('./Message');

var _events = require('events');

var log = false;

var MessageBus = (function () {
  function MessageBus() {
    _classCallCheck(this, MessageBus);

    this.messageEmitter = new _events.EventEmitter();
  }

  _createClass(MessageBus, [{
    key: 'publish',
    value: function publish(message) {
      this.checkPublish(message);
      if (log) console.log("publish '" + message.name + "' with payload '" + message.payload + "'");
      this.messageEmitter.emit(message.name, message);
      return;
    }
  }, {
    key: 'subscribe',
    value: function subscribe(messageName, callback) {
      if (log) console.log("subscribe to name '" + messageName + "' by callback '" + callback + "'");
      this.checkSubscribe(messageName, callback);
      this.messageEmitter.on(messageName, callback);
      return;
    }
  }, {
    key: 'checkSubscribe',
    value: function checkSubscribe() {}
  }, {
    key: 'checkPublish',
    value: function checkPublish(message) {
      if (!(message instanceof _Message.Message)) {
        throw new Error("Publish works only on instances of Message");
      }
    }
  }]);

  return MessageBus;
})();

exports.MessageBus = MessageBus;
//# sourceMappingURL=MessageBus.js.map

redpajama_set_name: RedPajamaGithub


text:
.resource-example h1 {
  background-color: purple
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rep. Tottori Mycol. Inst. 16: 50 (1978)

#### Original name
Boletus hortonii A.H. Sm. & Thiers

### Remarks
null


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.security.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The ARC autoprovisioning configuration. */
@Fluent
public final class DefenderForServersAwsOfferingArcAutoProvisioning {
    /*
     * Is arc auto provisioning enabled
     */
    @JsonProperty(value = "enabled")
    private Boolean enabled;

    /*
     * The cloud role ARN in AWS for this feature
     */
    @JsonProperty(value = "cloudRoleArn")
    private String cloudRoleArn;

    /** Creates an instance of DefenderForServersAwsOfferingArcAutoProvisioning class. */
    public DefenderForServersAwsOfferingArcAutoProvisioning() {
    }

    /**
     * Get the enabled property: Is arc auto provisioning enabled.
     *
     * @return the enabled value.
     */
    public Boolean enabled() {
        return this.enabled;
    }

    /**
     * Set the enabled property: Is arc auto provisioning enabled.
     *
     * @param enabled the enabled value to set.
     * @return the DefenderForServersAwsOfferingArcAutoProvisioning object itself.
     */
    public DefenderForServersAwsOfferingArcAutoProvisioning withEnabled(Boolean enabled) {
        this.enabled = enabled;
        return this;
    }

    /**
     * Get the cloudRoleArn property: The cloud role ARN in AWS for this feature.
     *
     * @return the cloudRoleArn value.
     */
    public String cloudRoleArn() {
        return this.cloudRoleArn;
    }

    /**
     * Set the cloudRoleArn property: The cloud role ARN in AWS for this feature.
     *
     * @param cloudRoleArn the cloudRoleArn value to set.
     * @return the DefenderForServersAwsOfferingArcAutoProvisioning object itself.
     */
    public DefenderForServersAwsOfferingArcAutoProvisioning withCloudRoleArn(String cloudRoleArn) {
        this.cloudRoleArn = cloudRoleArn;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
package com.xthena.gcgl.manager;

import com.xthena.gcgl.domain.PjHuiyi;

import com.xthena.core.hibernate.HibernateEntityDao;

import org.springframework.stereotype.Service;

@Service
public class PjHuiyiManager extends HibernateEntityDao<PjHuiyi> {
}


text:
import React, { Component } from 'react';
import { AppRegistry, ScrollView, Image, Text } from 'react-native'

export default class NewsFeed extends Component {
  render(){
    return(
      <ScrollView style={{backgroundColor : 'white'}}>

      <Image source={require('../images/Social-comm.png')} style={{width:360,height:64}}/>
      <Text style={{fontSize:20}}>club here</Text>
      <Image source={require('../images/Arts.png')}style={{width:360,height:64}} />
      <Text style={{fontSize:20}}>club here</Text>
      <Image source={require('../images/Makers.png')} style={{width:360,height:64}}/>
      <Text style={{fontSize:20}}>club here</Text>
      <Image source={require('../images/Sports.png')}style={{width:360,height:64}} />
      <Text style={{fontSize:20}}>club here</Text>
      <Image source={require('../images/Culture.png')} style={{width:360,height:64}}/>
      <Text style={{fontSize:20}}>club here</Text>
      </ScrollView>
    );
  }
}
AppRegistry.registerComponent(
  'NewsFeed',
  () => NewsFeed);


text:
package com.youzi.friends;

import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import java.util.List;

/**
 * Created by Administrator on 2017/8/11.
 */

public class CardItemTouchHelperCallback<T> extends ItemTouchHelper.Callback {

    private final RecyclerView.Adapter adapter;
    private List dataList;
    private OnSwipeListener<T> mListener;

    public CardItemTouchHelperCallback(@NonNull RecyclerView.Adapter adapter, @NonNull List<T> dataList){
        this.adapter = checkIsNull(adapter);
        this.dataList = checkIsNull(dataList);
    }

    public CardItemTouchHelperCallback(@NonNull RecyclerView.Adapter adapter, @NonNull List<T> dataList, OnSwipeListener<T> listener) {
        this.adapter = checkIsNull(adapter);
        this.dataList = checkIsNull(dataList);
        this.mListener = listener;
    }

    private <T> T checkIsNull(T t) {
        if (t == null) {
            throw new NullPointerException();
        }
        return t;
    }

    public void setOnSwipedListener(OnSwipeListener<T> mListener) {
        this.mListener = mListener;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = 0;
        int swipeFlags = 0;
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof CardLayoutManager) {
            swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        }
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        // 移除之前设置的 onTouchListener,否则触摸滑动会乱了
        viewHolder.itemView.setOnTouchListener(null);
        // 删除相对应的数据
        int layoutPosition = viewHolder.getLayoutPosition();
        T remove = (T) dataList .remove(layoutPosition);
        adapter.notifyDataSetChanged();
        // 卡片滑出后回调 OnSwipeListener 监听器
        if (mListener != null) {
            mListener.onSwiped(viewHolder, remove, direction == ItemTouchHelper.LEFT ? CardConfig.SWIPED_LEFT : CardConfig.SWIPED_RIGHT);
        }
        // 当没有数据时回调 mListener
        if (adapter.getItemCount() == 0) {
            if (mListener != null) {
                mListener.onSwipedClear();
            }
        }
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        //为了防止第二层和第三层卡片也能滑动
        return false;
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        View itemView = viewHolder.itemView;
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            // 得到滑动的阀值
            float ratio = dX / getThreshold(recyclerView, viewHolder);
            // ratio 最大为 1 或 -1
            if (ratio > 1) {
                ratio = 1;
            } else if (ratio < -1) {
                ratio = -1;
            }
            itemView.setRotation(ratio * CardConfig.DEFAULT_ROTATE_DEGREE);
            int childCount = recyclerView.getChildCount();
            // 当数据源个数大于最大显示数时
            if (childCount > CardConfig.DEFAULT_SHOW_ITEM) {
                for (int position = 1; position < childCount - 1; position++) {
                    int index = childCount - position - 1;
                    View view = recyclerView.getChildAt(position);
                    // 和之前 onLayoutChildren 是一个意思,不过是做相反的动画
                    view.setScaleX(1 - index * CardConfig.DEFAULT_SCALE + Math.abs(ratio) * CardConfig.DEFAULT_SCALE);
                    view.setScaleY(1 - index * CardConfig.DEFAULT_SCALE + Math.abs(ratio) * CardConfig.DEFAULT_SCALE);
                    view.setTranslationY((index - Math.abs(ratio)) * itemView.getMeasuredHeight() / CardConfig.DEFAULT_TRANSLATE_Y);
                }
            } else {
                // 当数据源个数小于或等于最大显示数时
                for (int position = 0; position < childCount - 1; position++) {
                    int index = childCount - position - 1;
                    View view = recyclerView.getChildAt(position);
                    view.setScaleX(1 - index * CardConfig.DEFAULT_SCALE + Math.abs(ratio) * CardConfig.DEFAULT_SCALE);
                    view.setScaleY(1 - index * CardConfig.DEFAULT_SCALE + Math.abs(ratio) * CardConfig.DEFAULT_SCALE);
                    view.setTranslationY((index - Math.abs(ratio)) * itemView.getMeasuredHeight() / CardConfig.DEFAULT_TRANSLATE_Y);
                }
            }
            if (mListener != null) {
                if (ratio != 0) {
                    mListener.onSwiping(viewHolder, ratio, ratio < 0 ? CardConfig.SWIPING_LEFT : CardConfig.SWIPING_RIGHT);
                } else {
                    mListener.onSwiping(viewHolder, ratio, CardConfig.SWIPING_NONE);
                }
            }
        }
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setRotation(0f);
    }

    private float getThreshold(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        return recyclerView.getWidth() * getSwipeThreshold(viewHolder);
    }
}


text:
package ch.bfh.ti.jts.importer;

import static ch.bfh.ti.jts.utils.Helpers.convert;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * Abstract class for XML file importers.
 *
 * @author Enteee
 * @author winki
 * @param <T>
 *            type of the imported class file.
 */
public abstract class Importer<T> {

    private DocumentBuilderFactory documentBuilderFactory;
    private DocumentBuilder        documentBuilder;
    private Document               document;
    private T                      data;

    public Importer() {
        try {
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Abstract method that handles the data extraction.
     *
     * @param document
     *            XML document
     * @return object representation of the imported file
     */
    abstract T extractData(final Document document);

    /**
     * Get the attribute value of a node with the specified type.
     *
     * @param node
     *            document node
     * @param attributeName
     *            name of the attribute to convert
     * @param outputClass
     *            output type of the attribute
     * @return attribute value
     */
    protected <O> O getAttribute(final Node node, final String attributeName, final Class<O> outputClass) {
        O output = null;
        try {
            if (node.hasAttributes()) {
                final Node attribute = node.getAttributes().getNamedItem(attributeName);
                if (attribute != null) {
                    final String value = attribute.getNodeValue();
                    output = convert(value, outputClass);
                }
            }
        } catch (final Exception ex) {
            throw new RuntimeException("conversion failed", ex);
        }
        return output;
    }

    /**
     * Imports data from a file into an object representation.
     *
     * @param path
     *            path to the file to import
     * @return object representation of the imported file
     */
    public T importData(final String path) {
        try {
            document = documentBuilder.parse(path);
            data = extractData(document);
        } catch (final Exception ex) {
            throw new RuntimeException("document parsing failed", ex);
        }
        return data;
    }
}


text:
let User = require.main.require('./models/user');
let validator = require('validator');
require.main.require('./config/custom-validation')(validator);
let handlers = require.main.require('./routes/services/handlers');

module.exports = function(app, passport, isLoggedIn) {
  app.get('/setup/youtube/subscriptions', isLoggedIn, function(req, res) {
    User.setUpYouTubeSubs(req.user._id, function(err, allContent,
        existingContent) {
      let settings = {
        name: 'YouTube',
        error: 'Error: Refreshed Access Token',
        singular: 'subscription'
      };
      handlers.retrieveActivity(settings, err, allContent, existingContent, req,
        res);
    });
  });
};


text:
.class Lcom/android/server/wm/WindowAnimator$1;
.super Ljava/lang/Object;
.source "WindowAnimator.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/wm/WindowAnimator;-><init>(Lcom/android/server/wm/WindowManagerService;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/wm/WindowAnimator;

# direct methods
.method constructor <init>(Lcom/android/server/wm/WindowAnimator;)V
    .locals 0

    .prologue
    .line 127
    iput-object p1, p0, Lcom/android/server/wm/WindowAnimator$1;->this$0:Lcom/android/server/wm/WindowAnimator;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 3

    .prologue
    .line 130
    iget-object v0, p0, Lcom/android/server/wm/WindowAnimator$1;->this$0:Lcom/android/server/wm/WindowAnimator;

    iget-object v0, v0, Lcom/android/server/wm/WindowAnimator;->mService:Lcom/android/server/wm/WindowManagerService;

    iget-object v1, v0, Lcom/android/server/wm/WindowManagerService;->mWindowMap:Ljava/util/HashMap;

    monitor-enter v1

    .line 131
    :try_start_0
    iget-object v0, p0, Lcom/android/server/wm/WindowAnimator$1;->this$0:Lcom/android/server/wm/WindowAnimator;

    iget-object v0, v0, Lcom/android/server/wm/WindowAnimator;->mService:Lcom/android/server/wm/WindowManagerService;

    const/4 v2, 0x0

    iput-boolean v2, v0, Lcom/android/server/wm/WindowManagerService;->mAnimationScheduled:Z

    .line 132
    iget-object v0, p0, Lcom/android/server/wm/WindowAnimator$1;->this$0:Lcom/android/server/wm/WindowAnimator;

    # invokes: Lcom/android/server/wm/WindowAnimator;->animateLocked()V
    invoke-static {v0}, Lcom/android/server/wm/WindowAnimator;->access$000(Lcom/android/server/wm/WindowAnimator;)V

    .line 133
    monitor-exit v1

    .line 134
    return-void

    .line 133
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method


text:
/* SourcesWidget.cs
 * Subclass of EmbeddedWidget
 * Handles the logic for displaying sources
 * Parameters are a parent (MainWindow), a description, an image, a dictionary of sources, and
 * the currently active source.
 * SourcesWidget is a little different from the other subclasses. It has a description box, which holds
 * the image for the episode and a description of the episode. It's table is also smaller with only one
 * row and three columns. It is the only widget to override OnSourcesChanged and it always hides the loadmore button.
*/

using System;
using System.Collections.Generic;
using System.Linq;

namespace VideoAggregator
{
	//[System.ComponentModel.ToolboxItem (true)]
	public class SourcesWidget : EmbeddedWidget
	{
		private string desc;
		private Gdk.Pixbuf thumb;

		//keys are the name of the source
		//values is a list of urls
		private Dictionary<string, List<string> > sources;

		//the currently active source in the SourceComboBox in the MainWindow
		private Source activeSource;

		public SourcesWidget (MainWindow parent, string desc, Gdk.Pixbuf thumb, Dictionary<string, List<string> > sources, Source activeSource) : base()
		{
			this.parent = parent;
			this.sources = sources;
			this.desc = desc;
			this.thumb = thumb;
			this.activeSource = activeSource;

			this.Build ();
			this.ShowAll ();
			this.loadMoreButton.Destroy (); //never more results to display

		}

		protected new void Build ()
		{
			this.Name = "SourcesWidget";
			if ((this.Child != null)) {
				this.Child.ShowAll ();
			}

			makeDescriptionBox ();
			initTable ();
			populateTable ();

		}

		//Makes the box that holds the image and description of episode/movie
		//puts it above the table
		protected void makeDescriptionBox(){
			Gtk.Image img = new Gtk.Image();
			if (thumb != null)
				img.Pixbuf = thumb;

			Gtk.Label lbl = new Gtk.Label (desc);
			lbl.LineWrap = true;
			lbl.ModifyFont (Pango.FontDescription.FromString("12"));
			lbl.WidthRequest = 600;
			Gtk.VBox box = new Gtk.VBox ();
			box.Add (img);
			box.Add (lbl);
			containerVbox.PackStart(box);
		}

		//overrides initTable to make a table with only 1 row and 3 columns
		protected override void initTable(){
			this.table = new Gtk.Table (((uint)(3)), ((uint)(1)), true);
			this.table.Name = "table";
			this.table.RowSpacing = ((uint)(1));
			this.table.ColumnSpacing = ((uint)(6));
			this.showContainer.PackStart (this.table);
		}

		//populate the table with the sources
		//each source is in an eventbox
		protected void populateTable(){
			List<string> srcs = sources.Keys.ToList();

			//change what will be displayed based on the active source
			switch (activeSource) {
			case Source.All:
				break;
			case Source.Hulu:
				if (srcs.Contains ("Hulu"))
					srcs = new List<string>{ "Hulu" };
				else
					srcs = new List<string> ();
				break;
			case Source.Amazon:
				if (srcs.Contains ("Amazon"))
					srcs = new List<string>{ "Amazon" };
				else
					srcs = new List<string> ();
				break;
			case Source.YouTube:
				if (srcs.Contains ("YouTube"))
					srcs = new List<string>{ "YouTube" };
				else
					srcs = new List<string> ();
				break;
			}

			//loop through table
			int curSource = 0;
			for (uint i = 0; i < 1; i++) {
				if (curSource >= srcs.Count)
					break;

				for (uint j = 0; j < 3; j++) {
					if (curSource >= srcs.Count)
						break;

					//image for the sources are stored in the MainWindow
					Gtk.Image img = new Gtk.Image();
					if (srcs [curSource] == "Hulu")
						img.Pixbuf = MainWindow.huluLogo;
					else if ((srcs[curSource] == "Amazon"))
						img.Pixbuf = MainWindow.amazonLogo;
					else if ((srcs[curSource] == "YouTube"))
						img.Pixbuf = MainWindow.youtubeLogo;

					//source item
					Gtk.Label lbl = new Gtk.Label (srcs[curSource]);
					lbl.ModifyFont (Pango.FontDescription.FromString("12"));
					Gtk.VBox box = new Gtk.VBox ();
					box.Add (img);
					box.Add (lbl);
					Gtk.EventBox eventbox = new Gtk.EventBox ();
					eventbox.Add (box);

					//create event for clicking a source
					Func<string, Gtk.ButtonPressEventHandler> ButtonPressWrapper = ((src) => ((s, e) => { OnSourceSelected(s, e, src); }));
					eventbox.ButtonPressEvent += ButtonPressWrapper(srcs[curSource]);

					//create hover events
					Func<Gtk.EventBox, Gtk.EnterNotifyEventHandler> EnterNotifyWrapper = ((Gtk.EventBox eBox) => ((s, e) => {OnHoverEnter(s,e,eBox);}));
					eventbox.EnterNotifyEvent += EnterNotifyWrapper(eventbox);

					Func<Gtk.EventBox, Gtk.LeaveNotifyEventHandler> LeaveNotifyWrapper = ((Gtk.EventBox eBox) => ((s, e) => {OnHoverLeave(s,e,eBox);}));
					eventbox.LeaveNotifyEvent += LeaveNotifyWrapper(eventbox);

					table.Attach (eventbox, j, j + 1, i, i + 1);

					curSource++;
					if (curSource >= sources.Keys.Count)
						break;
				}
			}
		}

		//Event handler for selecting a source. Calls the MainWindow method
		protected void OnSourceSelected (object o, Gtk.ButtonPressEventArgs args, string source)
		{
			List<string> urls = sources[source];
			parent.sourceSelected (source, urls);
		}

		//Updates active source and then the table. Called from MainWindow
		public override void OnSourceChanged(Source activeSource){
			this.activeSource = activeSource;
			showContainer.Remove (table);
			initTable ();
			populateTable ();
			this.ShowAll ();
		}
	}
}


text: server '<%= staging_server %>', :app, :web, :db, :primary => true


text: Welcome to the Draft Room!


text:
local typedefs = require "kong.db.schema.typedefs"

return {
    name = "cookies-to-headers",
    fields = {
        { consumer = typedefs.no_consumer },
        { protocols = typedefs.protocols_http },
        {
            config = {
                type = "record",
                fields = {
                    { cookie_name = { type = "string", default = "SESSION", required = false }, },
                    { header_name = { type = "string", default = "Authorization", required = false }, },
                },
            }
        },
    },
}


text:
package com.adaptris.jdbc;

public class StoredProcedureParameter {

  private String name;

  private int order;

  private Object inValue;

  private Object outValue;

  private ParameterValueType parameterValueType;

  private ParameterType parameterType;

  public StoredProcedureParameter() {
  }

  public StoredProcedureParameter(String name, int order, ParameterValueType type, ParameterType parameterType, Object value) {
    this.setName(name);
    this.setOrder(order);
    this.setParameterValueType(type);
    this.setParameterType(parameterType);
    this.setInValue(value);
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getOrder() {
    return order;
  }

  public void setOrder(int order) {
    this.order = order;
  }

  public Object getInValue() {
    return inValue;
  }

  public void setInValue(Object value) {
    this.inValue = value;
  }

  public ParameterValueType getParameterValueType() {
    return parameterValueType;
  }

  public void setParameterValueType(ParameterValueType parameterValueType) {
    this.parameterValueType = parameterValueType;
  }

  public ParameterType getParameterType() {
    return parameterType;
  }

  public void setParameterType(ParameterType parameterType) {
    this.parameterType = parameterType;
  }

  public Object getOutValue() {
    return outValue;
  }

  public void setOutValue(Object outValue) {
    this.outValue = outValue;
  }

  public String toString() {
    StringBuffer buffer = new StringBuffer();
    buffer.append("Name = " + this.getName() + "; ");
    buffer.append("Order = " + this.getOrder() + "; ");
    buffer.append("InValue = " + this.getInValue() + "; ");
    buffer.append("OutValue = " + this.getOutValue() + "; ");
    buffer.append("ParameterType = " + this.getParameterType() + "; ");
    buffer.append("ParameterValueType = " + this.getParameterValueType());
    return buffer.toString();
  }

}


text:
import { has, createDict, defProp, defProps, isPlain, getKeys } from './object'
import { isDom, isArray, isStrOrNum, isFn } from './check'
import { toStringNode, toBool, c2d } from './util'
import { each, every, map } from './collection'
import { setObserver } from './observer'
import { assign, assignExtend } from './assign'
import { attachEvent } from './event'
import { setReference } from './reference'
import { insertBefore } from './insert_node'
import { Component } from './component'

var pxChecks = ['width', 'height', 'maxWidth', 'minWidth', 'maxHeight', 'minHeight']
!['', 'Top', 'Right', 'Bottom', 'Left'].forEach(function (pos) {
    pxChecks.push('padding' + pos)
    pxChecks.push('margin' + pos)
})

var dimensionStyle = pxChecks,
    displayStyle = ['color', 'backgroundColor', 'background', 'display', 'position', 'border', 'transform', 'opacity', 'fontSize'],
    shareStyle = ['defaults'],
    specialChecks = ['style', 'attrs'],
    childrenChecks = [ 'children', 'items'],
    evtArrChecks = ['events'],
    directStyleChecks = dimensionStyle.concat(displayStyle)

var mouseEvts = ['click', 'mousedown', 'mouseup', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave', 'mousemove'],
    dragEvts = ['dragstart', 'dragend', 'drag', 'dragover', 'dragenter', 'dragleave', 'drop'],
    focusEvts = ['blur', 'focus'],
    keyEvts = ['keydown', 'keypress', 'keyup'],
    formEvts = ['change', 'input', 'submit'],
    touchEvts = ['touchstart', 'touchmove', 'touchend'],
    scrEvts = ['wheel', 'scroll'],
    eventChecks = mouseEvts.concat(dragEvts,focusEvts,keyEvts,formEvts,touchEvts,scrEvts)

var cbChecks = ['created', 'appended'],
    classChecks = ['className', 'cls'],
    delayExtraClasses = ['xtraCls', 'xCls'],
    allClassNameChecks = delayExtraClasses.concat(classChecks),
    delayTextProps = ['text', 'textContent'],
    delayAppendTarget = ['parent'],
    allChecks = dimensionStyle.concat(
        displayStyle,
        shareStyle,
        specialChecks,
        childrenChecks,
        evtArrChecks,
        eventChecks,
        cbChecks,
        classChecks,
        delayExtraClasses,
        delayTextProps,
        delayAppendTarget
    )

var dimRange = dimensionStyle.length,
    disRange = dimRange + displayStyle.length,
    shareRange = disRange + shareStyle.length,
    specialRange = shareRange + specialChecks.length,
    childrenRange = specialRange + childrenChecks.length,
    evtArrRange = childrenRange + evtArrChecks.length,
    evtRange = evtArrRange + eventChecks.length,
    cbRange = evtRange + cbChecks.length,
    clsRange = cbRange + classChecks.length,
    xtraRange = clsRange + delayExtraClasses.length,
    textRange = xtraRange + delayTextProps.length
/**
 * @private specialKey {number} key for differentiating template groups
 */
var specialKey = Math.floor(Math.random() * 100000)
/**
 * @param el {Element}
 * @returns {Object}
 */
function getDefaults(el) {
    var elSetups = el.setups
    return elSetups ? elSetups.__configs.defaults : null
}
/**
 * Return children configs object when element is created by dominic
 * Return null if error / not found
 * @param el {Element}
 */
function getChildrenConfigs(el) {
    var elSetups = el.setups
    if (!elSetups) return null
    if (has(elSetups, 'items'))
        return elSetups.items
    if (has(elSetups, 'children'))
        return elSetups.children
    return null
}
/**
 * @param el {Element}
 * @param defs {Object} el definitions
 */
function setDefs(el, defs) {
    var elSetups = el.setups,
        configs = elSetups.__configs,
        events = elSetups.__events,
        evtLen = events.length,
        elStyle = el.style
    for (var key in defs) {
        if (has(defs, key)) {
            var val = defs[key],
                keyIdx = allChecks.indexOf(key)
            if (keyIdx == -1)
                el[key] = val
            else {
                if (keyIdx < dimRange) {
                    elStyle[key] = isNaN(val) ? val : (val + 'px')
                } else if (keyIdx < disRange) {
                    elStyle[key] = val
                } else if (keyIdx < shareRange) {
                    if (!has(configs, 'defaults')) {
                        defProp(configs, 'defaults', { value: createDict() })
                    }
                    assign(configs.defaults, val)
                } else if (keyIdx < specialRange) {
                    elSetups[key] = val
                } else if (keyIdx < childrenRange) {
                    elSetups.children = val
                } else if (keyIdx < evtArrRange) {
                    val.forEach(function (evtArgs) { events[evtLen++] = evtArgs })
                } else if (keyIdx < evtRange) {
                    events[evtLen++] = assign({ type: key }, val)
                } else if (keyIdx < cbRange) {
                    elSetups[key] = val
                } else if (keyIdx < xtraRange) {
                    if (!val) continue
                    if (!has(elSetups, 'cls')) {
                        elSetups.cls = ''
                    }
                    elSetups.cls += val + ' '
                } else if (keyIdx < textRange) {
                    el.appendChild(document.createTextNode(val))
                } else {
                    defProp(elSetups, 'parent', { value: val })
                }
            }
        }
    }
}
/**
 * @param el {Element}
 */
function setAttrs(el) {
    var elSetups = el.setups
    if (!elSetups || !has(elSetups, 'attrs')) return
    each(elSetups.attrs, function(value, attrName) {
        el.setAttribute(c2d(attrName), value)
    })
}
/**
 * @param el {Element}
 */
function setStyles(el) {
    var elSetups = el.setups
    if (!elSetups || !has(elSetups, 'style')) return
    var elStyle = el.style,
        styles = elSetups.style
    for (var s in styles) {
        if (has(styles, s)) {
            var styleVal = styles[s]
            if (pxChecks.indexOf(s) !== -1)
                elStyle[s] = isNaN(styleVal) ? styleVal : (styleVal + 'px')
            else
                elStyle[s] = styleVal
        }
    }
}
/**
 * @param el {Element}
 * @param root {Element}
 */
function setEvents(el, root) {
    var elSetups = el.setups
    if (!elSetups || !has(elSetups, '__events')) return
    for (var i = 0, elEvents = elSetups.__events, len = elEvents.length; i < len; i++) {
        var evtArgs = elEvents[i]
        attachEvent(el, evtArgs, root)
    }
}
/**
 * set class attribute for element, from el.setups
 * @param el {Element}
 */
function setCls(el) {
    var elSetups = el.setups
    if (!elSetups || !has(elSetups, 'cls') || !elSetups.cls) return
    el.className = elSetups.cls.trim()
}
function callCreated(el, root) {
    var elSetups = el.setups
    if (!elSetups || !has(elSetups, 'created')) return
    if (isFn(elSetups.created))
        elSetups.created.call(root, el, root)
}
/**
 * @param defs {Object} child definitions
 * @returns {Element}
 */
function createChildren(defs) {
    if (has(defs, 'if') && !toBool(defs.if)) return null
    var tag = has(defs, 'tag') ? defs.tag : 'div',
        el = document.createElement(tag)
    createSetupsHolder(el)
    setDefs(el, defs)
    return el
}
/**
 * @param el {Element} parent -> for defaults configs purpose
 * @param object {Object} child definitions
 * {Element}
 */
function object2children(el, object, root) {
    var defaults = getDefaults(el),
        defs = assignExtend(object, defaults),
        child = createChildren(defs)
    if (!child) return null
    setAttrs(child)
    setStyles(child)
    setEvents(child, root)
    setCls(child)
    if (has(child, 'hide') && toBool(child.hide))
        child.style.display = 'none'
    child.root_ = root
    return child
}
/**
 * @param parent {Element}
 * @param child {Element}
 * @param root {Element}
 * @param [stop] {Element}
 */
function appendChild(parent, child, root, stop) {
    if (child === null || typeof child === 'undefined') return
    setReference(parent, child, root)
    insertBefore(parent, child, stop)
    if (has(child, 'd__isCmp')) {
        if (has(child, 'hide'))
            child.style.display = 'none'
        child.root_ = root
        return
    }
    var f2 = getChildrenConfigs(child)
    setChildren(child, f2, root)
    callCreated(child, root)
}
/**
 * Used by 'for', does not accept array as input
 * @param el {Element}
 * @param input {(string|number|Object)}
 * @param root {Element}
 * @param [groupKey] {number}
 */
function makeChild(el, input, root, groupKey) {
    var child = null
    if (isArray(input) || typeof input === 'function') {
        console.info('Return value in template function is an array or a function. Ingored')
        return null
    }
    if (isPlain(input)) {
        if (has(input, 'ctype'))
            child = createComponent(input)
        else
            child = object2children(el, input, root)
    } else if (isStrOrNum(input)) {
        child = document.createTextNode(input)
    } else if (isDom(input)) {
        child = input
    }
    if (groupKey && child)
        child.groupKey = groupKey
    return child
}
/**
 * @param el {Element}
 * @param forOpts {{for: Object, scope: (string|Object), tplFn: Function, root: string, alwaysIterate: bool, observeProp: string }}
 * @param groupKey {number}
 * @param rool {Element}
 */
function for2children(el, forOpts, groupKey, root, stop) {
    var val = forOpts.for
    if (!val) return
    var data = has(forOpts, 'root') ? val[forOpts.root] : val,
        fn = forOpts.tplFn,
        children,
        fnResult,
        child
    if (data && typeof fn === 'function') {
        var thisArg = root
        if (has(forOpts, 'scope')) {
            var scope = opts.scope
            thisArg = scope === 'root' ? root : (scope === 'parent' ? parent : scope)
        }
        if (isArray(data))
            data.forEach(function(d, i) {
                fnResult = fn.call(thisArg, d, i)
                child = makeChild(el, fnResult, root, groupKey)
                if (child)
                    appendChild(el, child, root, stop)
                // return child
            })
        else if (isPlain(data) && forOpts.alwaysIterate) {
            var keys = getKeys(data)
            children = keys.forEach(function (key, i) {
                fnResult = fn.call(thisArg, data[key], key)
                child = makeChild(el, fnResult, root, groupKey)
                if (child)
                    appendChild(el, child, root, stop)
                return child
            })
        }
        else {
            fnResult = fn.call(thisArg, data)
			if (!isArray(fnResult)) {
				fnResult = [fnResult]
            }
            children = fnResult.forEach(function(result, i) {
                child = makeChild(el, result, root, groupKey)
                if (child)
                    appendChild(el, child, root, stop)
                return child
            })
		}
    }
}
/**
 * @param el {Element}
 * @param tplOpts {Object}
 * @param root {Element}
 */
function setChildrenInFor(el, tplOpts, root) {
    var groupKey
    if (has(tplOpts, 'observeProp')) {
        var obsProp = tplOpts.observeProp,
            groupKey = specialKey++
        if (obsProp && isStrOrNum(obsProp) && obsProp !== '__owner') {
            var observer = setObserver(el, tplOpts, groupKey, root)
        }
    }
    for2children(el, tplOpts, groupKey, root)
}
/**
 * @param el {Element}
 * @param children {any}
 * @param root {Element}
 */
function setChildren(el, children, root) {
    if (!children) return
    var child
    if (isPlain(children)) {
        if (has(children, 'ctype')) {
            child = createComponent(children)
            appendChild(el, child, root)
            return
        }
        if (has(children, 'for')) {
            setChildrenInFor(el, children, root)
        }
        else {
            child = object2children(el, children, root)
            appendChild(el, child, root)
        }
        return
    }
    if (isArray(children)) {
        children.forEach(function(ch) {
            setChildren(el, ch, root)
        })
        return
    }
    if (typeof children === 'function') {
        var realChildren = children()
        setChildren(el, realChildren, root)
        return
    }
    if (isDom(children)) {
        appendChild(el, children, root)
    }
    else
        appendChild(el, document.createTextNode(children), root)
}
function setRootChildren(el) {
    var elSetups = el.setups
    if (!elSetups) return
    var children = getChildrenConfigs(el)
    setChildren(el, children, el)
}
/**
 * Define an object { setups: { __configs:Object, __events:[] } on an element
 * @param el {Element}
 */
function createSetupsHolder(el) {
    var setups = createDict()
    defProps(setups, {
        __configs: { value: createDict() },
        __events: { value: [] }
    })
    el.setups = setups
}
/**
 * Entry function, executed only once
 * @param defs {Object} element definitions
 * @returns {Element}
 */
function createElement(defs) {
    var tag = has(defs, 'tag') ? defs.tag : 'div'
    var el = document.createElement(tag)
    defProp(el, 'd__isCmp', { value: true })
    createSetupsHolder(el)
    setDefs(el, defs)
    setAttrs(el)
    setStyles(el)
    setEvents(el, el)
    setCls(el)
    setRootChildren(el)
    var elSetups = el.setups
    if (has(elSetups, 'created') && isFn(elSetups.created)) {
        elSetups.created.call(el, el, el)
    }
    if (has(elSetups, 'parent')) {
        elSetups.parent.appendChild(el)
        if (has(elSetups, 'appended'))
            elSetups.appended.call(el)
    }
    return el
}
/**
 * Entry function, executed only once
 * @param defs {Object} component definitions
 * @return {Element}
 */
function createComponent(defs) {
    var ctype = defs.ctype
    var definitions = Component.get(ctype).create(defs)
    // Carry the reference to the component
    if (has(defs, 'ref')) {
        definitions.ref = defs.ref
        if (has(defs, 'refScope'))
            definitions.refScope = defs.refScope
    }
    else if (has(defs, 'directRef'))
        definitions.directRef = defs.directRef
    if (has(defs, 'hide'))
        definitions.hide = defs.hide
    var comp = createElement(definitions)
    comp.ctype = ctype
    return comp
}
/**
 * API function
 * @param defs {Object} Element definitions
 * @returns {Element}
 */
function create(defs) {
    if (has(defs, 'ctype')) {
        return createComponent(defs)
    }
    else {
        return createElement(defs)
    }
}

export { getDefaults, create, for2children }


text:
package service

import (
	"fmt"
	"io"
	"net"
	"os"
	"strings"

	"github.com/gravitational/teleport/lib/auth"
	"github.com/gravitational/teleport/lib/backend"
	"github.com/gravitational/teleport/lib/backend/boltbk"
	"github.com/gravitational/teleport/lib/defaults"
	"github.com/gravitational/teleport/lib/limiter"
	"github.com/gravitational/teleport/lib/services"
	"github.com/gravitational/teleport/lib/utils"

	log "github.com/Sirupsen/logrus"
	"gopkg.in/yaml.v2"
)

// Config structure is used to initialize _all_ services Teleporot can run.
// Some settings are globl (like DataDir) while others are grouped into
// sections, like AuthConfig
type Config struct {
	// DataDir provides directory where teleport stores it's permanent state
	// (in case of auth server backed by BoltDB) or local state, e.g. keys
	DataDir string

	// Hostname is a node host name
	Hostname string

	// Token is used to register this Teleport instance with the auth server
	Token string

	// AuthServers is a list of auth servers nodes, proxies and peer auth servers
	// connect to
	AuthServers []utils.NetAddr

	// Identities is an optional list of pre-generated key pairs
	// for teleport roles, this is helpful when server is preconfigured
	Identities []*auth.Identity

	// AdvertiseIP is used to "publish" an alternative IP address this node
	// can be reached on, if running behind NAT
	AdvertiseIP net.IP

	// SSH role an SSH endpoint server
	SSH SSHConfig

	// Auth server authentication and authorizatin server config
	Auth AuthConfig

	// Keygen points to a key generator implementation
	Keygen auth.Authority

	// Proxy is SSH proxy that manages incoming and outbound connections
	// via multiple reverse tunnels
	Proxy ProxyConfig

	// HostUUID is a unique UUID of this host (it will be known via this UUID within
	// a teleport cluster). It's automatically generated on 1st start
	HostUUID string

	// Console writer to speak to a user
	Console io.Writer

	// ReverseTunnels is a list of reverse tunnels to create on the
	// first cluster start
	ReverseTunnels []services.ReverseTunnel

	// OIDCConnectors is a list of trusted OpenID Connect identity providers
	OIDCConnectors []services.OIDCConnector

	// PidFile is a full path of the PID file for teleport daemon
	PIDFile string

	// Trust is a service that manages users and credentials
	Trust services.Trust

	// Presence service is a discovery and hearbeat tracker
	Presence services.Presence

	// Provisioner is a service that keeps track of provisioning tokens
	Provisioner services.Provisioner

	// Trust is a service that manages users and credentials
	Identity services.Identity

	// Access is a service that controls access
	Access services.Access

	// SeedConfig tells teleport to treat its start-up configuration as initial
	// "seed" configuration on 1st start.
	SeedConfig bool
}

// ApplyToken assigns a given token to all internal services but only if token
// is not an empty string.
//
// Returns 'true' if token was modified
func (cfg *Config) ApplyToken(token string) bool {
	if token != "" {
		cfg.Token = token
		return true
	}
	return false
}

// RoleConfig is a config for particular Teleport role
func (cfg *Config) RoleConfig() RoleConfig {
	return RoleConfig{
		DataDir:     cfg.DataDir,
		HostUUID:    cfg.HostUUID,
		HostName:    cfg.Hostname,
		AuthServers: cfg.AuthServers,
		Auth:        cfg.Auth,
		Console:     cfg.Console,
	}
}

// DebugDumpToYAML is useful for debugging: it dumps the Config structure into
// a string
func (cfg *Config) DebugDumpToYAML() string {
	shallow := *cfg
	// do not copy sensitive data to stdout
	shallow.Identities = nil
	shallow.Auth.Authorities = nil
	out, err := yaml.Marshal(shallow)
	if err != nil {
		return err.Error()
	}
	return string(out)
}

// ProxyConfig configures proy service
type ProxyConfig struct {
	// Enabled turns proxy role on or off for this process
	Enabled bool

	// DisableWebUI allows to turn off serving the Web UI
	DisableWebUI bool

	// ReverseTunnelListenAddr is address where reverse tunnel dialers connect to
	ReverseTunnelListenAddr utils.NetAddr

	// WebAddr is address for web portal of the proxy
	WebAddr utils.NetAddr

	// SSHAddr is address of ssh proxy
	SSHAddr utils.NetAddr

	// TLSKey is a base64 encoded private key used by web portal
	TLSKey string

	// TLSCert is a base64 encoded certificate used by web portal
	TLSCert string

	Limiter limiter.LimiterConfig
}

// AuthConfig is a configuration of the auth server
type AuthConfig struct {
	// Enabled turns auth role on or off for this process
	Enabled bool

	// SSHAddr is the listening address of SSH tunnel to HTTP service
	SSHAddr utils.NetAddr

	// Authorities is a set of trusted certificate authorities
	// that will be added by this auth server on the first start
	Authorities []services.CertAuthority

	// Roles is a set of roles to pre-provision for this cluster
	Roles []services.Role

	// DomainName is a name that identifies this authority and all
	// host nodes in the cluster that will share this authority domain name
	// as a base name, e.g. if authority domain name is example.com,
	// all nodes in the cluster will have UUIDs in the form: <uuid>.example.com
	DomainName string

	// StaticTokens are pre-defined host provisioning tokens supplied via config file for
	// environments where paranoid security is not needed
	StaticTokens []services.ProvisionToken

	// StorageConfig contains configuration settings for
	// the secrets storage backend
	StorageConfig backend.Config

	Limiter limiter.LimiterConfig

	// NoAudit, when set to true, disables session recording and event audit
	NoAudit bool

	U2F services.U2F
}

// SSHConfig configures SSH server node role
type SSHConfig struct {
	Enabled   bool
	Addr      utils.NetAddr
	Namespace string
	Shell     string
	Limiter   limiter.LimiterConfig
	Labels    map[string]string
	CmdLabels services.CommandLabels
}

// MakeDefaultConfig creates a new Config structure and populates it with defaults
func MakeDefaultConfig() (config *Config) {
	config = &Config{}
	ApplyDefaults(config)
	return config
}

// ApplyDefaults applies default values to the existing config structure
func ApplyDefaults(cfg *Config) {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "localhost"
		log.Errorf("Failed to determine hostname: %v", err)
	}
	cfg.SeedConfig = false

	// global defaults
	cfg.Hostname = hostname
	cfg.DataDir = defaults.DataDir
	cfg.Console = os.Stdout

	// defaults for the auth service:
	cfg.Auth.Enabled = true
	cfg.Auth.SSHAddr = *defaults.AuthListenAddr()
	cfg.Auth.U2F.Enabled = false
	cfg.Auth.U2F.AppID = fmt.Sprintf("https://%s:%d", strings.ToLower(hostname), defaults.HTTPListenPort)
	cfg.Auth.U2F.Facets = []string{cfg.Auth.U2F.AppID}
	cfg.Auth.StorageConfig.Type = boltbk.GetName()
	cfg.Auth.StorageConfig.Params = backend.Params{"path": cfg.DataDir}
	defaults.ConfigureLimiter(&cfg.Auth.Limiter)

	// defaults for the SSH proxy service:
	cfg.Proxy.Enabled = true
	cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr()
	cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr()
	cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr()
	defaults.ConfigureLimiter(&cfg.Proxy.Limiter)

	// defaults for the SSH service:
	cfg.SSH.Enabled = true
	cfg.SSH.Addr = *defaults.SSHServerListenAddr()
	cfg.SSH.Shell = defaults.DefaultShell
	defaults.ConfigureLimiter(&cfg.SSH.Limiter)
}