text:
@extends('../layouts.app')

@section('page-title') {!! trans('reg-profile.my_profile') !!} @endsection
@section('page-class') my-profile @endsection

@section('meta')
  <meta id="token" content="{{ $token }}" />
@endsection

@section ('profile_warning')
@endsection

@section('content')

{!! trans('reg-profile.my_profile') !!}

        getPhoto()) }}" alt="" class="img-responsive" />

{!! trans('reg-profile.profile') !!}

{!! trans('reg-profile.company_contact_person') !!}

{!! trans('reg-profile.change_your_password') !!}

          <form enctype='multipart/form-data'  class="form-vertical" role="form" method="POST" action="{{ route('update_profile'). '#profile' }}" >
              {{ csrf_field() }}

{!! trans('reg-profile.profile_visibility') !!}

                <input type="radio" @if ($user->visible == true) checked @endif name="visible" value="1">{!! trans('reg-profile.profile_visibility_visible') !!}

                <input @if ($user->visible != true) checked @endif type="radio" name="visible" value="0">{!! trans('reg-profile.profile_visibility_hidden') !!}

{!! trans('reg-profile.notifications') !!}

                <input type="radio" @if ($user->notify_me == true) checked @endif name="notify_me" value="1">{!! trans('reg-profile.notifications_enabled') !!}

                <input @if ($user->notify_me != true) checked @endif type="radio" name="notify_me" value="0">{!! trans('reg-profile.notifications_disabled') !!}

{!! trans('reg-profile.about') !!}

              <text-box-form code="name" label="{!! trans('reg-profile.name') !!}" placeholder="{!! trans('reg-profile.name') !!}" value="{{ old('name', $user->name) }}"
                  required errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="fiscal_id" label="{!! trans('reg-profile.fiscal_id') !!}" placeholder="{!! trans('reg-profile.fiscal_id') !!}"
                      value="{{ old('fiscal_id', $company->fiscal_id) }}"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="overseer" label="{!! trans('reg-profile.legal_representative') !!}"
                      placeholder="{!! trans('reg-profile.legal_representative') !!}" value="{{ old('overseer', $company->overseer) }}"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="email" label="{!! trans('reg-profile.email') !!}" placeholder="{!! trans('reg-profile.email') !!}" readonly
                      value="{{ old('email', $user->email) }}"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="phone" label="{!! trans('reg-profile.phone') !!}" placeholder="{!! trans('reg-profile.phone') !!}"
                      value="{{ old('phone', $user->phone) }}"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

              <select-form code="activity" label="{!! trans('reg-profile.company_activity') !!}" placeholder=" - {!! trans('reg-profile.company_activity') !!} - " required
                  values='{!! json_encode($activities, JSON_HEX_APOS) !!}'
                  value="{{ old('activity', $company->activity) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></select-form>

has('image')) alert alert-danger   @endif  ">
                @if ($errors->has('image'))

                    {{ $errors->first('image') }}
                 @endif

                  {!! trans('reg-profile.company_logo') !!}
                  <input type="file" id="image" name="image" accept="image/*">

{!! trans('reg-profile.social_and_web') !!}

              <text-box-form code="facebook" label="{!! trans('reg-profile.facebook_page_url') !!}" placeholder="{!! trans('reg-profile.facebook_page_url') !!}"
                  value="{{ old('facebook', $user->facebook) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>
              <text-box-form code="twitter" label="{!! trans('reg-profile.twitter_page_url') !!}" placeholder="{!! trans('reg-profile.twitter_page_url') !!}"
                  value="{{ old('twitter', $user->twitter) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>
              <text-box-form code="linkedin" label="{!! trans('reg-profile.linkedin_page_url') !!}" placeholder="{!! trans('reg-profile.linkedin_page_url') !!}"
                  value="{{ old('linkedin', $user->linkedin) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>
              <text-box-form code="website" label="{!! trans('reg-profile.web_url') !!}" placeholder="{!! trans('reg-profile.web_url') !!}"
                  value="{{ old('website', $company->website) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

{!! trans('reg-profile.address') !!}

              <text-box-form code="address" label="{!! trans('reg-profile.address') !!}" placeholder="{!! trans('reg-profile.address') !!}"
                  value="{{ old('address', $user->address) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="postal_code" label="{!! trans('reg-profile.postal_code') !!}" placeholder="{!! trans('reg-profile.postal_code') !!}"
                      value="{{ old('postal_code', $user->postal_code) }}" minlength="3"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

                  <text-box-form code="city" label="{!! trans('reg-profile.city') !!}" placeholder="{!! trans('reg-profile.city') !!}"
                      required value="{{ old('city', $user->city) }}"
                      errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

              <select-form code="country" label="{!! trans('reg-profile.country') !!}" placeholder=" - {!! trans('reg-profile.country') !!} - " required
                  values='{!! json_encode($countries, JSON_HEX_APOS) !!}' value="{{ old('country', $user->country) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></select-form>

              <text-area-form code="description" label="{!! trans('reg-profile.description') !!} ({!! trans('reg-profile.input_max_characters') !!} 300 characters)"
                  placeholder="{!! trans('reg-profile.description') !!} ({!! trans('reg-profile.input_max_characters') !!} 300)."
                  value="{{ old('description', $company->description) }}" errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-area-form>

              <text-area-form code="talent" label="{!! trans('reg-profile.company_what_is_talent') !!} ({!! trans('reg-profile.input_max_characters') !!} 300 characters)"
                  placeholder="{!! trans('reg-profile.what_is_talent_for_you_in_a_few_words') !!} ({!! trans('reg-profile.input_max_characters') !!} 300)." required
                  value="{{ old('talent', $company->talent) }}" errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-area-form>

              <personal-skills-form label="{!! trans('reg-profile.student_personal_skills') !!} ({!! trans('reg-profile.input_max_characters') !!} 6)"
                  sublabel="{!! trans('reg-profile.most_valuable_skills_for_company') !!}"
                  values='{!! json_encode($personalSkills, JSON_HEX_APOS) !!}'
                  value='{!! json_encode($company->personalSkills, JSON_HEX_APOS) !!}'
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></personal-skills-form>

                <button type="submit" class="btn btn-primary">{!! trans('reg-profile.update_settings') !!}</button>
                <remove-account></remove-account>

            </form>

{!! trans('reg-profile.company_contact_person') !!}

            {!! trans('reg-profile.setup_alternative_contact') !!}
            <form class="form-vertical" role="form" method="POST" action="{{ route('update_profile'). '#contact' }}" >
              {{ csrf_field() }}
              <text-box-form code="notification_name" label="{!! trans('reg-profile.name') !!}" placeholder="{!! trans('reg-profile.name') !!}"
                  value="{{ old('notification_name', $company->notification_name) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>
              <text-box-form type="email" code="notification_email" label="{!! trans('reg-profile.email') !!}" placeholder="{!! trans('reg-profile.email') !!}"
                  value="{{ old('notification_email', $company->notification_email) }}"
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

              <button type="submit" class="btn btn-primary">{!! trans('reg-profile.update_settings') !!}</button>
            </form>

{!! trans('reg-profile.change_your_password') !!}

            <form class="form-vertical" role="form" method="POST" action="{{ route('update_profile'). '#change-password' }}">
              {{ csrf_field() }}
              <text-box-form type="password" code="password" label="{!! trans('reg-profile.new_password') !!}"
                  required placeholder="{!! trans('reg-profile.new_password') !!}" value="" no-validate
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>
              <text-box-form type="password" code="password_confirm" label="{!! trans('reg-profile.repeat_new_password') !!}"
                  required placeholder="{!! trans('reg-profile.repeat_new_password') !!}" value="" no-validate
                  errors='{!! json_encode($errors->toArray(), JSON_HEX_APOS) !!}'></text-box-form>

              <button type="submit" class="btn btn-primary">{!! trans('reg-profile.save_new_password') !!}</button>
            </form>

@endsection


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Datamodel;

namespace DmxPad
{
    public partial class AttributePanel : UserControl
    {
        public AttributePanel()
        {
            InitializeComponent();
        }

        public System.IO.FileInfo File
        {
            get { return (System.IO.FileInfo)GetValue(FileProperty); }
            set { SetValue(FileProperty, value); }
        }
        public static readonly DependencyProperty FileProperty =
            DependencyProperty.Register("File", typeof(System.IO.FileInfo), typeof(AttributePanel), new PropertyMetadata(null));

        public object Selected
        {
            get { return (object)GetValue(SelectedProperty); }
            set { SetValue(SelectedProperty, value); }
        }
        public static readonly DependencyProperty SelectedProperty =
            DependencyProperty.Register("Selected", typeof(object), typeof(AttributePanel), new PropertyMetadata(null));

        private void GUIDCopy_Click(object sender, RoutedEventArgs e)
        {
            var elem = ((Element)((Hyperlink)sender).CommandParameter);
            System.Windows.Clipboard.SetText(elem.ID.ToString());
            e.Handled = true;
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            var attr = ((Button)sender).DataContext as AttributeView;
            if (attr != null)
                attr.Owner.Remove(attr.Key);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function($) {

    var Alpaca = $.alpaca;

    Alpaca.Fields.GridField = Alpaca.Fields.ArrayField.extend(
    /**
     * @lends Alpaca.Fields.GridField.prototype
     */
    {
        /**
         * @see Alpaca.ControlField#getFieldType
         */
        getFieldType: function() {
            return "grid";
        },

        setup: function()
        {
            this.base();

            if (typeof(this.options.grid) == "undefined")
            {
                this.options.grid = {};
            }
        },

        afterRenderContainer: function(model, callback)
        {
            var self = this;

            this.base(model, function() {

                // convert the data array into the grid's expected format
                var gridData = [];

                // add in headers
                var headers = [];
                for (var key in self.options.fields)
                {
                    var fieldDefinition = self.options.fields[key];

                    var label = key;
                    if (fieldDefinition.label)
                    {
                        label = fieldDefinition.label;
                    }

                    headers.push(label);
                }
                gridData.push(headers);

                for (var i = 0; i < self.data.length; i++)
                {
                    var row = [];
                    for (var key2 in self.data[i])
                    {
                        row.push(self.data[i][key2]);
                    }
                    gridData.push(row);
                }

                /*
                // TODO
                var gridData = [
                    ["Maserati", "Mazda", "Mercedes", "Mini", "Mitsubishi"],
                    ["2009", 0, 2941, 4303, 354, 5814],
                    ["2010", 5, 2905, 2867, 412, 5284],
                    ["2011", 4, 2517, 4822, 552, 6127],
                    ["2012", 2, 2422, 5399, 776, 4151]
                ];
                */

                var holder = $(self.container).find(".alpaca-container-grid-holder");

                var gridConfig = self.options.grid;
                gridConfig.data = gridData;

                $(holder).handsontable(gridConfig);

                callback();
            });
        },

        /**
         * @see Alpaca.ControlField#getType
         */
        getType: function() {
            return "array";
        }

        /* builder_helpers */
        ,

        /**
         * @see Alpaca.ControlField#getTitle
         */
        getTitle: function() {
            return "Grid Field";
        },

        /**
         * @see Alpaca.ControlField#getDescription
         */
        getDescription: function() {
            return "Renders array items into a grid";
        }

        /* end_builder_helpers */
    });

    Alpaca.registerFieldClass("grid", Alpaca.Fields.GridField);

})(jQuery);


text:
define(['knockout', 'jquery'], function (ko, $) {

	ko.bindingHandlers.contentEditable = {
		init: function (element, valueAccessor, allBindingsAccessor) {
			element.contentEditable = true;
			var value = ko.unwrap(valueAccessor());

			$(element).on("input", function () {
				if (ko.isWriteableObservable(valueAccessor())) {
					valueAccessor()(this.innerText);
				}
			});
		},
		update: function (element, valueAccessor) {
			var value = ko.unwrap(valueAccessor());

			if (!$(element).is(':focus')) {
				element.innerText = value;
			}
		}
	};
});


text:
@interface PodsDummy_TLTabBarController : NSObject
@end
@implementation PodsDummy_TLTabBarController
@end


text:
package main

import (
	"time"

	log "github.com/inconshreveable/log15"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/lib/crypto/trc"
	"github.com/scionproto/scion/go/lib/ctrl"
	"github.com/scionproto/scion/go/lib/ctrl/cert_mgmt"
	"github.com/scionproto/scion/go/lib/snet"
)

var (
	// trcReqCache is an expiring cache for pending requests of TRCs.
	trcReqCache = NewReqCache(30*time.Second, 10*time.Minute, 1*time.Second)
)

type TRCHandler struct {
	conn *snet.Conn
}

func NewTRCHandler(conn *snet.Conn) *TRCHandler {
	return &TRCHandler{conn: conn}
}

// HandleReq handles TRC requests. If the TRC is not already cached and the cache-only flag is set
// or the requester is from a remote AS, the request is dropped.
func (h *TRCHandler) HandleReq(addr *snet.Addr, req *cert_mgmt.TRCReq) {
	log.Info("Received TRC request", "addr", addr, "req", req)
	var t *trc.TRC
	if req.Version == cert_mgmt.NewestVersion {
		t = config.Store.GetNewestTRC(req.ISD)
	} else {
		t = config.Store.GetTRC(req.ISD, req.Version)
	}
	srcLocal := config.PublicAddr.IA.Eq(addr.IA)
	if t != nil {
		if err := h.sendTRCRep(addr, t); err != nil {
			log.Error("Unable to send TRC reply", "addr", addr, "req", req, "err", err)
		}
	} else if !srcLocal || req.CacheOnly {
		log.Info("Dropping TRC requeset", "addr", addr, "req", req, "err", "TRC not found")
	} else {
		if err := h.fetchTRC(addr, req); err != nil {
			log.Error("Unable to fetch TRC", "req", req, "err", err)
		}
	}
}

// sendTRCRep creates a TRC response and sends it to the requester.
func (h *TRCHandler) sendTRCRep(addr *snet.Addr, t *trc.TRC) error {
	raw, err := t.Compress()
	if err != nil {
		return err
	}
	cpld, err := ctrl.NewCertMgmtPld(&cert_mgmt.TRC{RawTRC: raw}, nil, nil)
	if err != nil {
		return err
	}
	log.Debug("Send TRC reply", "trc", t, "addr", addr)
	return SendPayload(h.conn, cpld, addr)
}

// fetchTRC fetches a TRC from the remote AS.
func (h *TRCHandler) fetchTRC(addr *snet.Addr, req *cert_mgmt.TRCReq) error {
	key := trc.NewKey(req.ISD, req.Version).String()
	sendReq := trcReqCache.Put(key, addr)
	if sendReq { // rate limit
		return h.sendTRCReq(req)
	}
	log.Info("Ignoring TRC request (same request already pending)", "addr", addr, "req", req)
	return nil
}

// sendTRCReq sends a TRC request to the specified remote AS.
func (h *TRCHandler) sendTRCReq(req *cert_mgmt.TRCReq) error {
	cpld, err := ctrl.NewCertMgmtPld(req, nil, nil)
	if err != nil {
		return err
	}
	pathSet := snet.DefNetwork.PathResolver().Query(config.PublicAddr.IA, req.IA())
	path := pathSet.GetAppPath("")
	if path == nil {
		return common.NewBasicError("Unable to find core AS", nil)
	}
	a := &snet.Addr{IA: path.Entry.Path.DstIA(), Host: addr.SvcCS}
	log.Debug("Send TRC request", "req", req, "addr", a)
	return SendPayload(h.conn, cpld, a)
}

// HandleRep handles TRC replies. Pending requests are answered and removed.
func (h *TRCHandler) HandleRep(addr *snet.Addr, rep *cert_mgmt.TRC) {
	log.Info("Received TRC reply", "addr", addr, "rep", rep)
	t, err := rep.TRC()
	if err != nil {
		log.Error("Unable to parse TRC reply", "err", err)
		return
	}
	if err = config.Store.AddTRC(t, true); err != nil {
		log.Error("Unable to store TRC", "key", t.Key(), "err", err)
		return
	}
	key := t.Key()
	reqVer := chainReqCache.Pop(key.String())
	key.Ver = cert_mgmt.NewestVersion
	reqNew := chainReqCache.Pop(key.String())
	key.Ver = t.Version
	if reqVer == nil && reqNew == nil { // No pending requests
		return
	}
	cpld, err := ctrl.NewCertMgmtPld(rep, nil, nil)
	if err != nil {
		log.Error("Unable to create TRC reply", "key", t.Key(), "err", err)
		return
	}
	h.answerReqs(reqVer, cpld, key)
	h.answerReqs(reqNew, cpld, key)
}

// answerReqs responds to pending requests.
func (h *TRCHandler) answerReqs(reqs *AddrSet, cpld *ctrl.Pld, key *trc.Key) {
	if reqs == nil {
		return
	}
	for _, dst := range reqs.Addrs {
		if err := SendPayload(h.conn, cpld, dst); err != nil {
			log.Error("Unable to write TRC reply", "key", key, "err", err)
			continue
		}
	}
}


text:
/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
  "use strict";

  var fs = require('fs')
    , path = require('path')
    ;

  fs.exists = fs.exists || path.exists;

  function rfind(fullpath, next) {
    fs.exists(fullpath, function (exists) {
      var fullpathArr
        , filename
        ;

      if (exists) {
        next(null, fullpath);
        return;
      }

      fullpathArr = fullpath.split(path.sep);
      filename = fullpathArr.pop();
      fullpathArr.pop();

      if (!fullpathArr.length) {
        next(new Error('Not Found'));
        return;
      }

      fullpath = path.join(fullpathArr.join(path.sep), filename);
      rfind(fullpath, next);
    });
  }

  function rfindHelper(fullpath, cb) {
    fullpath = path.normalize(path.resolve(process.cwd(), fullpath));
    rfind(fullpath, cb || function () {});
  }

  if (require.main === module) {
    rfindHelper(process.argv[2], function (err, pathname) {
      if (err) {
        console.error('couldn\'t find ' + process.argv[2]);
        return;
      }
      console.log(pathname);
    });
  }
}());


text:
package com.hea3ven.tools.commonutils.util;

import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.util.DefaultedList;

public class InventoryExtraUtil {

    public static void serialize(CompoundTag tag, DefaultedList<ItemStack> inventory,
            String tagName) {
        ListTag list = new ListTag();
        for (int i = 0; i < inventory.size(); i++) {
            ItemStack stack = inventory.get(i);
            if (!stack.isEmpty()) {
                CompoundTag slotTag = new CompoundTag();
                slotTag.putByte("Slot", (byte) i);
                stack.toTag(slotTag);
                list.add(slotTag);
            }
        }
        tag.put(tagName, list);
    }

    public static void deserialize(CompoundTag tag, DefaultedList<ItemStack> inventory,
            String tagName) {
        ListTag list = tag.getList(tagName, 10);
        for (int i = 0; i < list.size(); i++) {
            CompoundTag slotTag = list.getCompound(i);
            int slot = slotTag.getByte("Slot");
            if (slot >= 0 && slot < inventory.size()) {
                inventory.set(slot, ItemStack.fromTag(slotTag));
            }
        }
    }
}


text:
ActionController::Base.session = {
  :key         => '_railsapp_session',
  :secret      => 'd2afa759e50e524cd416a5474b020368c02ce4a6435c01224796a3471738f0e35dce8386d79cfdb46323a0e08775dcd3be8ba4d2a94e61ac344f36d3dd92feb1'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store


text:
<?php

/* @var $this CiesController */
/* @var $estado Estado */
/* @var $mdCies Cies */

$uf = strtolower($estado->uf);
$action = ['cies/adiciona'];
$nomeBotao = 'Salvar CIES';
?>

    	Nova CIES

        <?php $form = $this->beginWidget('CActiveForm', array('action' => $action)); ?>
        <?php echo $form->hiddenField($mdCies, 'estado_uf', ['value' => $uf]); ?>
        <?php $labels = $mdCies->attributeLabels(); ?>

        <?php if ($this->user->hasFlash('cies.erro')) : ?>

		    	<button type="button" class="close"
		        	data-dismiss="alert" aria-label="Fechar">×
				</button>
		        <?php echo $this->user->getFlash('cies.erro'); ?>

		<?php endif; ?>
        <div class="form-group <?php echo $mdCies->hasErrors('nome') ? 'has-error' : ''; ?>">

            	<?php
                echo $form->label($mdCies, 'nome', [
                	'class' => 'input-group-addon',
                    'label' => '',
                ]);

                echo $form->textField($mdCies, 'nome', [
                	'class' => 'form-control',
                    'placeholder' => $labels['nome'],
                	'title' => $labels['nome'],
                	'data-toggle' => 'tooltip'
                ]);
                ?>

            <?php echo $form->error($mdCies, 'nome', ['class' => 'help-block']); ?>

            <?php $icobtn = CHtml::tag('i', ['class' => 'fa fa-plus-circle fa-fw'], ''); ?>
            <?php echo CHtml::tag('button', ['type' => 'submit', 'class' => 'btn btn-primary'],
                    "{$icobtn} Adicionar"); ?>

        <?php $this->endWidget(); ?>


text:
package org.apache.vxquery.serializer;

import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.vxquery.datamodel.accessors.PointablePool;
import org.apache.vxquery.datamodel.accessors.PointablePoolFactory;
import org.apache.vxquery.datamodel.accessors.SequencePointable;
import org.apache.vxquery.datamodel.accessors.TaggedValuePointable;
import org.apache.vxquery.datamodel.accessors.atomic.CodedQNamePointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSBinaryPointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSDatePointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSDateTimePointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSDecimalPointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSDurationPointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSQNamePointable;
import org.apache.vxquery.datamodel.accessors.atomic.XSTimePointable;
import org.apache.vxquery.datamodel.accessors.jsonitem.ArrayPointable;
import org.apache.vxquery.datamodel.accessors.jsonitem.ObjectPointable;
import org.apache.vxquery.datamodel.accessors.nodes.AttributeNodePointable;
import org.apache.vxquery.datamodel.accessors.nodes.DocumentNodePointable;
import org.apache.vxquery.datamodel.accessors.nodes.ElementNodePointable;
import org.apache.vxquery.datamodel.accessors.nodes.NodeTreePointable;
import org.apache.vxquery.datamodel.accessors.nodes.PINodePointable;
import org.apache.vxquery.datamodel.accessors.nodes.TextOrCommentNodePointable;
import org.apache.vxquery.datamodel.values.ValueTag;
import org.apache.vxquery.exceptions.SystemException;
import org.apache.vxquery.runtime.functions.cast.CastToStringOperation;

import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.data.IPrinter;
import org.apache.hyracks.data.std.primitive.BooleanPointable;
import org.apache.hyracks.data.std.primitive.BytePointable;
import org.apache.hyracks.data.std.primitive.DoublePointable;
import org.apache.hyracks.data.std.primitive.FloatPointable;
import org.apache.hyracks.data.std.primitive.IntegerPointable;
import org.apache.hyracks.data.std.primitive.LongPointable;
import org.apache.hyracks.data.std.primitive.ShortPointable;
import org.apache.hyracks.data.std.primitive.UTF8StringPointable;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;

public class XMLSerializer implements IPrinter {
    private final PointablePool pp;

    private NodeTreePointable ntp;

    private ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
    private DataOutput dOut = abvs.getDataOutput();
    private CastToStringOperation castToString = new CastToStringOperation();

    public XMLSerializer() {
        pp = PointablePoolFactory.INSTANCE.createPointablePool();
    }

    @Override
    public void print(byte[] b, int s, int l, PrintStream ps) {
        TaggedValuePointable tvp = pp.takeOne(TaggedValuePointable.class);
        try {
            tvp.set(b, s, l);
            printTaggedValuePointable(ps, tvp);
        } finally {
            pp.giveBack(tvp);
        }
    }

    public void printTaggedValuePointable(PrintStream ps, TaggedValuePointable tvp) {
        byte tag = tvp.getTag();
        switch ((int) tag) {
            case ValueTag.XS_ANY_URI_TAG:
                printString(ps, tvp);
                break;

            case ValueTag.XS_BASE64_BINARY_TAG:
                printBase64Binary(ps, tvp);
                break;

            case ValueTag.XS_BOOLEAN_TAG:
                printBoolean(ps, tvp);
                break;

            case ValueTag.XS_DATE_TAG:
                printDate(ps, tvp);
                break;

            case ValueTag.XS_DATETIME_TAG:
                printDateTime(ps, tvp);
                break;

            case ValueTag.XS_DAY_TIME_DURATION_TAG:
                printDTDuration(ps, tvp);
                break;

            case ValueTag.XS_BYTE_TAG:
                printByte(ps, tvp);
                break;

            case ValueTag.XS_DECIMAL_TAG:
                printDecimal(ps, tvp);
                break;

            case ValueTag.XS_DOUBLE_TAG:
                printDouble(ps, tvp);
                break;

            case ValueTag.XS_DURATION_TAG:
                printDuration(ps, tvp);
                break;

            case ValueTag.XS_FLOAT_TAG:
                printFloat(ps, tvp);
                break;

            case ValueTag.XS_G_DAY_TAG:
                printGDay(ps, tvp);
                break;

            case ValueTag.XS_G_MONTH_TAG:
                printGMonth(ps, tvp);
                break;

            case ValueTag.XS_G_MONTH_DAY_TAG:
                printGMonthDay(ps, tvp);
                break;

            case ValueTag.XS_G_YEAR_TAG:
                printGYear(ps, tvp);
                break;

            case ValueTag.XS_G_YEAR_MONTH_TAG:
                printGYearMonth(ps, tvp);
                break;

            case ValueTag.XS_HEX_BINARY_TAG:
                printHexBinary(ps, tvp);
                break;

            case ValueTag.XS_INT_TAG:
            case ValueTag.XS_UNSIGNED_SHORT_TAG:
                printInt(ps, tvp);
                break;

            case ValueTag.XS_INTEGER_TAG:
            case ValueTag.XS_LONG_TAG:
            case ValueTag.XS_NEGATIVE_INTEGER_TAG:
            case ValueTag.XS_NON_POSITIVE_INTEGER_TAG:
            case ValueTag.XS_NON_NEGATIVE_INTEGER_TAG:
            case ValueTag.XS_POSITIVE_INTEGER_TAG:
            case ValueTag.XS_UNSIGNED_INT_TAG:
            case ValueTag.XS_UNSIGNED_LONG_TAG:
                printInteger(ps, tvp);
                break;

            case ValueTag.XS_NOTATION_TAG:
                printString(ps, tvp);
                break;

            case ValueTag.XS_QNAME_TAG:
                printQName(ps, tvp);
                break;

            case ValueTag.XS_SHORT_TAG:
            case ValueTag.XS_UNSIGNED_BYTE_TAG:
                printShort(ps, tvp);
                break;

            case ValueTag.XS_STRING_TAG:
            case ValueTag.XS_NORMALIZED_STRING_TAG:
            case ValueTag.XS_TOKEN_TAG:
            case ValueTag.XS_LANGUAGE_TAG:
            case ValueTag.XS_NMTOKEN_TAG:
            case ValueTag.XS_NAME_TAG:
            case ValueTag.XS_NCNAME_TAG:
            case ValueTag.XS_ID_TAG:
            case ValueTag.XS_IDREF_TAG:
            case ValueTag.XS_ENTITY_TAG:
                printString(ps, tvp);
                break;

            case ValueTag.XS_TIME_TAG:
                printTime(ps, tvp);
                break;

            case ValueTag.XS_UNTYPED_ATOMIC_TAG:
                printString(ps, tvp);
                break;

            case ValueTag.XS_YEAR_MONTH_DURATION_TAG:
                printYMDuration(ps, tvp);
                break;

            case ValueTag.SEQUENCE_TAG:
                printSequence(ps, tvp);
                break;

            case ValueTag.NODE_TREE_TAG:
                printNodeTree(ps, tvp);
                break;

            case ValueTag.DOCUMENT_NODE_TAG:
                printDocumentNode(ps, tvp);
                break;

            case ValueTag.ELEMENT_NODE_TAG:
                printElementNode(ps, tvp);
                break;

            case ValueTag.ARRAY_TAG:
                printArray(ps, tvp);
                break;

            case ValueTag.ATTRIBUTE_NODE_TAG:
                printAttributeNode(ps, tvp);
                break;

            case ValueTag.TEXT_NODE_TAG:
                printTextNode(ps, tvp);
                break;

            case ValueTag.COMMENT_NODE_TAG:
                printCommentNode(ps, tvp);
                break;

            case ValueTag.PI_NODE_TAG:
                printPINode(ps, tvp);
                break;

            case ValueTag.OBJECT_TAG:
                printObject(ps, tvp);
                break;

            case ValueTag.JS_NULL_TAG:
                printNull(ps, tvp);
                break;
            default:
                throw new UnsupportedOperationException("Encountered tag: " + tvp.getTag());
        }
    }

    private void printNull(PrintStream ps, TaggedValuePointable tvp) {
        ps.append("null");
    }

    private void printDecimal(PrintStream ps, TaggedValuePointable tvp) {
        XSDecimalPointable dp = pp.takeOne(XSDecimalPointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertDecimal(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printNodeTree(PrintStream ps, TaggedValuePointable tvp) {
        if (ntp != null) {
            throw new IllegalStateException("Nested NodeTreePointable found");
        }
        ntp = pp.takeOne(NodeTreePointable.class);
        TaggedValuePointable rootTVP = pp.takeOne(TaggedValuePointable.class);
        try {
            tvp.getValue(ntp);
            ntp.getRootNode(rootTVP);
            printTaggedValuePointable(ps, rootTVP);
        } finally {
            pp.giveBack(rootTVP);
            pp.giveBack(ntp);
            ntp = null;
        }
    }

    private void printPINode(PrintStream ps, TaggedValuePointable tvp) {
        PINodePointable pnp = pp.takeOne(PINodePointable.class);
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        try {
            tvp.getValue(pnp);
            ps.append("<?");
            pnp.getTarget(ntp, utf8sp);
            printString(ps, utf8sp);
            ps.append(' ');
            pnp.getContent(ntp, utf8sp);
            printString(ps, utf8sp);
            ps.append("?>");
        } finally {
            pp.giveBack(pnp);
            pp.giveBack(utf8sp);
        }
    }

    private void printCommentNode(PrintStream ps, TaggedValuePointable tvp) {
        TextOrCommentNodePointable tcnp = pp.takeOne(TextOrCommentNodePointable.class);
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        try {
            tvp.getValue(tcnp);
            tcnp.getValue(ntp, utf8sp);
            ps.append("<!--");
            printString(ps, utf8sp);
            ps.append("-->");
        } finally {
            pp.giveBack(tcnp);
            pp.giveBack(utf8sp);
        }
    }

    private void printTextNode(PrintStream ps, TaggedValuePointable tvp) {
        TextOrCommentNodePointable tcnp = pp.takeOne(TextOrCommentNodePointable.class);
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        try {
            tvp.getValue(tcnp);
            tcnp.getValue(ntp, utf8sp);
            printString(ps, utf8sp);
        } finally {
            pp.giveBack(tcnp);
            pp.giveBack(utf8sp);
        }
    }

    private void printAttributeNode(PrintStream ps, TaggedValuePointable tvp) {
        AttributeNodePointable anp = pp.takeOne(AttributeNodePointable.class);
        CodedQNamePointable cqp = pp.takeOne(CodedQNamePointable.class);
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        TaggedValuePointable valueTVP = pp.takeOne(TaggedValuePointable.class);
        try {
            tvp.getValue(anp);
            anp.getName(cqp);
            printPrefixedQName(ps, cqp, utf8sp);
            ps.append("=\"");
            anp.getValue(ntp, valueTVP);
            printTaggedValuePointable(ps, valueTVP);
            ps.append('"');
        } finally {
            pp.giveBack(valueTVP);
            pp.giveBack(utf8sp);
            pp.giveBack(anp);
            pp.giveBack(cqp);
        }
    }

    private void printObject(PrintStream ps, TaggedValuePointable tvp) {
        ObjectPointable op = pp.takeOne(ObjectPointable.class);
        TaggedValuePointable keys = pp.takeOne(TaggedValuePointable.class);
        tvp.getValue(op);
        try {
            op.getKeys(keys);
            ps.append('{');
            if (keys.getTag() == ValueTag.SEQUENCE_TAG) {
                printObjectPairs(ps, keys, op);
            } else {
                printObjectPair(ps, keys, op);
            }
            ps.append('}');
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(keys);
            pp.giveBack(op);
        }
    }

    private void printObjectPairs(PrintStream ps, TaggedValuePointable keys, ObjectPointable op) {
        SequencePointable seqp = pp.takeOne(SequencePointable.class);
        TaggedValuePointable tvp = pp.takeOne(TaggedValuePointable.class);
        try {
            keys.getValue(seqp);
            int len = seqp.getEntryCount();
            for (int i = 0; i < len; i++) {
                seqp.getEntry(i, tvp);
                printObjectPair(ps, tvp, op);
                if (i != len - 1) {
                    ps.append(',');
                }
            }
        } finally {
            pp.giveBack(seqp);
            pp.giveBack(tvp);
        }
    }

    private void printObjectPair(PrintStream ps, TaggedValuePointable key, ObjectPointable op) {
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        TaggedValuePointable tvp = pp.takeOne(TaggedValuePointable.class);
        try {
            printQuotedTaggedValuePointable(ps, key);
            key.getValue(utf8sp);
            ps.append(":");
            op.getValue(utf8sp, tvp);
            printJsonValue(ps, tvp);
        } finally {
            pp.giveBack(tvp);
            pp.giveBack(utf8sp);
        }
    }

    private void printArray(PrintStream ps, TaggedValuePointable tvp) {
        ArrayPointable ap = pp.takeOne(ArrayPointable.class);
        try {
            tvp.getValue(ap);
            int len = ap.getEntryCount();
            ps.append('[');
            for (int i = 0; i < len; i++) {
                ap.getEntry(i, tvp);
                printJsonValue(ps, tvp);
                if (i != len - 1) {
                    ps.append(',');
                }
            }
            ps.append(']');
        } finally {
            pp.giveBack(ap);
        }
    }

    private void printJsonValue(PrintStream ps, TaggedValuePointable tvp) {
        int tag = tvp.getTag();
        switch (tag) {
            case ValueTag.ARRAY_TAG:
            case ValueTag.ATTRIBUTE_NODE_TAG:
            case ValueTag.COMMENT_NODE_TAG:
            case ValueTag.DOCUMENT_NODE_TAG:
            case ValueTag.ELEMENT_NODE_TAG:
            case ValueTag.JS_NULL_TAG:
            case ValueTag.NODE_TREE_TAG:
            case ValueTag.OBJECT_TAG:
            case ValueTag.PI_NODE_TAG:
            case ValueTag.TEXT_NODE_TAG:
            case ValueTag.XS_BOOLEAN_TAG:
            case ValueTag.XS_BYTE_TAG:
            case ValueTag.XS_DECIMAL_TAG:
            case ValueTag.XS_DOUBLE_TAG:
            case ValueTag.XS_FLOAT_TAG:
            case ValueTag.XS_INT_TAG:
            case ValueTag.XS_INTEGER_TAG:
            case ValueTag.XS_LONG_TAG:
            case ValueTag.XS_NEGATIVE_INTEGER_TAG:
            case ValueTag.XS_NON_NEGATIVE_INTEGER_TAG:
            case ValueTag.XS_NON_POSITIVE_INTEGER_TAG:
            case ValueTag.XS_POSITIVE_INTEGER_TAG:
            case ValueTag.XS_SHORT_TAG:
            case ValueTag.XS_UNSIGNED_BYTE_TAG:
            case ValueTag.XS_UNSIGNED_INT_TAG:
            case ValueTag.XS_UNSIGNED_LONG_TAG:
            case ValueTag.XS_UNSIGNED_SHORT_TAG:
                printTaggedValuePointable(ps, tvp);
                break;
            default:
                printQuotedTaggedValuePointable(ps, tvp);
        }
    }

    private void printQuotedTaggedValuePointable(PrintStream ps, TaggedValuePointable tvp) {
        ps.append('\"');
        printTaggedValuePointable(ps, tvp);
        ps.append('\"');
    }

    private void printElementNode(PrintStream ps, TaggedValuePointable tvp) {
        ElementNodePointable enp = pp.takeOne(ElementNodePointable.class);
        CodedQNamePointable cqp = pp.takeOne(CodedQNamePointable.class);
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        SequencePointable seqp = pp.takeOne(SequencePointable.class);
        try {
            tvp.getValue(enp);
            enp.getName(cqp);
            ps.append('<');
            printPrefixedQName(ps, cqp, utf8sp);

            int nsCount = enp.getNamespaceEntryCount(ntp);
            for (int i = 0; i < nsCount; ++i) {
                ps.append(" xmlns:");
                ntp.getString(enp.getNamespacePrefixCode(ntp, i), utf8sp);
                printString(ps, utf8sp);
                ps.append("=\"");
                ntp.getString(enp.getNamespaceURICode(ntp, i), utf8sp);
                printString(ps, utf8sp);
                ps.append("\"");
            }

            enp.getAttributeSequence(ntp, seqp);
            if (seqp.getByteArray() != null && seqp.getEntryCount() > 0) {
                ps.append(' ');
                printSequence(ps, seqp, " ");
            }

            enp.getChildrenSequence(ntp, seqp);
            if (seqp.getByteArray() != null) {
                ps.append('>');
                printSequence(ps, seqp);
                ps.append("</");
                printPrefixedQName(ps, cqp, utf8sp);
                ps.append('>');
            } else {
                ps.append("/>");
            }
        } finally {
            pp.giveBack(seqp);
            pp.giveBack(utf8sp);
            pp.giveBack(cqp);
            pp.giveBack(enp);
        }
    }

    private void printPrefixedQName(PrintStream ps, CodedQNamePointable cqp, UTF8StringPointable utf8sp) {
        ntp.getString(cqp.getPrefixCode(), utf8sp);
        if (utf8sp.getStringLength() > 0) {
            printString(ps, utf8sp);
            ps.append(':');
        }
        ntp.getString(cqp.getLocalCode(), utf8sp);
        printString(ps, utf8sp);
    }

    private void printDocumentNode(PrintStream ps, TaggedValuePointable tvp) {
        DocumentNodePointable dnp = pp.takeOne(DocumentNodePointable.class);
        SequencePointable seqp = pp.takeOne(SequencePointable.class);
        try {
            ps.append("<?xml version=\"1.0\"?>\n");
            tvp.getValue(dnp);
            dnp.getContent(ntp, seqp);
            printSequence(ps, seqp);
        } finally {
            pp.giveBack(seqp);
            pp.giveBack(dnp);
        }
    }

    private void printSequence(PrintStream ps, TaggedValuePointable tvp) {
        SequencePointable seqp = pp.takeOne(SequencePointable.class);
        try {
            tvp.getValue(seqp);
            printSequence(ps, seqp);
        } finally {
            pp.giveBack(seqp);
        }
    }

    private void printSequence(PrintStream ps, SequencePointable seqp) {
        printSequence(ps, seqp, null);
    }

    private void printSequence(PrintStream ps, SequencePointable seqp, String between) {
        VoidPointable vp = pp.takeOne(VoidPointable.class);
        try {
            int len = seqp.getEntryCount();
            for (int i = 0; i < len; ++i) {
                seqp.getEntry(i, vp);
                print(vp.getByteArray(), vp.getStartOffset(), vp.getLength(), ps);
                if (i < len - 1 && between != null) {
                    ps.append(between);
                }
            }
        } finally {
            pp.giveBack(vp);
        }
    }

    private void printBase64Binary(PrintStream ps, TaggedValuePointable tvp) {
        XSBinaryPointable bp = pp.takeOne(XSBinaryPointable.class);
        try {
            tvp.getValue(bp);
            abvs.reset();
            castToString.convertBase64Binary(bp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(bp);
        }
    }

    private void printBoolean(PrintStream ps, TaggedValuePointable tvp) {
        BooleanPointable bp = pp.takeOne(BooleanPointable.class);
        try {
            tvp.getValue(bp);
            ps.print(bp.getBoolean());
        } finally {
            pp.giveBack(bp);
        }
    }

    private void printByte(PrintStream ps, TaggedValuePointable tvp) {
        BytePointable bp = pp.takeOne(BytePointable.class);
        try {
            tvp.getValue(bp);
            ps.print(bp.byteValue());
        } finally {
            pp.giveBack(bp);
        }
    }

    private void printDouble(PrintStream ps, TaggedValuePointable tvp) {
        DoublePointable dp = pp.takeOne(DoublePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertDouble(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printDate(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertDate(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printDateTime(PrintStream ps, TaggedValuePointable tvp) {
        XSDateTimePointable dtp = pp.takeOne(XSDateTimePointable.class);
        try {
            tvp.getValue(dtp);
            abvs.reset();
            castToString.convertDatetime(dtp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dtp);
        }
    }

    private void printDTDuration(PrintStream ps, TaggedValuePointable tvp) {
        LongPointable lp = pp.takeOne(LongPointable.class);
        try {
            tvp.getValue(lp);
            abvs.reset();
            castToString.convertDTDuration(lp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(lp);
        }
    }

    private void printDuration(PrintStream ps, TaggedValuePointable tvp) {
        XSDurationPointable dp = pp.takeOne(XSDurationPointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertDuration(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printFloat(PrintStream ps, TaggedValuePointable tvp) {
        FloatPointable fp = pp.takeOne(FloatPointable.class);
        try {
            tvp.getValue(fp);
            abvs.reset();
            castToString.convertFloat(fp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(fp);
        }
    }

    private void printGDay(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertGDay(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printGMonth(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertGMonth(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printGMonthDay(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertGMonthDay(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printGYear(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertGYear(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printGYearMonth(PrintStream ps, TaggedValuePointable tvp) {
        XSDatePointable dp = pp.takeOne(XSDatePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertGYearMonth(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printHexBinary(PrintStream ps, TaggedValuePointable tvp) {
        XSBinaryPointable bp = pp.takeOne(XSBinaryPointable.class);
        try {
            tvp.getValue(bp);
            abvs.reset();
            castToString.convertHexBinary(bp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(bp);
        }
    }

    private void printInt(PrintStream ps, TaggedValuePointable tvp) {
        IntegerPointable ip = pp.takeOne(IntegerPointable.class);
        try {
            tvp.getValue(ip);
            ps.print(ip.intValue());
        } finally {
            pp.giveBack(ip);
        }
    }

    private void printInteger(PrintStream ps, TaggedValuePointable tvp) {
        LongPointable lp = pp.takeOne(LongPointable.class);
        try {
            tvp.getValue(lp);
            ps.print(lp.longValue());
        } finally {
            pp.giveBack(lp);
        }
    }

    private void printShort(PrintStream ps, TaggedValuePointable tvp) {
        ShortPointable sp = pp.takeOne(ShortPointable.class);
        try {
            tvp.getValue(sp);
            ps.print(sp.shortValue());
        } finally {
            pp.giveBack(sp);
        }
    }

    private void printQName(PrintStream ps, TaggedValuePointable tvp) {
        XSQNamePointable dp = pp.takeOne(XSQNamePointable.class);
        try {
            tvp.getValue(dp);
            abvs.reset();
            castToString.convertQName(dp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(dp);
        }
    }

    private void printStringAbvs(PrintStream ps) {
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        try {
            utf8sp.set(abvs.getByteArray(), abvs.getStartOffset() + 1, abvs.getLength() - 1);
            printString(ps, utf8sp);
        } finally {
            pp.giveBack(utf8sp);
        }
    }

    private void printString(PrintStream ps, TaggedValuePointable tvp) {
        UTF8StringPointable utf8sp = pp.takeOne(UTF8StringPointable.class);
        try {
            tvp.getValue(utf8sp);
            printString(ps, utf8sp);
        } finally {
            pp.giveBack(utf8sp);
        }
    }

    private void printString(PrintStream ps, UTF8StringPointable utf8sp) {
        int utfLen = utf8sp.getUTFLength();
        int offset = 2;
        while (utfLen > 0) {
            char c = utf8sp.charAt(offset);
            switch (c) {
                case '<':
                    ps.append("<");
                    break;

                case '>':
                    ps.append(">");
                    break;

                case '&':
                    ps.append("&");
                    break;

                case '"':
                    ps.append(""");
                    break;

                case '\'':
                    ps.append("'");
                    break;

                default:
                    ps.append(c);
                    break;
            }
            int cLen = UTF8StringPointable.getModifiedUTF8Len(c);
            offset += cLen;
            utfLen -= cLen;
        }
    }

    private void printTime(PrintStream ps, TaggedValuePointable tvp) {
        XSTimePointable tp = pp.takeOne(XSTimePointable.class);
        try {
            tvp.getValue(tp);
            abvs.reset();
            castToString.convertTime(tp, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(tp);
        }
    }

    private void printYMDuration(PrintStream ps, TaggedValuePointable tvp) {
        IntegerPointable ip = pp.takeOne(IntegerPointable.class);
        try {
            tvp.getValue(ip);
            abvs.reset();
            castToString.convertYMDuration(ip, dOut);
            printStringAbvs(ps);
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pp.giveBack(ip);
        }
    }

    @Override
    public void init() throws AlgebricksException {

    }
}


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

namespace SharedHardware.Services
{
    public interface IEmailSender
    {
        Task SendEmailAsync(string email, string subject, string message);
    }
}


text:
<?php

class Email_Model extends Model
{
	const PLAIN			=		1;
	const HTML			=		2;

	protected $name = 'email';
	protected $primary = 'email_id';
	protected $prefix = 'email_';

	private $data = array();

	public function send($emailName, $recipient, $name = '', array $data = array())
	{
		if (!$recipient)
		{
			throw new Exception('Recipient param is missing!');
		}

		$query = $this->select()->where("email_name = '$emailName'")->get();
		if (!count($query))
		{
			return false;
		}
		$result = $query->fetchAssoc();

		$email = &$this->load->library('email');
		$email->setSubject($result['email_subject']);
		$email->setFrom(Config::getItem('site.email'), Config::getItem('email.from'));
		$email->setMessage($result['email_text']);

		if ($result['email_format']  == self::HTML)
		{
			$email->setContentType('text/html');
		}
		if (is_array($recipient))
		{
			$email->setRecipient($recipient);
		}
		else
		{
			$email->addRecipient($recipient, $name);
		}
		$data = array_merge($data, $this->data);
		$defaultVars = array(
			'SITE_TITLE'			=> Config::getItem('site.title'),
			'SITE_URL'				=> Url::base(),
			'SITE_EMAIL'			=> Config::getItem('site.email')
		);

		foreach ($defaultVars as $key => $value)
		{
			if (!isset($data[$key]))
			{
				$data[$key] = $value;
			}
		}

		$email->assign($data);
		return $email->send();
	}

	public function sendToUser($emailName, $userId, array $data = array())
	{
		$user = &$this->load->model('user');
		$query = $user->select()->where("user_id = $userId")->get();

		$result = $query->fetchAssoc();
		if (!$result['user_confirm'])
		{
			return false;
		}
		foreach ($result as $key => $value)
		{
			$data[substr($key, 5)] = $value;
		}

		return $this->send($emailName, $result['user_email'], $result['user_name'], $data);
	}

	public function setValue($key, $value = '')
	{
		if (!is_array($key))
		{
			$this->data[$key] = $value;
		}
		else
		{
			foreach ($key as $k => $v)
			{
				$this->data[$k] = $v;
			}
		}
	}

	public function getValue($key)
	{
		return isset($this->data[$key]) ? $this->data[$key] : false;
	}
}
?>


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner v2.2.0</title>

  <link rel="shortcut icon" type="test/image/png" href="lib/jasmine-2.2.0/jasmine_favicon.png">
  <link rel="stylesheet" href="test/lib/jasmine-2.2.0/jasmine.css">

  <script src="test/lib/jasmine-2.2.0/jasmine.js"></script>
  <script src="test/lib/jasmine-2.2.0/jasmine-html.js"></script>
  <script src="test/lib/jasmine-2.2.0/boot.js"></script>

  <!-- include source files here... -->
  <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  <script src="JS/core.js" type="text/javascript"></script>

  <!-- include spec files here... -->
  <script src="test/spec/Engine/Core.js"></script>

</head>

<body>
</body>
</html>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.heyne.gcrud</groupId>
		<artifactId>gcrud</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>gcrud-ui</artifactId>

	<dependencies>
		<dependency>
			<groupId>javax.enterprise</groupId>
			<artifactId>cdi-api</artifactId>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>gcrud-api</artifactId>
			<version>${project.version}</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>


text:
package libvirtxml

type Network struct {
	doc  *Document
	root *Node
}

func NewNetwork() Network {
	doc := &Document{}
	doc.Root = NewNode(nameForLocal("network"))

	return Network{
		doc:  doc,
		root: doc.Root,
	}
}

func NewNetworkForXML(xmlDoc string) (*Network, error) {
	doc := &Document{}
	if err := doc.Unmarshal(xmlDoc); err != nil {
		return nil, err
	}

	if doc.Root == nil {
		doc.Root = NewNode(nameForLocal("network"))
	}

	return &Network{
		doc:  doc,
		root: doc.Root,
	}, nil
}

func (s Network) MarshalToXML() (string, error) {
	return s.doc.Marshal()
}

func (s Network) Name() string {
	return s.root.ensureNode(nameForLocal("name")).CharData
}

func (s Network) SetName(value string) {
	s.root.ensureNode(nameForLocal("name")).CharData = value
}

func (s Network) UUID() string {
	return s.root.ensureNode(nameForLocal("uuid")).CharData
}

func (s Network) SetUUID(value string) {
	s.root.ensureNode(nameForLocal("uuid")).CharData = value
}

func (s Network) MACAddress() string {
	node := s.root.ensureNode(nameForLocal("mac"))
	return node.getAttribute(nameForLocal("address"))
}

func (s Network) Forward() NetworkForward {
	node := s.root.ensureNode(nameForLocal("forward"))
	return newNetworkForward(node)
}

func (s Network) Bridge() NetworkBridge {
	node := s.root.ensureNode(nameForLocal("bridge"))
	return newNetworkBridge(node)
}

func (s Network) IPs() []NetworkIP {
	var result []NetworkIP

	nodes := s.root.findNodes(nameForLocal("ip"))
	for _, node := range nodes {
		result = append(result, newNetworkIP(node))
	}

	return result
}

func (s Network) SetIPs(ips []NetworkIP) {
	s.root.removeNodes(nameForLocal("ip"))

	for _, ip := range ips {
		s.root.addNode(ip.node)
	}
}

func (s Network) NewIP() NetworkIP {
	node := NewNode(nameForLocal("ip"))
	s.root.addNode(node)
	return newNetworkIP(node)
}

func (s Network) Metadata() Metadata {
	node := s.root.ensureNode(nameForLocal("metadata"))
	return newMetadata(node)
}

func (s Network) Domain() NetworDomain {
	node := s.root.ensureNode(nameForLocal("domain"))
	return newNetworkDomain(node)
}

func (s Network) DNS() NetworkDNS {
	node := s.root.ensureNode(nameForLocal("dns"))
	return newNetworkDNS(node)
}


text:
=pod

Hello World server

Binds REP socket to tcp://*:5555

Expects "Hello" from client, replies with "World"

Author: Daisuke Maki (lestrrat)
Original version Author: Alexander D'Archangel (darksuji) <darksuji(at)gmail(dot)com>

=cut

use strict;
use warnings;
use 5.10.0;

use ZMQ::LibZMQ3;
use ZMQ::Constants qw(ZMQ_REP);

my $MAX_MSGLEN = 255;

my $context = zmq_init();

# Socket to talk to clients
my $responder = zmq_socket($context, ZMQ_REP);
zmq_bind($responder, 'tcp://*:5555');

while (1) {
    # Wait for the next request from client
    my $message;
    my $size = zmq_recv($responder, $message, $MAX_MSGLEN);
    my $request = substr($message, 0, $size);
    say 'Received request: ['. $request .']';

    # Do some 'work'
    sleep (1);

    # Send reply back to client
    zmq_send($responder, 'World');
}


text:
/*! HTML5 Boilerplate v5.2.0 | MIT License | https://html5boilerplate.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between audio, canvas, iframes,
 * images, videos and the bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

/* UNIVERSALS */

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

img {
	max-width: 100%
}

body {
	font-family: "source sans pro", helvetica, sans-serif;
	font-weight: 300;
	color: #505050;
	margin: 100px 50px;
}

p {
	color: #A5A5A5;
	line-height: 1.9;
}

/* HEADS */

h1 {
	font-family: questrial, helvetica, sans-serif;
	font-weight: 400;
	font-size: 1.7em
}

h2 {
	font-size: 2.4em;
	font-weight: 200;
	text-align: center;
	line-height: 1.2em;
	padding-bottom: .2em;
}

h3 {
	font-size: 1.8em;
	font-weight: 200;
	margin-top: 0;
	margin-bottom: 0;
}

h4 {
	font-size: 1.5em;
	font-weight: 200;
	margin-top: 0;
	margin-bottom: 0;
}

h6 {
	font-size: .83em;
	margin: 0 0 5px 0;
}

/* HEADER */
.page-header {
	position: fixed;
	top: 0px;
	left: 0px;
	background-color: white;
	width: 100%;
	z-index: 10;
}

.page-header h1 {
	margin: 30px 50px;
}

.main-nav ul {
	list-style: none;
	margin: 0;
}

.main-nav a {
	text-decoration: none;
	color: #505050;
	display: block;
	padding-left: 1.5em;
}

.main-nav li {
	float: left;
}

a {
	text-decoration: none;
	color: #A5A5A5;
}

a:hover {
	color: #61CFB5;
}

.plus {
	padding-left: 9px;
	font-size: 1.7em;
	font-weight: 100;
	position: absolute;
	top: -8.5px;
	right: -20px;
}

.page-header .main-nav {
	position: absolute;
	top: 34px;
	right: 70px;
}

.jumbotron-quote {
	background: #F2F2F2;
	width: 100%;
	padding: 7.5em;
}

.jumbotron-content {
	padding-top: 5em;
	padding-bottom: 7em;
	background: #F2F2F2;
	overflow: auto;
}

.content-list {
	list-style: none;
	padding: 0;
}

.col-1-3-wrap {
	padding: 0 0 0 60px;
	overflow: auto;
	margin-bottom: 1em;
}

.col-1-3 {
	width: 33.3333%;
	float: left;
}

.col-1-3 ul {
	color: #ADADAD
}

/* PROJECT THUMBNAIL SECTION */

.project-thumb {
	background: none;
	width: 50%;
	display: block;
	float: left;
	position: relative;
}

.project-thumb-portrait {
	float: right;
}

.project-thumb:hover {
	background-color: hsla(0,0%,0%,0.7);
}

.project-thumb img {
	position: relative;
	z-index: -10;
}

.project-label {
	font-family: "source sans pro", helvetica, sans-serif;
	font-weight: 200;
	font-size: 1.2em;
	color: white;
	position: absolute;
	top: 20px;
	left: 20px;
}

.project-thumb:hover .btn-wrap {
	visibility: visible;
	opacity: 1;
}

.project-thumb h5 {
	margin: 0;
}

.btn {
	font-size: .9em;
	font-weight: 600;
	letter-spacing: .06em;
	line-height: 1;
	color: white;
	border: 2px solid white;
	width: 40%;
	padding: 12px 0;
	margin-top: 0;
	margin-bottom: 0;
	text-decoration: none;
	text-transform: uppercase;
	text-align: center;
	position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.btn-wrap {
	visibility: hidden;
}

.btn:hover {
	background-color: white;
	color: black;
}

.project-thumb:hover {
	visibility: visible;
	transition: all 0.7s ease 0s;
}

.page-section-white {
	background: white;
}

/* ARTICLES */

.page-article {
	padding: 0 50px 250px 50px;
}

.article-col-1-2 {
	border-top: 1px solid #CECECE;
	padding-top: 20px;
	margin-right: 40px;
	width: 30%;
	float: left;
}

.article-col-2-3 {
	border-top: 1px solid #CECECE;
	padding-top: 20px;
	width: 60%;
	float: left;
}

.article-category {
	font-size: 1.2em;
}

.article-separator {
	color: #A5A5A5;
	font-size: .8em;
	padding: 5px;
	position: relative;
	top: -.2em;
}

.article-date {
	color: #A5A5A5;
}

.news-title {
	color: #505050;
}

/* FOOTER */

.footer-contact {
	padding: 50px 15px 50px 0px;
	position: relative;
}

.footer-contact p {
	font-size: .9em;
	line-height: 1.4;
	margin: 0;
}

.col-1-4 {
	width: 25%;
	float: left;
	padding: 0 15px 0 0;
}

i {
	font-size: 4em;
	padding-right: 15px
}

i:hover {
	color: #61CFB5;
}
.character-map {
	width: 100%;
}

/* SOCIAL MEDIA */

.social-media {
  position: absolute;
  right: -15px;
  top: 50px;
}

.copyright {
	padding-top: 40px;
	clear: both;
}

.copyright {
  font-size: .7em;
}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Hide visually and from screen readers:
 */

.hidden {
    display: none !important;
}

/*
 * Hide only visually, but have it available for screen readers:
 * http://snook.ca/archives/html_and_css/hiding-content-for-accessibility
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element
 * to be focusable when navigated to via the keyboard:
 * https://www.drupal.org/node/897638
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screen readers, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid the additional HTTP request:
   http://www.phpied.com/delay-loading-your-print-css/
   ========================================================================== */

@media print {
    *,
    *:before,
    *:after {
        background: transparent !important;
        color: #000 !important; /* Black prints faster:
                                   http://www.sanbeiji.com/archives/953 */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links that are fragment identifiers,
     * or use the `javascript:` pseudo protocol
     */

    a[href^="#"]:after,
    a[href^="javascript:"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    /*
     * Printing Tables:
     * http://css-discuss.incutio.com/wiki/Printing_Tables
     */

    thead {
        display: table-header-group;
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
{% extends 'base/layout.html' %}
{% load bootstrap3 static ddm %}

{% block extrahead %}
    {{ block.super }}
    <link rel="stylesheet" href="{% static 'dashboard/home.css' %}">
{% endblock %}

{% block content %}

 Dashboard

 Best Options

Current leading options

                {% for option in best_options|slice:':5' %}

{{ option.name }} {{ option.get_fitness|show_average }}

                {% endfor %}

 Most up-to-date users

Users who have completed the most scores

                {% for user in up_to_date_users|slice:':5' %}

{% firstof user.get_full_name user.username %} {{ user.num_scores }}

                {% endfor %}

 Discordant Priorities

Criteria whos importance users are least consistent about

                {% for criterion in criteria_by_weight_variance_high|slice:':5' %}

{{ criterion }} {{ criterion.get_weight_variance|show_average }}

                {% endfor %}

 Common Priorities

Criteria whos importance users are most consistent about

                {% for criterion in criteria_by_weight_variance_low|slice:':5' %}

{{ criterion }} {{ criterion.get_weight_variance|show_average }}

                {% endfor %}

 Option Variability

Criteria that score the most variably across options

                {% for criterion in criteria_by_score_variance_high|slice:':5' %}

{{ criterion }} {{ criterion.get_score_variance|show_average }}

                {% endfor %}

 Option Consistency

Criteria that score the most consistently across options

                {% for criterion in criteria_by_score_variance_low|slice:':5' %}

{{ criterion }} {{ criterion.get_score_variance|show_average }}

                {% endfor %}

{% endblock %}


text:
/**
 * @fileoverview Prefer es6 class instead of createClass for React Component
 * @author Dan Hamilton
 */
'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

var rule = require('../../../lib/rules/prefer-es6-class');
var RuleTester = require('eslint').RuleTester;

var parserOptions = {
  ecmaVersion: 6,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true
  }
};

require('babel-eslint');

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

var ruleTester = new RuleTester();
ruleTester.run('prefer-es6-class', rule, {

  valid: [{
    code: [
      'class Hello extends React.Component {',
      '  render() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '}',
      'Hello.displayName = \'Hello\''
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'export default class Hello extends React.Component {',
      '  render() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '}',
      'Hello.displayName = \'Hello\''
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'var Hello = "foo";',
      'module.exports = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'var Hello = React.createClass({',
      '  render: function() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '});'
    ].join('\n'),
    options: ['never'],
    parserOptions: parserOptions
  }, {
    code: [
      'class Hello extends React.Component {',
      '  render() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '}'
    ].join('\n'),
    options: ['always'],
    parserOptions: parserOptions
  }],

  invalid: [{
    code: [
      'var Hello = React.createClass({',
      '  displayName: \'Hello\',',
      '  render: function() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '});'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{
      message: 'Component should use es6 class instead of createClass'
    }]
  }, {
    code: [
      'var Hello = React.createClass({',
      '  render: function() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '});'
    ].join('\n'),
    options: ['always'],
    parserOptions: parserOptions,
    errors: [{
      message: 'Component should use es6 class instead of createClass'
    }]
  }, {
    code: [
      'class Hello extends React.Component {',
      '  render() {',
      '    return
Hello {this.props.name}
;',
      '  }',
      '}'
    ].join('\n'),
    options: ['never'],
    parserOptions: parserOptions,
    errors: [{
      message: 'Component should use createClass instead of es6 class'
    }]
  }
]});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Psora albilabra subsp. albilabra (Dufour) Körb.

### Remarks
null


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace gameLIB.components.sprites
{
    abstract public class Sprite
    {
        public Image image { get; set; }
        public Vector2 position { get; set; }
        public Vector2 initPosition { get; set; }

        public Sprite(Image image, Vector2 position) //pour tout le reste (clonage)
        {
            this.image = image;
            this.position = position;
            this.initPosition = new Vector2(position.X, position.Y);
        }

        public virtual void initialize()
        {
            this.position = new Vector2(initPosition.X, initPosition.Y);
        }

        public abstract void draw(SpriteBatch spriteBatch);
    }
}


text:
{% extends 'templates/layout/default.html' %}
{% block body %}

Portal de Cursos

{% endblock %}


text:
ListBoxFunctions::<BIG>VerifyItem</BIG>

RJ

<short_desc xmlns="">
                Verifies a particular case-sensitive item based on index is equal
                to a particular value.
              </short_desc>

<detailed_desc xmlns="">
                Verifies a particular case-sensitive item based on index is equal
                to a particular value.
              </detailed_desc>

Fields: [ ]=Optional with Default Value

Index

<short_desc xmlns="">
                 Index of the item in the list starting from 1
              </short_desc>

<detailed_desc xmlns="">
                 Index of the item in the list starting from 1
              </detailed_desc>

TextValue

<short_desc xmlns="">
                 Case-sensitive string to compare to the text of the node at the index.
              </short_desc>

<detailed_desc xmlns="">
                 Case-sensitive string to compare to the text of the node at the index.
              </detailed_desc>

Examples:

<usage xmlns="">T, WINDOW, ListBox, VerifyItem, 1, "ATextString"</usage>

<short_desc xmlns="">
                 Verifies that the first item is equal to "ATextString"
              </short_desc>

<usage xmlns="">T, WINDOW, ListBox, VerifyItem, 10, "ATextString10"</usage>

<short_desc xmlns="">
                 Verifies that the item at index 10 is equal to "ATextString10"
              </short_desc>

[How To Read This Reference]


text:
#ifndef soapPTZBindingService_H
#define soapPTZBindingService_H
#include "soapH.h"
class SOAP_CMAC PTZBindingService
{ public:
	struct soap *soap;
	bool own;
	/// Constructor
	PTZBindingService();
	/// Constructor to use/share an engine state
	PTZBindingService(struct soap*);
	/// Constructor with engine input+output mode control
	PTZBindingService(soap_mode iomode);
	/// Constructor with engine input and output mode control
	PTZBindingService(soap_mode imode, soap_mode omode);
	/// Destructor, also frees all deserialized data
	virtual ~PTZBindingService();
	/// Delete all deserialized data (with soap_destroy and soap_end)
	virtual	void destroy();
	/// Delete all deserialized data and reset to defaults
	virtual	void reset();
	/// Initializer used by constructor
	virtual	void PTZBindingService_init(soap_mode imode, soap_mode omode);
	/// Create a copy
	virtual	PTZBindingService *copy() SOAP_PURE_VIRTUAL;
	/// Close connection (normally automatic)
	virtual	int soap_close_socket();
	/// Force close connection (can kill a thread blocked on IO)
	virtual	int soap_force_close_socket();
	/// Return sender-related fault to sender
	virtual	int soap_senderfault(const char *string, const char *detailXML);
	/// Return sender-related fault with SOAP 1.2 subcode to sender
	virtual	int soap_senderfault(const char *subcodeQName, const char *string, const char *detailXML);
	/// Return receiver-related fault to sender
	virtual	int soap_receiverfault(const char *string, const char *detailXML);
	/// Return receiver-related fault with SOAP 1.2 subcode to sender
	virtual	int soap_receiverfault(const char *subcodeQName, const char *string, const char *detailXML);
	/// Print fault
	virtual	void soap_print_fault(FILE*);
#ifndef WITH_LEAN
	/// Print fault to stream
#ifndef WITH_COMPAT
	virtual	void soap_stream_fault(std::ostream&);
#endif
	/// Put fault into buffer
	virtual	char *soap_sprint_fault(char *buf, size_t len);
#endif
	/// Disables and removes SOAP Header from message
	virtual	void soap_noheader();
	/// Put SOAP Header in message
	virtual	void soap_header(char *wsa5__MessageID, struct wsa5__RelatesToType *wsa5__RelatesTo, struct wsa5__EndpointReferenceType *wsa5__From, struct wsa5__EndpointReferenceType *wsa5__ReplyTo, struct wsa5__EndpointReferenceType *wsa5__FaultTo, char *wsa5__To, char *wsa5__Action, struct chan__ChannelInstanceType *chan__ChannelInstance, struct _wsse__Security *wsse__Security);
	/// Get SOAP Header structure (NULL when absent)
	virtual	const SOAP_ENV__Header *soap_header();
	/// Run simple single-thread iterative service on port until a connection error occurs (returns error code or SOAP_OK), use this->bind_flag = SO_REUSEADDR to rebind for a rerun
	virtual	int run(int port);
	/// Bind service to port (returns master socket or SOAP_INVALID_SOCKET)
	virtual	SOAP_SOCKET bind(const char *host, int port, int backlog);
	/// Accept next request (returns socket or SOAP_INVALID_SOCKET)
	virtual	SOAP_SOCKET accept();
#if defined(WITH_OPENSSL) || defined(WITH_GNUTLS)
	/// Then accept SSL handshake, when SSL is used
	virtual	int ssl_accept();
#endif
	/// Serve this request (returns error code or SOAP_OK)
	virtual	int serve();
	/// Used by serve() to dispatch a request (returns error code or SOAP_OK)
	virtual	int dispatch();

	///
	/// Service operations (you should define these):
	/// Note: compile with -DWITH_PURE_VIRTUAL for pure virtual methods
	///

	/// Web service operation 'GetServiceCapabilities' (returns error code or SOAP_OK)
	virtual	int GetServiceCapabilities(_tptz__GetServiceCapabilities *tptz__GetServiceCapabilities, _tptz__GetServiceCapabilitiesResponse *tptz__GetServiceCapabilitiesResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetConfigurations' (returns error code or SOAP_OK)
	virtual	int GetConfigurations(_tptz__GetConfigurations *tptz__GetConfigurations, _tptz__GetConfigurationsResponse *tptz__GetConfigurationsResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetPresets' (returns error code or SOAP_OK)
	virtual	int GetPresets(_tptz__GetPresets *tptz__GetPresets, _tptz__GetPresetsResponse *tptz__GetPresetsResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'SetPreset' (returns error code or SOAP_OK)
	virtual	int SetPreset(_tptz__SetPreset *tptz__SetPreset, _tptz__SetPresetResponse *tptz__SetPresetResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'RemovePreset' (returns error code or SOAP_OK)
	virtual	int RemovePreset(_tptz__RemovePreset *tptz__RemovePreset, _tptz__RemovePresetResponse *tptz__RemovePresetResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GotoPreset' (returns error code or SOAP_OK)
	virtual	int GotoPreset(_tptz__GotoPreset *tptz__GotoPreset, _tptz__GotoPresetResponse *tptz__GotoPresetResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetStatus' (returns error code or SOAP_OK)
	virtual	int GetStatus(_tptz__GetStatus *tptz__GetStatus, _tptz__GetStatusResponse *tptz__GetStatusResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetConfiguration' (returns error code or SOAP_OK)
	virtual	int GetConfiguration(_tptz__GetConfiguration *tptz__GetConfiguration, _tptz__GetConfigurationResponse *tptz__GetConfigurationResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetNodes' (returns error code or SOAP_OK)
	virtual	int GetNodes(_tptz__GetNodes *tptz__GetNodes, _tptz__GetNodesResponse *tptz__GetNodesResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetNode' (returns error code or SOAP_OK)
	virtual	int GetNode(_tptz__GetNode *tptz__GetNode, _tptz__GetNodeResponse *tptz__GetNodeResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'SetConfiguration' (returns error code or SOAP_OK)
	virtual	int SetConfiguration(_tptz__SetConfiguration *tptz__SetConfiguration, _tptz__SetConfigurationResponse *tptz__SetConfigurationResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetConfigurationOptions' (returns error code or SOAP_OK)
	virtual	int GetConfigurationOptions(_tptz__GetConfigurationOptions *tptz__GetConfigurationOptions, _tptz__GetConfigurationOptionsResponse *tptz__GetConfigurationOptionsResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GotoHomePosition' (returns error code or SOAP_OK)
	virtual	int GotoHomePosition(_tptz__GotoHomePosition *tptz__GotoHomePosition, _tptz__GotoHomePositionResponse *tptz__GotoHomePositionResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'SetHomePosition' (returns error code or SOAP_OK)
	virtual	int SetHomePosition(_tptz__SetHomePosition *tptz__SetHomePosition, _tptz__SetHomePositionResponse *tptz__SetHomePositionResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'ContinuousMove' (returns error code or SOAP_OK)
	virtual	int ContinuousMove(_tptz__ContinuousMove *tptz__ContinuousMove, _tptz__ContinuousMoveResponse *tptz__ContinuousMoveResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'RelativeMove' (returns error code or SOAP_OK)
	virtual	int RelativeMove(_tptz__RelativeMove *tptz__RelativeMove, _tptz__RelativeMoveResponse *tptz__RelativeMoveResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'SendAuxiliaryCommand' (returns error code or SOAP_OK)
	virtual	int SendAuxiliaryCommand(_tptz__SendAuxiliaryCommand *tptz__SendAuxiliaryCommand, _tptz__SendAuxiliaryCommandResponse *tptz__SendAuxiliaryCommandResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'AbsoluteMove' (returns error code or SOAP_OK)
	virtual	int AbsoluteMove(_tptz__AbsoluteMove *tptz__AbsoluteMove, _tptz__AbsoluteMoveResponse *tptz__AbsoluteMoveResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'Stop' (returns error code or SOAP_OK)
	virtual	int Stop(_tptz__Stop *tptz__Stop, _tptz__StopResponse *tptz__StopResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetPresetTours' (returns error code or SOAP_OK)
	virtual	int GetPresetTours(_tptz__GetPresetTours *tptz__GetPresetTours, _tptz__GetPresetToursResponse *tptz__GetPresetToursResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetPresetTour' (returns error code or SOAP_OK)
	virtual	int GetPresetTour(_tptz__GetPresetTour *tptz__GetPresetTour, _tptz__GetPresetTourResponse *tptz__GetPresetTourResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetPresetTourOptions' (returns error code or SOAP_OK)
	virtual	int GetPresetTourOptions(_tptz__GetPresetTourOptions *tptz__GetPresetTourOptions, _tptz__GetPresetTourOptionsResponse *tptz__GetPresetTourOptionsResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'CreatePresetTour' (returns error code or SOAP_OK)
	virtual	int CreatePresetTour(_tptz__CreatePresetTour *tptz__CreatePresetTour, _tptz__CreatePresetTourResponse *tptz__CreatePresetTourResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'ModifyPresetTour' (returns error code or SOAP_OK)
	virtual	int ModifyPresetTour(_tptz__ModifyPresetTour *tptz__ModifyPresetTour, _tptz__ModifyPresetTourResponse *tptz__ModifyPresetTourResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'OperatePresetTour' (returns error code or SOAP_OK)
	virtual	int OperatePresetTour(_tptz__OperatePresetTour *tptz__OperatePresetTour, _tptz__OperatePresetTourResponse *tptz__OperatePresetTourResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'RemovePresetTour' (returns error code or SOAP_OK)
	virtual	int RemovePresetTour(_tptz__RemovePresetTour *tptz__RemovePresetTour, _tptz__RemovePresetTourResponse *tptz__RemovePresetTourResponse) SOAP_PURE_VIRTUAL;

	/// Web service operation 'GetCompatibleConfigurations' (returns error code or SOAP_OK)
	virtual	int GetCompatibleConfigurations(_tptz__GetCompatibleConfigurations *tptz__GetCompatibleConfigurations, _tptz__GetCompatibleConfigurationsResponse *tptz__GetCompatibleConfigurationsResponse) SOAP_PURE_VIRTUAL;
};
#endif


text:
"""
Support for BloomSky weather station.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/bloomsky/
"""
import logging
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.const import CONF_API_KEY
from homeassistant.helpers import discovery
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

BLOOMSKY = None
BLOOMSKY_TYPE = ['camera', 'binary_sensor', 'sensor']

DOMAIN = 'bloomsky'

# The BloomSky only updates every 5-8 minutes as per the API spec so there's
# no point in polling the API more frequently
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_API_KEY): cv.string,
    }),
}, extra=vol.ALLOW_EXTRA)

# pylint: disable=unused-argument,too-few-public-methods
def setup(hass, config):
    """Setup BloomSky component."""
    api_key = config[DOMAIN][CONF_API_KEY]

    global BLOOMSKY
    try:
        BLOOMSKY = BloomSky(api_key)
    except RuntimeError:
        return False

    for component in BLOOMSKY_TYPE:
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True

class BloomSky(object):
    """Handle all communication with the BloomSky API."""

    # API documentation at http://weatherlution.com/bloomsky-api/
    API_URL = 'https://api.bloomsky.com/api/skydata'

    def __init__(self, api_key):
        """Initialize the BookSky."""
        self._api_key = api_key
        self.devices = {}
        _LOGGER.debug("Initial BloomSky device load...")
        self.refresh_devices()

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def refresh_devices(self):
        """Use the API to retrieve a list of devices."""
        _LOGGER.debug("Fetching BloomSky update")
        response = requests.get(self.API_URL,
                                headers={"Authorization": self._api_key},
                                timeout=10)
        if response.status_code == 401:
            raise RuntimeError("Invalid API_KEY")
        elif response.status_code != 200:
            _LOGGER.error("Invalid HTTP response: %s", response.status_code)
            return
        # Create dictionary keyed off of the device unique id
        self.devices.update({
            device['DeviceID']: device for device in response.json()
        })


text:
<!DOCTYPE html>

JS Redirect After RAF

JS Redirect immediate

Meta refresh

Window Open + JS Redirect

Window Open Blank doc.write meta refresh

To 301 redirect


text: I'm a set of permissions for a Directory Entry


text:
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'False Positives')]
Param()

Import-Module $PSScriptRoot\..\..\ImportExcel.psd1 -Force

Describe "Test reading multiple XLSX files of different row count" -Tag ReadMultipleXLSX {
    It "Should find these xlsx files" {
        Test-Path -Path $PSScriptRoot\rows05.xlsx | Should -BeTrue
        Test-Path -Path $PSScriptRoot\rows10.xlsx | Should -BeTrue
    }

    It "Should find two xlsx files" {
        (Get-ChildItem $PSScriptRoot\row*xlsx).Count | Should -Be 2
    }

    It "Should get 5 rows" {
        (Import-Excel $PSScriptRoot\rows05.xlsx).Count | Should -Be 5
    }

    It "Should get 10 rows" {
        (Import-Excel $PSScriptRoot\rows10.xlsx).Count | Should -Be 10
    }

    It "Should get 15 rows" {
        $actual = Get-ChildItem $PSScriptRoot\row*xlsx | Import-Excel

        $actual.Count | Should -Be 15
    }

    It "Should get 4 property names" {
        $actual = Get-ChildItem $PSScriptRoot\row*xlsx | Import-Excel

        $names = $actual[0].psobject.properties.name
        $names.Count | Should -Be 4

        $names[0] | Should -BeExactly "Region"
        $names[1] | Should -BeExactly "State"
        $names[2] | Should -BeExactly "Units"
        $names[3] | Should -BeExactly "Price"
    }

    It "Should have the correct data" {
        $actual = Get-ChildItem $PSScriptRoot\row*xlsx | Import-Excel

        # rows05.xlsx
        $actual[0].Region | Should -BeExactly "South"
        $actual[0].Price | Should -Be 181.52
        $actual[4].Region | Should -BeExactly "West"
        $actual[4].Price | Should -Be 216.56

        # rows10.xlsx
        $actual[5].Region | Should -BeExactly "South"
        $actual[5].Price | Should -Be 199.85
        $actual[14].Region | Should -BeExactly "East"
        $actual[14].Price | Should -Be 965.25
    }
}


text:
title: IE9 and Safari Compatibility
page_title: IE9 and Safari Compatibility | RadClientExportManager for ASP.NET AJAX Documentation
description: IE9 and Safari Compatibility
slug: clientexportmanager/troubleshooting/ie9-and-safari-compatibility
tags: ie9,and,safari,compatibility
published: True
position: 0
---

# IE9 and Safari Compatibility

This article explains the specifics in RadClientExportManager's configuration for use in IE9 and Safari

## IE9 and Safari Compatibility

The **RadClientExportManager** relies on the File API in order to work.IE9 and Safari browser does not support File API so in order to export the browser needs to make a request to the server and receive back the data. For this functionality is used the **RadClientExportManager ProxyURL**. The example below shows how to configure RadClientExportManager, to be able to use it with IE9 and Safari.

**Example1:** The example shows how to configure the **RadClientExportManager** in order to use ProxyURL, process and returns the data stream to the client.

````ASPNET
<div id="foo">
	<span>Some text</span>

	<telerik:RadClientExportManager runat="server" ID="RadClientExportManager1">
		<PdfSettings FileName="MyFile.pdf" ProxyURL="api/export/file" />
	</telerik:RadClientExportManager>

	<script type="text/javascript">
		function exportElement() {
			var exp = $find("RadClientExportManager1");
			exp.exportPDF($telerik.$("html"));
		}
	</script>
</div>
````
````VB.NET
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Net.Http.Formatting
Imports System.Net.Http.Headers
Imports System.Web.Http

Public Class ExportController
	Inherits ApiController
	<HttpPost> _
	Public Function File(values As FormDataCollection) As HttpResponseMessage
		Dim contentType = values.[Get]("contentType")
		Dim base64 = values.[Get]("base64")
		Dim fileName = values.[Get]("fileName")

		Dim fileContents = Convert.FromBase64String(base64)

		Dim response = New HttpResponseMessage()
		response.Content = New ByteArrayContent(fileContents)
		response.Content.Headers.ContentDisposition = New ContentDispositionHeaderValue("attachment")
		response.Content.Headers.ContentDisposition.FileName = fileName
		response.Content.Headers.ContentType = New MediaTypeHeaderValue(contentType)
		response.Content.Headers.ContentLength = fileContents.Length

		Return response
	End Function
End Class
#End Region
````

# See Also

* [Export in IE9 and Safari using a WCF service and ProxyURL](http://www.telerik.com/support/code-library/ie9-and-safari-compatibility)

* [Save exported files on the server]({%slug clientexportmanager/how-to/save-exported-files%})


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

<Context swallowOutput="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>


text:
import { Component, ElementRef, HostListener, Renderer2 } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';

import 'style-loader!./register.scss';
import { EmailValidator } from "../theme/validators/email.validator";
import { EqualPasswordsValidator } from "../theme/validators/equalPasswords.validator";
import { RegisterService } from "./register.service";
import { Router } from "@angular/router";
import { ToasterConfig, ToasterService } from "angular2-toaster";

@Component({
  selector: 'register',
  templateUrl: './register.html',
  styleUrls: ['./register.css'],
  providers: [RegisterService]
})
export class Register {

  public form: FormGroup;
  public name: AbstractControl;
  public email: AbstractControl;
  public password: AbstractControl;
  public repeatPassword: AbstractControl;
  public passwords: FormGroup;

  public submitted: boolean = false;

  toasterconfig: ToasterConfig =
    new ToasterConfig({
      tapToDismiss: false,
      showCloseButton: true
    });

  constructor(fb: FormBuilder, private elementRef: ElementRef, private Renderer: Renderer2,
    private service: RegisterService, private router: Router, private toasterService: ToasterService) {

    this.form = fb.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
      'email': ['', Validators.compose([Validators.required, EmailValidator.validate])],
      'passwords': fb.group({
        'password': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
        'repeatPassword': ['', Validators.compose([Validators.required, Validators.minLength(1)])]
      }, { validator: EqualPasswordsValidator.validate('password', 'repeatPassword') })
    });

    this.name = this.form.controls['name'];
    this.email = this.form.controls['email'];
    this.passwords = <FormGroup>this.form.controls['passwords'];
    this.password = this.passwords.controls['password'];
    this.repeatPassword = this.passwords.controls['repeatPassword'];
  }

  onSubmit(): void {

    // let submit: HTMLElement = this.elementRef.nativeElement.querySelector('#re-register');
    // this.Renderer.s

    this.service.register(this.name.value, this.password.value, this.email.value)
      .then(res => {
        if (res.msg) {
          this.toasterService.pop('error', res.msg[1], '注册失败');
        } else {
          this.toasterService.pop('OK', '注册成功,自动登录');
          this.router.navigate(['/pages/welcome']);
        }
      }, err => {
        console.log(err)
        this.toasterService.pop('error', JSON.parse(err._body).msg[1], '注册失败');
      })
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {

    let header: HTMLElement = this.elementRef.nativeElement.querySelector('#header');
    let content: HTMLElement = this.elementRef.nativeElement.querySelector('#content');
    let register: HTMLElement = this.elementRef.nativeElement.querySelector('#RegisterPart');

    if (header.scrollHeight > content.scrollHeight) {
      // content.style.marginTop = (header.scrollHeight - content.scrollHeight) / 2 + 20 + 'px';
      this.Renderer.setStyle(content, 'marginTop', "(header.scrollHeight - content.scrollHeight)/2 + 20 + 'px'");
    }

    if (screen.width < 1920 && screen.height < 1080) {

      this.Renderer.setStyle(content, 'width', '980px');
      this.Renderer.setStyle(content, 'height', '560px');
      this.Renderer.setStyle(content, 'minWidth', '980px');
      this.Renderer.setStyle(register, 'top', '120px')
    }
  }
  ngOnInit() {
    this.onResize(event);
  }

}