text:
package org.jboss.resteasy.reactive.common.util;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.core.MultivaluedMap;

/**
 * Unmodifiable implementation of {@link javax.ws.rs.core.MultivaluedMap} interface
 *
 * @author Martin Stefanko
 * @version $Revision: 1 $
 */
public class UnmodifiableMultivaluedMap<K, V> implements MultivaluedMap<K, V> {

    private final MultivaluedMap<K, V> delegate;

    private volatile Set<java.util.Map.Entry<K, List<V>>> entrySet;

    public UnmodifiableMultivaluedMap(final MultivaluedMap<K, V> delegate) {
        this(delegate, true);
    }

    public UnmodifiableMultivaluedMap(final MultivaluedMap<K, V> delegate, final boolean eagerlyInitializeEntrySet) {
        this.delegate = delegate;
        if (eagerlyInitializeEntrySet) {
            this.entrySet = buildEntrySet();
        }
    }

    private Set<java.util.Map.Entry<K, List<V>>> buildEntrySet() {
        Set<java.util.Map.Entry<K, List<V>>> entrySetDelegator = delegate.entrySet();
        Set<java.util.Map.Entry<K, List<V>>> entrySetToReturn = new HashSet<>();
        for (final java.util.Map.Entry<K, List<V>> entry : entrySetDelegator) {
            entrySetToReturn.add(new Entry<K, List<V>>() {

                @Override
                public K getKey() {
                    return entry.getKey();
                }

                @Override
                public List<V> getValue() {
                    List<V> value = entry.getValue();
                    return value == null ? null : Collections.unmodifiableList(value);
                }

                @Override
                public List<V> setValue(List<V> value) {
                    throw new UnsupportedOperationException();
                }
            });
        }
        return Collections.unmodifiableSet(entrySetToReturn);
    }

    @Override
    public void putSingle(K k, V v) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void add(K k, V v) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V getFirst(K key) {
        return delegate.getFirst(key);
    }

    @SuppressWarnings(value = "unchecked")
    @Override
    public void addAll(K k, V... vs) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void addAll(K k, List<V> list) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void addFirst(K k, V v) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean equalsIgnoreValueOrder(MultivaluedMap<K, V> omap) {
        return delegate.equalsIgnoreValueOrder(omap);
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<Entry<K, List<V>>> entrySet() {
        if (this.entrySet == null) {
            this.entrySet = buildEntrySet();
        }
        return this.entrySet;
    }

    @Override
    public List<V> get(Object key) {
        List<V> list = delegate.get(key);
        return list == null ? null : Collections.unmodifiableList(list);
    }

    @Override
    public Set<K> keySet() {
        return Collections.unmodifiableSet(delegate.keySet());
    }

    @Override
    public List<V> put(K key, List<V> value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map<? extends K, ? extends List<V>> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public List<V> remove(Object key) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<List<V>> values() {
        return Collections.unmodifiableCollection(delegate.values());
    }

    @Override
    public boolean containsKey(Object o) {
        return delegate.containsKey(o);
    }

    @Override
    public boolean containsValue(Object o) {
        return delegate.containsValue(o);
    }

    @Override
    public int size() {
        return delegate.size();
    }

    @Override
    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    @Override
    public String toString() {
        return delegate.toString();
    }
}


text:
package legends.model.events;

import legends.model.Entity;
import legends.model.Site;
import legends.model.World;
import legends.model.events.basic.EntityRelatedEvent;
import legends.model.events.basic.Event;
import legends.model.events.basic.HfRelatedEvent;
import legends.model.events.basic.SiteRelatedEvent;
import legends.xml.annotation.Xml;
import legends.xml.annotation.XmlSubtype;

@XmlSubtype("hf destroyed site")
public class HfDestroyedSiteEvent extends Event implements HfRelatedEvent, EntityRelatedEvent, SiteRelatedEvent {
	@Xml("attacker_hfid")
	private int attackerHfId = -1;
	@Xml("defender_civ_id")
	private int defenderCivId = -1;
	@Xml("site_civ_id")
	private int siteCivId = -1;
	@Xml("site_id")
	private int siteId = -1;

	public int getAttackerHfId() {
		return attackerHfId;
	}

	public void setAttackerHfId(int attackerHfId) {
		this.attackerHfId = attackerHfId;
	}

	public int getDefenderCivId() {
		return defenderCivId;
	}

	public void setDefenderCivId(int defenderCivId) {
		this.defenderCivId = defenderCivId;
	}

	public int getSiteId() {
		return siteId;
	}

	public void setSiteId(int siteId) {
		this.siteId = siteId;
	}

	public int getSiteCivId() {
		return siteCivId;
	}

	public void setSiteCivId(int siteCivId) {
		this.siteCivId = siteCivId;
	}

	@Override
	public boolean isRelatedToHf(int hfId) {
		return attackerHfId == hfId;
	}

	@Override
	public boolean isRelatedToEntity(int entityId) {
		return defenderCivId == entityId || siteCivId == entityId;
	}

	@Override
	public boolean isRelatedToSite(int siteId) {
		return this.siteId == siteId;
	}

	@Override
	public void process() {
		Entity defender = World.getEntity(defenderCivId);
		Site site = World.getSite(siteId);
		site.getEvents().add(this);
		site.setOwner(null);
		defender.getSites().add(site);

		Entity siteCiv = World.getEntity(siteCivId);
		if (siteCiv.getType().equals("unknown"))
			siteCiv.setType("sitegovernment");
		if (siteCiv.getRace().equals("unknown"))
			siteCiv.setRace(defender.getRace());
	}

	@Override
	public String getShortDescription() {
		String attacker = World.getHistoricalFigure(attackerHfId).getLink();
		String defender = defenderCivId != -1 ? World.getEntity(defenderCivId).getLink() : "an unknown civilization";
		String loc = World.getSite(siteId).getLink();
		return attacker + " routed " + World.getEntity(siteCivId).getLink() + " of " + defender + " and destroyed "
				+ loc;
	}

}

redpajama_set_name: RedPajamaGithub


text:
[Routegadget](http://www.routegadget.net/) live GPS tracker client for Windows Phone 8

Download from store: http://windowsphone.com/s?appid=137a59a7-0c45-4539-b82f-22876bef2ac0


text:
package com.github.jdsjlzx.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.github.jdsjlzx.R;
import com.github.jdsjlzx.interfaces.BaseRefreshHeader;
import com.github.jdsjlzx.progressindicator.AVLoadingIndicatorView;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import java.util.Date;

public class ArrowRefreshHeader extends LinearLayout implements BaseRefreshHeader {

    private LinearLayout mContainer;
    private ImageView mArrowImageView;
    private SimpleViewSwitcher mProgressBar;
    private TextView mStatusTextView;
    private int mState = STATE_NORMAL;

    private TextView mHeaderTimeView;

    private Animation mRotateUpAnim;
    private Animation mRotateDownAnim;

    private static final int ROTATE_ANIM_DURATION = 180;

    public int mMeasuredHeight;
    private Context mContext;

    public ArrowRefreshHeader(Context context) {
        super(context);
        initView();
    }

    /**
     * @param context
     * @param attrs
     */
    public ArrowRefreshHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        mContext = getContext();
        // 初始情况,设置下拉刷新view高度为0
        mContainer = (LinearLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.listview_header, null);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 0);
        this.setLayoutParams(lp);
        this.setPadding(0, 0, 0, 0);

        addView(mContainer, new LayoutParams(LayoutParams.MATCH_PARENT, 0));
        setGravity(Gravity.BOTTOM);

        mArrowImageView = (ImageView) findViewById(R.id.listview_header_arrow);
        mStatusTextView = (TextView) findViewById(R.id.refresh_status_textview);

        //init the progress view
        mProgressBar = (SimpleViewSwitcher) findViewById(R.id.listview_header_progressbar);
        AVLoadingIndicatorView progressView = new AVLoadingIndicatorView(getContext());
        progressView.setIndicatorColor(0xffB5B5B5);
        progressView.setIndicatorId(ProgressStyle.BallSpinFadeLoader);
        mProgressBar.setView(progressView);

        mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateUpAnim.setFillAfter(true);
        mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
        mRotateDownAnim.setFillAfter(true);

        mHeaderTimeView = (TextView) findViewById(R.id.last_refresh_time);
        measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mMeasuredHeight = getMeasuredHeight();
    }

    public void setProgressStyle(int style) {
        if (style == ProgressStyle.SysProgress) {
            mProgressBar.setView(new ProgressBar(getContext(), null, android.R.attr.progressBarStyle));
        } else {
            AVLoadingIndicatorView progressView = new AVLoadingIndicatorView(this.getContext());
            progressView.setIndicatorColor(0xffB5B5B5);
            progressView.setIndicatorId(style);
            mProgressBar.setView(progressView);
        }
    }

    public void setArrowImageView(int resid) {
        mArrowImageView.setImageResource(resid);
    }

    public void setState(int state) {
        if (state == mState) return;

        if (state == STATE_REFRESHING) {    // 显示进度
            mArrowImageView.clearAnimation();
            mArrowImageView.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.VISIBLE);
        } else if (state == STATE_DONE) {
            mArrowImageView.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
        } else {    // 显示箭头图片
            mArrowImageView.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
        }

        switch (state) {
            case STATE_NORMAL:
                if (mState == STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.startAnimation(mRotateDownAnim);
                }
                if (mState == STATE_REFRESHING) {
                    mArrowImageView.clearAnimation();
                }
                mStatusTextView.setText(R.string.listview_header_hint_normal);
                break;
            case STATE_RELEASE_TO_REFRESH:
                if (mState != STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.clearAnimation();
                    mArrowImageView.startAnimation(mRotateUpAnim);
                    mStatusTextView.setText(R.string.listview_header_hint_release);
                }
                break;
            case STATE_REFRESHING:
                mStatusTextView.setText(R.string.refreshing);
                break;
            case STATE_DONE:
                mStatusTextView.setText(R.string.refresh_done);
                break;
            default:
        }

        mState = state;
    }

    public int getState() {
        return mState;
    }

    @Override
    public void refreshComplete() {
        mHeaderTimeView.setText(friendlyTime(new Date()));
        setState(STATE_DONE);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                reset();
            }
        }, 200);
    }

    public void setVisibleHeight(int height) {
        if (height < 0) height = 0;
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
    }

    public int getVisibleHeight() {
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        return lp.height;
    }

    @Override
    public void onMove(float delta) {
        if (getVisibleHeight() > 0 || delta > 0) {
            setVisibleHeight((int) delta + getVisibleHeight());
            if (mState <= STATE_RELEASE_TO_REFRESH) { // 未处于刷新状态,更新箭头
                if (getVisibleHeight() > mMeasuredHeight) {
                    setState(STATE_RELEASE_TO_REFRESH);
                } else {
                    setState(STATE_NORMAL);
                }
            }
        }
    }

    @Override
    public boolean releaseAction() {
        boolean isOnRefresh = false;
        int height = getVisibleHeight();
        if (height == 0) // not visible.
            isOnRefresh = false;

        if (getVisibleHeight() > mMeasuredHeight && mState < STATE_REFRESHING) {
            setState(STATE_REFRESHING);
            isOnRefresh = true;
        }
        // refreshing and header isn't shown fully. do nothing.
        if (mState == STATE_REFRESHING && height <= mMeasuredHeight) {
            //return;
        }
        int destHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mState == STATE_REFRESHING) {
            destHeight = mMeasuredHeight;
        }
        smoothScrollTo(destHeight);

        return isOnRefresh;
    }

    public void reset() {
        smoothScrollTo(0);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                setState(STATE_NORMAL);
            }
        }, 500);
    }

    private void smoothScrollTo(int destHeight) {
        ValueAnimator animator = ValueAnimator.ofInt(getVisibleHeight(), destHeight);
        animator.setDuration(300).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setVisibleHeight((int) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    public String friendlyTime(Date time) {
        int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);

        if (ct == 0) {
            return mContext.getResources().getString(R.string.text_just);
        }

        if (ct > 0 && ct < 60) {
            return ct + mContext.getResources().getString(R.string.text_seconds_ago);
        }

        if (ct >= 60 && ct < 3600) {
            return Math.max(ct / 60, 1) + mContext.getResources().getString(R.string.text_minute_ago);
        }
        if (ct >= 3600 && ct < 86400)
            return ct / 3600 + mContext.getResources().getString(R.string.text_hour_ago);
        if (ct >= 86400 && ct < 2592000) { //86400 * 30
            int day = ct / 86400;
            return day + getContext().getResources().getString(R.string.text_day_ago);
        }
        if (ct >= 2592000 && ct < 31104000) { //86400 * 30
            return ct / 2592000 + mContext.getResources().getString(R.string.text_month_ago);
        }
        return ct / 31104000 + mContext.getResources().getString(R.string.text_year_ago);
    }

}


text:
layout: post

#event information
title:  "Boo At The Zoo"
cover: "/images/boo_at_the_zoo.jpg"
date:   "2016-10-21 15:30"
endDate:   "2016-10-23 20:30"
creation: "2016-09-21"
start_time: "5:30 PM"
end_time: "8:30 PM"
location:
  name: "National Zoo"
  address:
    - "3001 Connecticut Ave NW"
  city: "Washington"
  state: DC
  zip: 20008
tags: [ 'National Zoo', 'Family Events' ]
excerpt: >
  This annual tradition at the National Zoo has more than 40 treat stations,
  animal demonstrations, keeper chats, and decorated trails, this frightfully
  fun evening is a magical time for the whole family. October 21 - 23.

---

With treat stations, animal demonstrations, keeper chats, and decorated trails,
this frightfully fun evening is a treat for the whole family. An entertainment
stage will feature magicians, jugglers, and a DJ spinning Halloween favorites.
Don't miss a themed hay maze and scarecrow field.

Treat stations will include goodies for all ages, including adult treats like
craft beer and food tastings. Other treats include all the chocolate you could
desire with Twix, Snickers, Milky Way, M&Ms, Three Musketeers, and healthy
options from Benito's Chips and Honest Tea.

[Boo at the Zoo](https://nationalzoo.si.edu/events/boo-zoo) is appropriate for
children ages 4 to 12. All guests ages 2 and older, including adults, must
purchase a ticket. General Admission Tickets are $20 for members and $30 for
non-members.

Superheroes, zombies, and princesses will all enjoy:

* A commemorative Boo at the Zoo trick-or-treat bag
* 40+ treat stations
* Live entertainment
* After-hours access to animal houses and exhibits, including:
  * Small Mammal House
  * Great Ape House
  * Reptile Discovery Center
  * Think Tank
  * Great Cats Circle
  * Elephant Community Center
  * Kids Farm
  * Bird House
  * Asia Trail (David M. Rubenstein Family Giant Panda Habitat will be closed)
* Animal experiences and Zoo education stations
* Rides on the Speedwell Conservation Carousel (additional charge)


text:
namespace autofill {

AutofillType::AutofillType(ServerFieldType field_type)
    : html_type_(HTML_TYPE_UNSPECIFIED), html_mode_(HTML_MODE_NONE) {
  if ((field_type < NO_SERVER_DATA || field_type >= MAX_VALID_FIELD_TYPE) ||
      (field_type >= 15 && field_type <= 19) ||
      (field_type >= 25 && field_type <= 29) ||
      (field_type >= 44 && field_type <= 50)) {
    server_type_ = UNKNOWN_TYPE;
  } else {
    server_type_ = field_type;
  }
}

AutofillType::AutofillType(HtmlFieldType field_type, HtmlFieldMode mode)
    : server_type_(UNKNOWN_TYPE),
      html_type_(field_type),
      html_mode_(mode) {}

AutofillType::AutofillType(const AutofillType& autofill_type) {
  *this = autofill_type;
}

AutofillType& AutofillType::operator=(const AutofillType& autofill_type) {
  if (this != &autofill_type) {
    this->server_type_ = autofill_type.server_type_;
    this->html_type_ = autofill_type.html_type_;
    this->html_mode_ = autofill_type.html_mode_;
  }

  return *this;
}

FieldTypeGroup AutofillType::group() const {
  switch (server_type_) {
    case NAME_FIRST:
    case NAME_MIDDLE:
    case NAME_LAST:
    case NAME_MIDDLE_INITIAL:
    case NAME_FULL:
    case NAME_SUFFIX:
      return NAME;

    case NAME_BILLING_FIRST:
    case NAME_BILLING_MIDDLE:
    case NAME_BILLING_LAST:
    case NAME_BILLING_MIDDLE_INITIAL:
    case NAME_BILLING_FULL:
    case NAME_BILLING_SUFFIX:
      return NAME_BILLING;

    case EMAIL_ADDRESS:
    case USERNAME_AND_EMAIL_ADDRESS:
      return EMAIL;

    case PHONE_HOME_NUMBER:
    case PHONE_HOME_CITY_CODE:
    case PHONE_HOME_COUNTRY_CODE:
    case PHONE_HOME_CITY_AND_NUMBER:
    case PHONE_HOME_WHOLE_NUMBER:
    case PHONE_HOME_EXTENSION:
      return PHONE_HOME;

    case PHONE_BILLING_NUMBER:
    case PHONE_BILLING_CITY_CODE:
    case PHONE_BILLING_COUNTRY_CODE:
    case PHONE_BILLING_CITY_AND_NUMBER:
    case PHONE_BILLING_WHOLE_NUMBER:
      return PHONE_BILLING;

    case ADDRESS_HOME_LINE1:
    case ADDRESS_HOME_LINE2:
    case ADDRESS_HOME_LINE3:
    case ADDRESS_HOME_APT_NUM:
    case ADDRESS_HOME_CITY:
    case ADDRESS_HOME_STATE:
    case ADDRESS_HOME_ZIP:
    case ADDRESS_HOME_COUNTRY:
    case ADDRESS_HOME_STREET_ADDRESS:
    case ADDRESS_HOME_SORTING_CODE:
    case ADDRESS_HOME_DEPENDENT_LOCALITY:
      return ADDRESS_HOME;

    case ADDRESS_BILLING_LINE1:
    case ADDRESS_BILLING_LINE2:
    case ADDRESS_BILLING_LINE3:
    case ADDRESS_BILLING_APT_NUM:
    case ADDRESS_BILLING_CITY:
    case ADDRESS_BILLING_STATE:
    case ADDRESS_BILLING_ZIP:
    case ADDRESS_BILLING_COUNTRY:
    case ADDRESS_BILLING_STREET_ADDRESS:
    case ADDRESS_BILLING_SORTING_CODE:
    case ADDRESS_BILLING_DEPENDENT_LOCALITY:
      return ADDRESS_BILLING;

    case CREDIT_CARD_NAME_FULL:
    case CREDIT_CARD_NAME_FIRST:
    case CREDIT_CARD_NAME_LAST:
    case CREDIT_CARD_NUMBER:
    case CREDIT_CARD_EXP_MONTH:
    case CREDIT_CARD_EXP_2_DIGIT_YEAR:
    case CREDIT_CARD_EXP_4_DIGIT_YEAR:
    case CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
    case CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
    case CREDIT_CARD_TYPE:
    case CREDIT_CARD_VERIFICATION_CODE:
      return CREDIT_CARD;

    case COMPANY_NAME:
      return COMPANY;

    case PASSWORD:
    case ACCOUNT_CREATION_PASSWORD:
    case NOT_ACCOUNT_CREATION_PASSWORD:
    case NEW_PASSWORD:
    case PROBABLY_NEW_PASSWORD:
    case NOT_NEW_PASSWORD:
    case PROBABLY_ACCOUNT_CREATION_PASSWORD:
    case CONFIRMATION_PASSWORD:
      return PASSWORD_FIELD;

    case NO_SERVER_DATA:
    case EMPTY_TYPE:
    case PHONE_FAX_NUMBER:
    case PHONE_FAX_CITY_CODE:
    case PHONE_FAX_COUNTRY_CODE:
    case PHONE_FAX_CITY_AND_NUMBER:
    case PHONE_FAX_WHOLE_NUMBER:
    case FIELD_WITH_DEFAULT_VALUE:
    case MERCHANT_EMAIL_SIGNUP:
    case MERCHANT_PROMO_CODE:
      return NO_GROUP;

    case MAX_VALID_FIELD_TYPE:
      NOTREACHED();
      return NO_GROUP;

    case USERNAME:
      return USERNAME_FIELD;

    case UNKNOWN_TYPE:
      break;
  }

  switch (html_type_) {
    case HTML_TYPE_NAME:
    case HTML_TYPE_GIVEN_NAME:
    case HTML_TYPE_ADDITIONAL_NAME:
    case HTML_TYPE_ADDITIONAL_NAME_INITIAL:
    case HTML_TYPE_FAMILY_NAME:
      return html_mode_ == HTML_MODE_BILLING ? NAME_BILLING : NAME;

    case HTML_TYPE_ORGANIZATION:
      return COMPANY;

    case HTML_TYPE_STREET_ADDRESS:
    case HTML_TYPE_ADDRESS_LINE1:
    case HTML_TYPE_ADDRESS_LINE2:
    case HTML_TYPE_ADDRESS_LINE3:
    case HTML_TYPE_ADDRESS_LEVEL1:
    case HTML_TYPE_ADDRESS_LEVEL2:
    case HTML_TYPE_ADDRESS_LEVEL3:
    case HTML_TYPE_COUNTRY_CODE:
    case HTML_TYPE_COUNTRY_NAME:
    case HTML_TYPE_POSTAL_CODE:
    case HTML_TYPE_FULL_ADDRESS:
      return html_mode_ == HTML_MODE_BILLING ? ADDRESS_BILLING : ADDRESS_HOME;

    case HTML_TYPE_CREDIT_CARD_NAME_FULL:
    case HTML_TYPE_CREDIT_CARD_NAME_FIRST:
    case HTML_TYPE_CREDIT_CARD_NAME_LAST:
    case HTML_TYPE_CREDIT_CARD_NUMBER:
    case HTML_TYPE_CREDIT_CARD_EXP:
    case HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
    case HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
    case HTML_TYPE_CREDIT_CARD_EXP_MONTH:
    case HTML_TYPE_CREDIT_CARD_EXP_YEAR:
    case HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR:
    case HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR:
    case HTML_TYPE_CREDIT_CARD_VERIFICATION_CODE:
    case HTML_TYPE_CREDIT_CARD_TYPE:
      return CREDIT_CARD;

    case HTML_TYPE_TRANSACTION_AMOUNT:
    case HTML_TYPE_TRANSACTION_CURRENCY:
      return TRANSACTION;

    case HTML_TYPE_TEL:
    case HTML_TYPE_TEL_COUNTRY_CODE:
    case HTML_TYPE_TEL_NATIONAL:
    case HTML_TYPE_TEL_AREA_CODE:
    case HTML_TYPE_TEL_LOCAL:
    case HTML_TYPE_TEL_LOCAL_PREFIX:
    case HTML_TYPE_TEL_LOCAL_SUFFIX:
    case HTML_TYPE_TEL_EXTENSION:
      return html_mode_ == HTML_MODE_BILLING ? PHONE_BILLING : PHONE_HOME;

    case HTML_TYPE_EMAIL:
      return EMAIL;

    case HTML_TYPE_UNSPECIFIED:
    case HTML_TYPE_UNRECOGNIZED:
      break;
  }

  return NO_GROUP;
}

bool AutofillType::IsUnknown() const {
  return server_type_ == UNKNOWN_TYPE && (html_type_ == HTML_TYPE_UNSPECIFIED ||
                                          html_type_ == HTML_TYPE_UNRECOGNIZED);
}

ServerFieldType AutofillType::GetStorableType() const {
  // Map billing types to the equivalent non-billing types.
  switch (server_type_) {
    case ADDRESS_BILLING_LINE1:
      return ADDRESS_HOME_LINE1;

    case ADDRESS_BILLING_LINE2:
      return ADDRESS_HOME_LINE2;

    case ADDRESS_BILLING_LINE3:
      return ADDRESS_HOME_LINE3;

    case ADDRESS_BILLING_APT_NUM:
      return ADDRESS_HOME_APT_NUM;

    case ADDRESS_BILLING_CITY:
      return ADDRESS_HOME_CITY;

    case ADDRESS_BILLING_STATE:
      return ADDRESS_HOME_STATE;

    case ADDRESS_BILLING_ZIP:
      return ADDRESS_HOME_ZIP;

    case ADDRESS_BILLING_COUNTRY:
      return ADDRESS_HOME_COUNTRY;

    case PHONE_BILLING_WHOLE_NUMBER:
      return PHONE_HOME_WHOLE_NUMBER;

    case PHONE_BILLING_NUMBER:
      return PHONE_HOME_NUMBER;

    case PHONE_BILLING_CITY_CODE:
      return PHONE_HOME_CITY_CODE;

    case PHONE_BILLING_COUNTRY_CODE:
      return PHONE_HOME_COUNTRY_CODE;

    case PHONE_BILLING_CITY_AND_NUMBER:
      return PHONE_HOME_CITY_AND_NUMBER;

    case NAME_BILLING_FIRST:
      return NAME_FIRST;

    case NAME_BILLING_MIDDLE:
      return NAME_MIDDLE;

    case NAME_BILLING_LAST:
      return NAME_LAST;

    case NAME_BILLING_MIDDLE_INITIAL:
      return NAME_MIDDLE_INITIAL;

    case NAME_BILLING_FULL:
      return NAME_FULL;

    case NAME_BILLING_SUFFIX:
      return NAME_SUFFIX;

    case ADDRESS_BILLING_STREET_ADDRESS:
      return ADDRESS_HOME_STREET_ADDRESS;

    case ADDRESS_BILLING_SORTING_CODE:
      return ADDRESS_HOME_SORTING_CODE;

    case ADDRESS_BILLING_DEPENDENT_LOCALITY:
      return ADDRESS_HOME_DEPENDENT_LOCALITY;

    case UNKNOWN_TYPE:
      break;  // Try to parse HTML types instead.

    default:
      return server_type_;
  }

  switch (html_type_) {
    case HTML_TYPE_UNSPECIFIED:
      return UNKNOWN_TYPE;

    case HTML_TYPE_NAME:
      return NAME_FULL;

    case HTML_TYPE_GIVEN_NAME:
      return NAME_FIRST;

    case HTML_TYPE_ADDITIONAL_NAME:
      return NAME_MIDDLE;

    case HTML_TYPE_FAMILY_NAME:
      return NAME_LAST;

    case HTML_TYPE_ORGANIZATION:
      return COMPANY_NAME;

    case HTML_TYPE_STREET_ADDRESS:
      return ADDRESS_HOME_STREET_ADDRESS;

    case HTML_TYPE_ADDRESS_LINE1:
      return ADDRESS_HOME_LINE1;

    case HTML_TYPE_ADDRESS_LINE2:
      return ADDRESS_HOME_LINE2;

    case HTML_TYPE_ADDRESS_LINE3:
      return ADDRESS_HOME_LINE3;

    case HTML_TYPE_ADDRESS_LEVEL1:
      return ADDRESS_HOME_STATE;

    case HTML_TYPE_ADDRESS_LEVEL2:
      return ADDRESS_HOME_CITY;

    case HTML_TYPE_ADDRESS_LEVEL3:
      return ADDRESS_HOME_DEPENDENT_LOCALITY;

    case HTML_TYPE_COUNTRY_CODE:
    case HTML_TYPE_COUNTRY_NAME:
      return ADDRESS_HOME_COUNTRY;

    case HTML_TYPE_POSTAL_CODE:
      return ADDRESS_HOME_ZIP;

    // Full address is composed of other types; it can't be stored.
    case HTML_TYPE_FULL_ADDRESS:
      return UNKNOWN_TYPE;

    case HTML_TYPE_CREDIT_CARD_NAME_FULL:
      return CREDIT_CARD_NAME_FULL;

    case HTML_TYPE_CREDIT_CARD_NAME_FIRST:
      return CREDIT_CARD_NAME_FIRST;

    case HTML_TYPE_CREDIT_CARD_NAME_LAST:
      return CREDIT_CARD_NAME_LAST;

    case HTML_TYPE_CREDIT_CARD_NUMBER:
      return CREDIT_CARD_NUMBER;

    case HTML_TYPE_CREDIT_CARD_EXP:
      return CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR;

    case HTML_TYPE_CREDIT_CARD_EXP_MONTH:
      return CREDIT_CARD_EXP_MONTH;

    case HTML_TYPE_CREDIT_CARD_EXP_YEAR:
      return CREDIT_CARD_EXP_4_DIGIT_YEAR;

    case HTML_TYPE_CREDIT_CARD_VERIFICATION_CODE:
      return CREDIT_CARD_VERIFICATION_CODE;

    case HTML_TYPE_CREDIT_CARD_TYPE:
      return CREDIT_CARD_TYPE;

    case HTML_TYPE_TEL:
      return PHONE_HOME_WHOLE_NUMBER;

    case HTML_TYPE_TEL_COUNTRY_CODE:
      return PHONE_HOME_COUNTRY_CODE;

    case HTML_TYPE_TEL_NATIONAL:
      return PHONE_HOME_CITY_AND_NUMBER;

    case HTML_TYPE_TEL_AREA_CODE:
      return PHONE_HOME_CITY_CODE;

    case HTML_TYPE_TEL_LOCAL:
    case HTML_TYPE_TEL_LOCAL_PREFIX:
    case HTML_TYPE_TEL_LOCAL_SUFFIX:
      return PHONE_HOME_NUMBER;

    case HTML_TYPE_TEL_EXTENSION:
      return PHONE_HOME_EXTENSION;

    case HTML_TYPE_EMAIL:
      return EMAIL_ADDRESS;

    case HTML_TYPE_ADDITIONAL_NAME_INITIAL:
      return NAME_MIDDLE_INITIAL;

    case HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
      return CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR;

    case HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
      return CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR;

    case HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR:
      return CREDIT_CARD_EXP_2_DIGIT_YEAR;

    case HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR:
      return CREDIT_CARD_EXP_4_DIGIT_YEAR;

    // These types aren't stored; they're transient.
    case HTML_TYPE_TRANSACTION_AMOUNT:
    case HTML_TYPE_TRANSACTION_CURRENCY:
      return UNKNOWN_TYPE;

    case HTML_TYPE_UNRECOGNIZED:
      return UNKNOWN_TYPE;
  }

  NOTREACHED();
  return UNKNOWN_TYPE;
}

// static
ServerFieldType AutofillType::GetEquivalentBillingFieldType(
    ServerFieldType field_type) {
  switch (field_type) {
    case ADDRESS_HOME_LINE1:
      return ADDRESS_BILLING_LINE1;

    case ADDRESS_HOME_LINE2:
      return ADDRESS_BILLING_LINE2;

    case ADDRESS_HOME_APT_NUM:
      return ADDRESS_BILLING_APT_NUM;

    case ADDRESS_HOME_CITY:
      return ADDRESS_BILLING_CITY;

    case ADDRESS_HOME_STATE:
      return ADDRESS_BILLING_STATE;

    case ADDRESS_HOME_ZIP:
      return ADDRESS_BILLING_ZIP;

    case ADDRESS_HOME_COUNTRY:
      return ADDRESS_BILLING_COUNTRY;

    case ADDRESS_HOME_STREET_ADDRESS:
      return ADDRESS_BILLING_STREET_ADDRESS;

    case ADDRESS_HOME_SORTING_CODE:
      return ADDRESS_BILLING_SORTING_CODE;

    case ADDRESS_HOME_DEPENDENT_LOCALITY:
      return ADDRESS_BILLING_DEPENDENT_LOCALITY;

    case PHONE_HOME_WHOLE_NUMBER:
      return PHONE_BILLING_WHOLE_NUMBER;

    case PHONE_HOME_NUMBER:
      return PHONE_BILLING_NUMBER;

    case PHONE_HOME_CITY_CODE:
      return PHONE_BILLING_CITY_CODE;

    case PHONE_HOME_COUNTRY_CODE:
      return PHONE_BILLING_COUNTRY_CODE;

    case PHONE_HOME_CITY_AND_NUMBER:
      return PHONE_BILLING_CITY_AND_NUMBER;

    case NAME_FIRST:
      return NAME_BILLING_FIRST;

    case NAME_MIDDLE:
      return NAME_BILLING_MIDDLE;

    case NAME_LAST:
      return NAME_BILLING_LAST;

    case NAME_MIDDLE_INITIAL:
      return NAME_BILLING_MIDDLE_INITIAL;

    case NAME_FULL:
      return NAME_BILLING_FULL;

    case NAME_SUFFIX:
      return NAME_BILLING_SUFFIX;

    default:
      return field_type;
  }
}

std::string AutofillType::ToString() const {
  if (IsUnknown())
    return "UNKNOWN_TYPE";

  if (server_type_ != UNKNOWN_TYPE)
    return ServerFieldTypeToString(server_type_);

  switch (html_type_) {
    case HTML_TYPE_UNSPECIFIED:
      NOTREACHED();
      break;
    case HTML_TYPE_NAME:
      return "HTML_TYPE_NAME";
    case HTML_TYPE_GIVEN_NAME:
      return "HTML_TYPE_GIVEN_NAME";
    case HTML_TYPE_ADDITIONAL_NAME:
      return "HTML_TYPE_ADDITIONAL_NAME";
    case HTML_TYPE_FAMILY_NAME:
      return "HTML_TYPE_FAMILY_NAME";
    case HTML_TYPE_ORGANIZATION:
      return "HTML_TYPE_ORGANIZATION";
    case HTML_TYPE_STREET_ADDRESS:
      return "HTML_TYPE_STREET_ADDRESS";
    case HTML_TYPE_ADDRESS_LINE1:
      return "HTML_TYPE_ADDRESS_LINE1";
    case HTML_TYPE_ADDRESS_LINE2:
      return "HTML_TYPE_ADDRESS_LINE2";
    case HTML_TYPE_ADDRESS_LINE3:
      return "HTML_TYPE_ADDRESS_LINE3";
    case HTML_TYPE_ADDRESS_LEVEL1:
      return "HTML_TYPE_ADDRESS_LEVEL1";
    case HTML_TYPE_ADDRESS_LEVEL2:
      return "HTML_TYPE_ADDRESS_LEVEL2";
    case HTML_TYPE_ADDRESS_LEVEL3:
      return "HTML_TYPE_ADDRESS_LEVEL3";
    case HTML_TYPE_COUNTRY_CODE:
      return "HTML_TYPE_COUNTRY_CODE";
    case HTML_TYPE_COUNTRY_NAME:
      return "HTML_TYPE_COUNTRY_NAME";
    case HTML_TYPE_POSTAL_CODE:
      return "HTML_TYPE_POSTAL_CODE";
    case HTML_TYPE_FULL_ADDRESS:
      return "HTML_TYPE_FULL_ADDRESS";
    case HTML_TYPE_CREDIT_CARD_NAME_FULL:
      return "HTML_TYPE_CREDIT_CARD_NAME_FULL";
    case HTML_TYPE_CREDIT_CARD_NAME_FIRST:
      return "HTML_TYPE_CREDIT_CARD_NAME_FIRST";
    case HTML_TYPE_CREDIT_CARD_NAME_LAST:
      return "HTML_TYPE_CREDIT_CARD_NAME_LAST";
    case HTML_TYPE_CREDIT_CARD_NUMBER:
      return "HTML_TYPE_CREDIT_CARD_NUMBER";
    case HTML_TYPE_CREDIT_CARD_EXP:
      return "HTML_TYPE_CREDIT_CARD_EXP";
    case HTML_TYPE_CREDIT_CARD_EXP_MONTH:
      return "HTML_TYPE_CREDIT_CARD_EXP_MONTH";
    case HTML_TYPE_CREDIT_CARD_EXP_YEAR:
      return "HTML_TYPE_CREDIT_CARD_EXP_YEAR";
    case HTML_TYPE_CREDIT_CARD_VERIFICATION_CODE:
      return "HTML_TYPE_CREDIT_CARD_VERIFICATION_CODE";
    case HTML_TYPE_CREDIT_CARD_TYPE:
      return "HTML_TYPE_CREDIT_CARD_TYPE";
    case HTML_TYPE_TEL:
      return "HTML_TYPE_TEL";
    case HTML_TYPE_TEL_COUNTRY_CODE:
      return "HTML_TYPE_TEL_COUNTRY_CODE";
    case HTML_TYPE_TEL_NATIONAL:
      return "HTML_TYPE_TEL_NATIONAL";
    case HTML_TYPE_TEL_AREA_CODE:
      return "HTML_TYPE_TEL_AREA_CODE";
    case HTML_TYPE_TEL_LOCAL:
      return "HTML_TYPE_TEL_LOCAL";
    case HTML_TYPE_TEL_LOCAL_PREFIX:
      return "HTML_TYPE_TEL_LOCAL_PREFIX";
    case HTML_TYPE_TEL_LOCAL_SUFFIX:
      return "HTML_TYPE_TEL_LOCAL_SUFFIX";
    case HTML_TYPE_TEL_EXTENSION:
      return "HTML_TYPE_TEL_EXTENSION";
    case HTML_TYPE_EMAIL:
      return "HTML_TYPE_EMAIL";
    case HTML_TYPE_ADDITIONAL_NAME_INITIAL:
      return "HTML_TYPE_ADDITIONAL_NAME_INITIAL";
    case HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
      return "HTML_TYPE_CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR";
    case HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
      return "HTML_TYPE_CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR";
    case HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR:
      return "HTML_TYPE_CREDIT_CARD_EXP_2_DIGIT_YEAR";
    case HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR:
      return "HTML_TYPE_CREDIT_CARD_EXP_4_DIGIT_YEAR";
    case HTML_TYPE_TRANSACTION_AMOUNT:
      return "HTML_TRANSACTION_AMOUNT";
    case HTML_TYPE_TRANSACTION_CURRENCY:
      return "HTML_TRANSACTION_CURRENCY";
    case HTML_TYPE_UNRECOGNIZED:
      return "HTML_TYPE_UNRECOGNIZED";
  }

  NOTREACHED();
  return std::string();
}

// static
std::string AutofillType::ServerFieldTypeToString(ServerFieldType type) {
  switch (type) {
    case NO_SERVER_DATA:
      return "NO_SERVER_DATA";
    case UNKNOWN_TYPE:
      return "UNKNOWN_TYPE";
    case EMPTY_TYPE:
      return "EMPTY_TYPE";
    case NAME_FIRST:
      return "NAME_FIRST";
    case NAME_MIDDLE:
      return "NAME_MIDDLE";
    case NAME_LAST:
      return "NAME_LAST";
    case NAME_MIDDLE_INITIAL:
      return "NAME_MIDDLE_INITIAL";
    case NAME_FULL:
      return "NAME_FULL";
    case NAME_SUFFIX:
      return "NAME_SUFFIX";
    case NAME_BILLING_FIRST:
      return "NAME_BILLING_FIRST";
    case NAME_BILLING_MIDDLE:
      return "NAME_BILLING_MIDDLE";
    case NAME_BILLING_LAST:
      return "NAME_BILLING_LAST";
    case NAME_BILLING_MIDDLE_INITIAL:
      return "NAME_BILLING_MIDDLE_INITIAL";
    case NAME_BILLING_FULL:
      return "NAME_BILLING_FULL";
    case NAME_BILLING_SUFFIX:
      return "NAME_BILLING_SUFFIX";
    case EMAIL_ADDRESS:
      return "EMAIL_ADDRESS";
    case PHONE_HOME_NUMBER:
      return "PHONE_HOME_NUMBER";
    case PHONE_HOME_CITY_CODE:
      return "PHONE_HOME_CITY_CODE";
    case PHONE_HOME_COUNTRY_CODE:
      return "PHONE_HOME_COUNTRY_CODE";
    case PHONE_HOME_CITY_AND_NUMBER:
      return "PHONE_HOME_CITY_AND_NUMBER";
    case PHONE_HOME_WHOLE_NUMBER:
      return "PHONE_HOME_WHOLE_NUMBER";
    case PHONE_HOME_EXTENSION:
      return "PHONE_HOME_EXTENSION";
    case PHONE_FAX_NUMBER:
      return "PHONE_FAX_NUMBER";
    case PHONE_FAX_CITY_CODE:
      return "PHONE_FAX_CITY_CODE";
    case PHONE_FAX_COUNTRY_CODE:
      return "PHONE_FAX_COUNTRY_CODE";
    case PHONE_FAX_CITY_AND_NUMBER:
      return "PHONE_FAX_CITY_AND_NUMBER";
    case PHONE_FAX_WHOLE_NUMBER:
      return "PHONE_FAX_WHOLE_NUMBER";
    case ADDRESS_HOME_LINE1:
      return "ADDRESS_HOME_LINE1";
    case ADDRESS_HOME_LINE2:
      return "ADDRESS_HOME_LINE2";
    case ADDRESS_HOME_LINE3:
      return "ADDRESS_HOME_LINE3";
    case ADDRESS_HOME_APT_NUM:
      return "ADDRESS_HOME_APT_NUM";
    case ADDRESS_HOME_CITY:
      return "ADDRESS_HOME_CITY";
    case ADDRESS_HOME_STATE:
      return "ADDRESS_HOME_STATE";
    case ADDRESS_HOME_ZIP:
      return "ADDRESS_HOME_ZIP";
    case ADDRESS_HOME_COUNTRY:
      return "ADDRESS_HOME_COUNTRY";
    case ADDRESS_BILLING_LINE1:
      return "ADDRESS_BILLING_LINE1";
    case ADDRESS_BILLING_LINE2:
      return "ADDRESS_BILLING_LINE2";
    case ADDRESS_BILLING_LINE3:
      return "ADDRESS_BILLING_LINE3";
    case ADDRESS_BILLING_APT_NUM:
      return "ADDRESS_BILLING_APT_NUM";
    case ADDRESS_BILLING_CITY:
      return "ADDRESS_BILLING_CITY";
    case ADDRESS_BILLING_STATE:
      return "ADDRESS_BILLING_STATE";
    case ADDRESS_BILLING_ZIP:
      return "ADDRESS_BILLING_ZIP";
    case ADDRESS_BILLING_COUNTRY:
      return "ADDRESS_BILLING_COUNTRY";
    case CREDIT_CARD_NAME_FULL:
      return "CREDIT_CARD_NAME_FULL";
    case CREDIT_CARD_NAME_FIRST:
      return "CREDIT_CARD_NAME_FIRST";
    case CREDIT_CARD_NAME_LAST:
      return "CREDIT_CARD_NAME_LAST";
    case CREDIT_CARD_NUMBER:
      return "CREDIT_CARD_NUMBER";
    case CREDIT_CARD_EXP_MONTH:
      return "CREDIT_CARD_EXP_MONTH";
    case CREDIT_CARD_EXP_2_DIGIT_YEAR:
      return "CREDIT_CARD_EXP_2_DIGIT_YEAR";
    case CREDIT_CARD_EXP_4_DIGIT_YEAR:
      return "CREDIT_CARD_EXP_4_DIGIT_YEAR";
    case CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR:
      return "CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR";
    case CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR:
      return "CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR";
    case CREDIT_CARD_TYPE:
      return "CREDIT_CARD_TYPE";
    case CREDIT_CARD_VERIFICATION_CODE:
      return "CREDIT_CARD_VERIFICATION_CODE";
    case COMPANY_NAME:
      return "COMPANY_NAME";
    case FIELD_WITH_DEFAULT_VALUE:
      return "FIELD_WITH_DEFAULT_VALUE";
    case PHONE_BILLING_NUMBER:
      return "PHONE_BILLING_NUMBER";
    case PHONE_BILLING_CITY_CODE:
      return "PHONE_BILLING_CITY_CODE";
    case PHONE_BILLING_COUNTRY_CODE:
      return "PHONE_BILLING_COUNTRY_CODE";
    case PHONE_BILLING_CITY_AND_NUMBER:
      return "PHONE_BILLING_CITY_AND_NUMBER";
    case PHONE_BILLING_WHOLE_NUMBER:
      return "PHONE_BILLING_WHOLE_NUMBER";
    case MERCHANT_EMAIL_SIGNUP:
      return "MERCHANT_EMAIL_SIGNUP";
    case MERCHANT_PROMO_CODE:
      return "MERCHANT_PROMO_CODE";
    case PASSWORD:
      return "PASSWORD";
    case ACCOUNT_CREATION_PASSWORD:
      return "ACCOUNT_CREATION_PASSWORD";
    case ADDRESS_HOME_STREET_ADDRESS:
      return "ADDRESS_HOME_STREET_ADDRESS";
    case ADDRESS_BILLING_STREET_ADDRESS:
      return "ADDRESS_BILLING_STREET_ADDRESS";
    case ADDRESS_HOME_SORTING_CODE:
      return "ADDRESS_HOME_SORTING_CODE";
    case ADDRESS_BILLING_SORTING_CODE:
      return "ADDRESS_BILLING_SORTING_CODE";
    case ADDRESS_HOME_DEPENDENT_LOCALITY:
      return "ADDRESS_HOME_DEPENDENT_LOCALITY";
    case ADDRESS_BILLING_DEPENDENT_LOCALITY:
      return "ADDRESS_BILLING_DEPENDENT_LOCALITY";
    case NOT_ACCOUNT_CREATION_PASSWORD:
      return "NOT_ACCOUNT_CREATION_PASSWORD";
    case USERNAME:
      return "USERNAME";
    case USERNAME_AND_EMAIL_ADDRESS:
      return "USERNAME_AND_EMAIL_ADDRESS";
    case NEW_PASSWORD:
      return "NEW_PASSWORD";
    case PROBABLY_NEW_PASSWORD:
      return "PROBABLY_NEW_PASSWORD";
    case NOT_NEW_PASSWORD:
      return "NOT_NEW_PASSWORD";
    case PROBABLY_ACCOUNT_CREATION_PASSWORD:
      return "PROBABLY_ACCOUNT_CREATION_PASSWORD";
    case CONFIRMATION_PASSWORD:
      return "CONFIRMATION_PASSWORD";

    case MAX_VALID_FIELD_TYPE:
      return std::string();
  }

  NOTREACHED();
  return std::string();
}

}  // namespace autofill


text:
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">

	<title></title>

Review & Feedback

Psychologists believe the test you just took measures how reflective and open-minded someone is, particularly when dealing with information that conflicts with their interests or beliefs. In one recent study, a researcher found that  tended to have scores that implied they were less open-minded than . How strongly do you agree or disagree with the following statement?

I think the test I just took supplies good evidence of how reflective and open-minded someone is.

			Strongly disagree
			Moderately disagree
			Slightly disagree
			Slightly agree
			Moderately agree
			Strongly agree

			<input name="subOpinion" type="radio" value="Strongly disagree" />
			<input name="subOpinion" type="radio" value="Moderately disagree" />
			<input name="subOpinion" type="radio" value="Slightly disagree" />
			<input name="subOpinion" type="radio" value="Slightly agree" />
			<input name="subOpinion" type="radio" value="Moderately agree" />
			<input name="subOpinion" type="radio" value="Strongly agree" />

Please provide any feedback you have on the survey or test in the space below (optional).  If you have not done so previously, you may provide your email address if you'd like a write-up explaining your test results.

<input id="emailID" name="emailID" style="width:600px" type="text" />

<input onclick="checkAndPostSurvey();" type="submit" value="Submit Survey" />


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// Copyright (c) 1996-2016 Live Networks, Inc.  All rights reserved.
// Basic Usage Environment: for a simple, non-scripted, console application
// Implementation

#include "BasicUsageEnvironment0.hh"
#include <stdio.h>
#if defined(__WIN32__) || defined(_WIN32) || defined(_WIN32_WCE)
#define snprintf _snprintf
#endif

////////// BasicUsageEnvironment //////////

BasicUsageEnvironment0::BasicUsageEnvironment0(TaskScheduler& taskScheduler)
  : UsageEnvironment(taskScheduler),
    fBufferMaxSize(RESULT_MSG_BUFFER_MAX) {
  reset();
}

BasicUsageEnvironment0::~BasicUsageEnvironment0() {
}

void BasicUsageEnvironment0::reset() {
  fCurBufferSize = 0;
  fResultMsgBuffer[fCurBufferSize] = '\0';
}

// Implementation of virtual functions:

char const* BasicUsageEnvironment0::getResultMsg() const {
  return fResultMsgBuffer;
}

void BasicUsageEnvironment0::setResultMsg(MsgString msg) {
  reset();
  appendToResultMsg(msg);
}

void BasicUsageEnvironment0::setResultMsg(MsgString msg1, MsgString msg2) {
  setResultMsg(msg1);
  appendToResultMsg(msg2);
}

void BasicUsageEnvironment0::setResultMsg(MsgString msg1, MsgString msg2,
				       MsgString msg3) {
  setResultMsg(msg1, msg2);
  appendToResultMsg(msg3);
}

void BasicUsageEnvironment0::setResultErrMsg(MsgString msg, int err) {
  setResultMsg(msg);

  if (err == 0) err = getErrno();
#if defined(__WIN32__) || defined(_WIN32) || defined(_WIN32_WCE)
  char errMsg[RESULT_MSG_BUFFER_MAX] = "\0";
  if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, errMsg, sizeof(errMsg)/sizeof(errMsg[0]), NULL)) {
    // Remove all trailing '\r', '\n' and '.'
    for (char* p = errMsg + strlen(errMsg); p != errMsg && (*p == '\r' || *p == '\n' || *p == '.' || *p == '\0'); --p) {
      *p = '\0';
    }
  } else
    snprintf(errMsg, sizeof(errMsg)/sizeof(errMsg[0]), "error %d", err);
  appendToResultMsg(errMsg);
#else
  appendToResultMsg(strerror(err));
#endif
}

void BasicUsageEnvironment0::appendToResultMsg(MsgString msg) {
  char* curPtr = &fResultMsgBuffer[fCurBufferSize];
  unsigned spaceAvailable = fBufferMaxSize - fCurBufferSize;
  unsigned msgLength = strlen(msg);

  // Copy only enough of "msg" as will fit:
  if (msgLength > spaceAvailable-1) {
    msgLength = spaceAvailable-1;
  }

  memmove(curPtr, (char*)msg, msgLength);
  fCurBufferSize += msgLength;
  fResultMsgBuffer[fCurBufferSize] = '\0';
}

void BasicUsageEnvironment0::reportBackgroundError() {
  fputs(getResultMsg(), stderr);
}


text:
package org.apache.geode.internal;

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

/**
 * Interface to implement if your class supports sending itself directly to a DataOutput during
 * serialization. Note that you are responsible for sending all the bytes that represent your
 * instance, even bytes describing your class name if those are required.
 *
 * @since GemFire 6.6
 */
public interface Sendable {
  /**
   * Take all the bytes in the object and write them to the data output. It needs to be written in
   * the GemFire wire format so that it will deserialize correctly if DataSerializer.readObject is
   * called.
   *
   * @param out the data output to send this object to
   * @throws IOException
   */
  void sendTo(DataOutput out) throws IOException;
}


text:
package com.focusti.cervejaria.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.focusti.cervejaria.controller.page.PageWrapper;
import com.focusti.cervejaria.dto.CervejaDTO;
import com.focusti.cervejaria.model.Cerveja;
import com.focusti.cervejaria.model.constants.Origem;
import com.focusti.cervejaria.model.constants.Sabor;
import com.focusti.cervejaria.repository.Cervejas;
import com.focusti.cervejaria.repository.Estilos;
import com.focusti.cervejaria.repository.filter.CervejaFilter;
import com.focusti.cervejaria.service.CervejaService;
import com.focusti.cervejaria.service.exception.ImpossivelExcluirEntidadeException;

@Controller
@RequestMapping("/cervejas")
public class CervejasController {

	private static final String CADASTRO_CERVEJA_VIEW = "cerveja/CadastroCerveja";

	@Autowired
	private CervejaService cervejaService;

	@Autowired
	private Estilos estilos;

	@Autowired
	private Cervejas cervejas;

	@GetMapping("/nova")
	public ModelAndView nova(Cerveja cerveja) {

		ModelAndView mv = new ModelAndView(CADASTRO_CERVEJA_VIEW);
		mv.addObject("sabores", Sabor.values());
		mv.addObject("origens", Origem.values());
		mv.addObject("estilos", estilos.listar());
		return mv;
	}

	@PostMapping
	public ModelAndView salvar(@Valid Cerveja cerveja, BindingResult result, RedirectAttributes attributes) {

		if (result.hasErrors()) {
			return nova(cerveja);
		}

		cervejaService.salvar(cerveja);
		attributes.addFlashAttribute("mensagem", "Cerveja salva com sucesso");

		return new ModelAndView("redirect:/cervejas/nova");
	}

	@GetMapping
	public ModelAndView pesquisar(CervejaFilter cervejaFilter, @PageableDefault(size = 2) Pageable pageable,
			HttpServletRequest httpServletRequest) {

		ModelAndView mv = new ModelAndView("cerveja/PesquisaCerveja");

		mv.addObject("estilos", estilos.listar());
		mv.addObject("sabores", Sabor.values());
		mv.addObject("origens", Origem.values());

		Page<Cerveja> pagina = cervejas.filtar(cervejaFilter, pageable);
		PageWrapper<Cerveja> pageWrapper = new PageWrapper<>(pagina, httpServletRequest);

		mv.addObject("pagina", pageWrapper);

		return mv;
	}

	@GetMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody List<CervejaDTO> pesquisar(String skuOuNome) {
		return cervejas.porSkuOuNome(skuOuNome);
	}

	@DeleteMapping("/{codigo}")
	public @ResponseBody ResponseEntity<?> excluir( @PathVariable Long codigo ) {

		try {
			cervejaService.excluir(codigo);
		} catch (ImpossivelExcluirEntidadeException e) {
			return ResponseEntity.badRequest().body(e.getMessage());
		}

		return ResponseEntity.ok().build();
	}

	@GetMapping("/{codigo}")
	public ModelAndView editar( @PathVariable("codigo") Cerveja cerveja ) {
		ModelAndView mv = nova(cerveja);
		mv.addObject(cerveja);
		return mv;
	}

}


text:
using System;
using System.Reactive.Linq;
using RfxCom.Events;

namespace RfxCom.Messages
{
    public static class ObservableExtensions
    {

        public static IObservable<MessageReceived<T>> MessagesOf<T>(this IObservable<Event> observable) where T : Message
        {
            return
                observable.Where(@event => @event is MessageReceived<T>)
                    .Cast<MessageReceived<T>>();
        }
    }
}


text:
package com.herokuapp.soliduxample.solidus.views;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.herokuapp.soliduxample.solidus.R;
import com.herokuapp.soliduxample.solidus.api.Config;
import com.herokuapp.soliduxample.solidus.app.Constants;
import com.herokuapp.soliduxample.solidus.models.Classification;
import com.herokuapp.soliduxample.solidus.models.Image;
import com.herokuapp.soliduxample.solidus.models.Product;
import com.herokuapp.soliduxample.solidus.models.ProductProperty;
import com.herokuapp.soliduxample.solidus.models.Variant;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by Roberto Morelos on 3/6/17.
 * This activity displays the detailed information of one product.
 */
public class ProductDetails extends AppCompatActivity {
    private static final String TAG = ProductDetails.class.getSimpleName();
    private ImageView ivProduct;
    private LinearLayout llProperties;
    private TableLayout tlTableProperties;
    private TextView tvName;
    private TextView tvDescription;
    private LinearLayout llVariants;
    private RadioGroup rgVariants;
    private TextView tvPrice;
    private LinearLayout llSimilar;
    private LinearLayout llMainSimilar;
    private ProgressBar progressBar;

    private Product product;

    /**
     * Method inherited from AppCompatActivity.
     * Initialize all the components here.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //We set link the view with the activity
        setContentView(R.layout.activity_product_details);
        //find all the views we will use and assign them to objects
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        ivProduct = (ImageView) findViewById(R.id.activity_product_details_ivProduct);
        llProperties = (LinearLayout) findViewById(R.id.activity_product_details_llProperties);
        tlTableProperties = (TableLayout) findViewById(R.id.activity_product_details_tlTableProperties);
        tvName = (TextView) findViewById(R.id.activity_product_details_tvName);
        tvDescription = (TextView) findViewById(R.id.activity_product_details_tvDescription);
        llVariants = (LinearLayout) findViewById(R.id.activity_product_details_llVariants);
        rgVariants = (RadioGroup) findViewById(R.id.activity_product_details_rgVariants);
        tvPrice = (TextView) findViewById(R.id.activity_product_details_tvPrice);
        llSimilar = (LinearLayout) findViewById(R.id.activity_product_details_llSimilar);
        llMainSimilar = (LinearLayout) findViewById(R.id.activity_product_details_llMainSimilar);
        progressBar = (ProgressBar) findViewById(R.id.activity_product_details_pbProgressBar);

        //obtain the object passed from the previous Activity
        product = (Product) getIntent().getSerializableExtra(Constants.PRODUCT);

        //set the toolbar as action bar
        setSupportActionBar(toolbar);
        //if action bar is not null set it with the back arrow
        if (null != getSupportActionBar()){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        //load the content in the views
        loadContent();
    }

    /**
     * Set the information in the views.
     */
    public void loadContent(){
        //show the progress in the image view
        showProgress();
        //get the images from the product object
        List<Image> images = product.getMaster().getImages();
        //if there are images then load the first one into the image view using Picasso
        if (images.size() > 0){
            String imageURL = Config.MAIN_URL + images.get(0).getProductUrl();
            Picasso.with(this).load(imageURL).fit().error(R.drawable.product_not_available).into(ivProduct, new Callback() {
                @Override
                public void onSuccess() {
                    hideProgress();
                }

                @Override
                public void onError() {
                    hideProgress();
                }
            });
        }else{
            //there are not images available, so show a default one
            Picasso.with(this).load(R.drawable.product_not_available).fit().into(ivProduct, new Callback() {
                @Override
                public void onSuccess() {
                    hideProgress();
                }

                @Override
                public void onError() {
                    hideProgress();
                }
            });
        }

        //set the product name
        tvName.setText(product.getName());
        //set the product price
        tvPrice.setText(product.getDisplayPrice());

        //obtain the product description
        String description = product.getDescription();
        //if the description is not null then make visible the view and display it in there, otherwise hide the view
        if (null != description){
            tvDescription.setVisibility(View.VISIBLE);
            tvDescription.setText(description);
        }else{
            tvDescription.setVisibility(View.GONE);
        }

        //if the product has variants then make the view visible and add radio buttons for each variant, otherwise hide the view
        if (product.getHasVariants()){
            llVariants.setVisibility(View.VISIBLE);

            for (Variant variant: product.getVariants()) {
                RadioButton newRadioButton = new RadioButton(this);
                newRadioButton.setText(variant.getName());
                newRadioButton.setId(variant.getId());
                LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                        RadioGroup.LayoutParams.WRAP_CONTENT,
                        RadioGroup.LayoutParams.WRAP_CONTENT);
                rgVariants.addView(newRadioButton, 0, layoutParams);
            }
        }else{
            llVariants.setVisibility(View.GONE);
        }

        //get a list of properties
        List<ProductProperty> productProperties = product.getProductProperties();
        //if the product has properties then make the view visible and add rows to the view for each property, otherwise hide the view
        if (productProperties.size()>0){
            llProperties.setVisibility(View.VISIBLE);
            for (ProductProperty productProperty: productProperties) {
                @SuppressLint("InflateParams") TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.table_row_properties, null);
                ((TextView)row.findViewById(R.id.table_row_properties_tvTitle)).setText(productProperty.getPropertyName());
                ((TextView)row.findViewById(R.id.table_row_properties_tvDescription)).setText(productProperty.getValue());
                tlTableProperties.addView(row);
            }
        }else{
            llProperties.setVisibility(View.GONE);
        }

        //get a list of classifications
        List<Classification> classifications = product.getClassifications();
        //if the product has classifications then make the view visible and add text views to the view for each classification, otherwise hide the view
        if (classifications.size()>0){
            llMainSimilar.setVisibility(View.VISIBLE);
            for (Classification classification: classifications) {
                TextView newTextView = new TextView(this);
                newTextView.setText(classification.getTaxon().getName());
                newTextView.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
                LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                        RadioGroup.LayoutParams.WRAP_CONTENT,
                        RadioGroup.LayoutParams.WRAP_CONTENT);
                llSimilar.addView(newTextView, 0, layoutParams);
            }
        }else{
            llMainSimilar.setVisibility(View.GONE);
        }
    }

    /**
     * Method inherited from AppCompatActivity.
     * If user presses the back arrow, then return to previous Activity.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Show the progress bar in the picture
     */
    public void showProgress(){
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * Hide the progress bar in the picture
     */
    public void hideProgress(){
        progressBar.setVisibility(View.GONE);
    }

}


text:
"use strict";

exports.__esModule = true;
exports.default = void 0;

var Platform = {
  OS: 'web',
  select: function select(obj) {
    return 'web' in obj ? obj.web : obj.default;
  },

  get isTesting() {
    if (process.env.NODE_ENV === 'test') {
      return true;
    }

    return false;
  }

};
var _default = Platform;
exports.default = _default;
module.exports = exports.default;


text:
package blockchain

import (
	"fmt"
)

// NotificationType represents the type of a notification message.
type NotificationType int

// NotificationCallback is used for a caller to provide a callback for
// notifications about various chain events.
type NotificationCallback func(*Notification)

// Constants for the type of a notification message.
const (
	// NTBlockAccepted indicates the associated block was accepted into
	// the block chain.  Note that this does not necessarily mean it was
	// added to the main chain.  For that, use NTBlockConnected.
	NTBlockAccepted NotificationType = iota

	// NTBlockConnected indicates the associated block was connected to the
	// main chain.
	NTBlockConnected

	// NTBlockDisconnected indicates the associated block was disconnected
	// from the main chain.
	NTBlockDisconnected
)

// notificationTypeStrings is a map of notification types back to their constant
// names for pretty printing.
var notificationTypeStrings = map[NotificationType]string{
	NTBlockAccepted:     "NTBlockAccepted",
	NTBlockConnected:    "NTBlockConnected",
	NTBlockDisconnected: "NTBlockDisconnected",
}

// String returns the NotificationType in human-readable form.
func (n NotificationType) String() string {
	if s, ok := notificationTypeStrings[n]; ok {
		return s
	}
	return fmt.Sprintf("Unknown Notification Type (%d)", int(n))
}

// Notification defines notification that is sent to the caller via the callback
// function provided during the call to New and consists of a notification type
// as well as associated data that depends on the type as follows:
// 	- NTBlockAccepted:     *btcutil.Block
// 	- NTBlockConnected:    *btcutil.Block
// 	- NTBlockDisconnected: *btcutil.Block
type Notification struct {
	Type NotificationType
	Data interface{}
}

// sendNotification sends a notification with the passed type and data if the
// caller requested notifications by providing a callback function in the call
// to New.
func (b *BlockChain) sendNotification(typ NotificationType, data interface{}) {
	// Ignore it if the caller didn't request notifications.
	if b.notifications == nil {
		return
	}

	// Generate and send the notification.
	n := Notification{Type: typ, Data: data}
	b.notifications(&n)
}


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

public class Laser : MonoBehaviour {
	private const float _LOCALSCALE = 0.9127775f;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

	void OnCollisionStay2D(Collision2D other) {
		if(other.gameObject.tag == "Cube"){
			transform.localScale = new Vector3(1,Vector2.Distance(other.gameObject.transform.position,transform.position)/2,1);

		}
	}

	void OnCollisionExit2D(Collision2D other) {
		if(other.gameObject.tag == "Cube"){
			transform.localScale = new Vector3(1,_LOCALSCALE,1);
		}
	}

	public void PowerOn() {
		transform.localScale = new Vector3(1,_LOCALSCALE,1);
	}

	public void PowerOff() {
		transform.localScale = new Vector3(1,0,1);
	}
}


text:
#ifndef ZORBA_SERIALIZATION_CALLBACK_H
#define ZORBA_SERIALIZATION_CALLBACK_H

#include <zorba/config.h>
#include <zorba/api_shared_types.h>
#include <ostream>

namespace zorba {

  class ZORBA_DLL_PUBLIC SerializationCallback {

    public:
      virtual ~SerializationCallback() {}

      virtual ExternalModule*
      getExternalModule(const String& aURI) const;

      virtual bool
      getTraceStream(std::ostream*&) const;

      /**
       * Get the i-th URIMapper that was registered before
       * serialization.
       */
      virtual URIMapper*
      getURIMapper(size_t i) const;

      /**
       * Get the i-th URLResolver that was registered before
       * serialization.
       */
      virtual URLResolver*
      getURLResolver(size_t i) const;
  };

} /* namespace zorba */

#endif
/* vim:set et sw=2 ts=2: */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.communote.server.web.fe.admin.AdministrationMenuEntryDetails (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.communote.server.web.fe.admin.AdministrationMenuEntryDetails

Packages that use AdministrationMenuEntryDetails

Package
Description

com.communote.server.web.commons.viewtool

com.communote.server.web.fe.admin

Uses of AdministrationMenuEntryDetails in com.communote.server.web.commons.viewtool

Methods in com.communote.server.web.commons.viewtool that return AdministrationMenuEntryDetails

Modifier and Type
Method and Description

AdministrationMenuEntryDetails
AdministrationTool.getCurrentMenuEntry(javax.servlet.http.HttpServletRequest request)

Delegates to AdministrationMenuManager.getCurrentEntry(HttpServletRequest)

Uses of AdministrationMenuEntryDetails in com.communote.server.web.fe.admin

Methods in com.communote.server.web.fe.admin that return AdministrationMenuEntryDetails

Modifier and Type
Method and Description

AdministrationMenuEntryDetails
AdministrationMenuManager.getCurrentEntry(javax.servlet.http.HttpServletRequest request)

Return the entry that belongs to the current request.

AdministrationMenuEntryDetails
AdministrationMenuManager.getEntry(String categoryId,
        String entryId)

Get an entry of a given category.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2019 Communote team. All rights reserved.


text:
namespace SolidEdgeSpy.Forms
{
    partial class CommandBrowser
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.listViewEx = new SolidEdgeSpy.Forms.ListViewEx();
            this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
            this.toolStrip2 = new System.Windows.Forms.ToolStrip();
            this.buttonStart = new System.Windows.Forms.ToolStripButton();
            this.textBoxCommandID = new System.Windows.Forms.ToolStripTextBox();
            this.labelCommandID = new System.Windows.Forms.ToolStripLabel();
            this.textBoxSearch = new SolidEdgeSpy.Forms.ToolStripSpringTextBox();
            this.buttonSearch = new System.Windows.Forms.ToolStripButton();
            this.buttonClearSearch = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.toolStrip2.SuspendLayout();
            this.SuspendLayout();
            //
            // listViewEx
            //
            this.listViewEx.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.columnHeader5,
            this.columnHeader6,
            this.columnHeader7});
            this.listViewEx.Dock = System.Windows.Forms.DockStyle.Fill;
            this.listViewEx.FullRowSelect = true;
            this.listViewEx.HideSelection = false;
            this.listViewEx.Location = new System.Drawing.Point(0, 25);
            this.listViewEx.Name = "listViewEx";
            this.listViewEx.Size = new System.Drawing.Size(469, 292);
            this.listViewEx.TabIndex = 7;
            this.listViewEx.UseCompatibleStateImageBehavior = false;
            this.listViewEx.View = System.Windows.Forms.View.Details;
            this.listViewEx.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.listViewEx_ItemSelectionChanged);
            //
            // columnHeader5
            //
            this.columnHeader5.Text = "Command";
            //
            // columnHeader6
            //
            this.columnHeader6.Text = "ID";
            //
            // columnHeader7
            //
            this.columnHeader7.Text = "Type";
            //
            // toolStrip2
            //
            this.toolStrip2.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
            this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.buttonStart,
            this.textBoxCommandID,
            this.labelCommandID,
            this.textBoxSearch,
            this.buttonSearch,
            this.buttonClearSearch,
            this.toolStripSeparator1});
            this.toolStrip2.Location = new System.Drawing.Point(0, 0);
            this.toolStrip2.Name = "toolStrip2";
            this.toolStrip2.Size = new System.Drawing.Size(469, 25);
            this.toolStrip2.TabIndex = 6;
            this.toolStrip2.Text = "toolStrip2";
            //
            // buttonStart
            //
            this.buttonStart.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
            this.buttonStart.Image = global::SolidEdgeSpy.Properties.Resources.Start_16x16;
            this.buttonStart.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(111, 22);
            this.buttonStart.Text = "Start Command";
            this.buttonStart.ToolTipText = "Start Command";
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            //
            // textBoxCommandID
            //
            this.textBoxCommandID.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
            this.textBoxCommandID.Name = "textBoxCommandID";
            this.textBoxCommandID.Size = new System.Drawing.Size(75, 25);
            this.textBoxCommandID.TextChanged += new System.EventHandler(this.textBoxCommandID_TextChanged);
            //
            // labelCommandID
            //
            this.labelCommandID.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
            this.labelCommandID.Name = "labelCommandID";
            this.labelCommandID.Size = new System.Drawing.Size(78, 22);
            this.labelCommandID.Text = "Command ID";
            //
            // textBoxSearch
            //
            this.textBoxSearch.InactiveText = "<Search>";
            this.textBoxSearch.Name = "textBoxSearch";
            this.textBoxSearch.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
            this.textBoxSearch.Size = new System.Drawing.Size(100, 25);
            this.textBoxSearch.TextAccepted += new System.EventHandler(this.textBoxSearch_TextAccepted);
            //
            // buttonSearch
            //
            this.buttonSearch.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.buttonSearch.Image = global::SolidEdgeSpy.Properties.Resources.Find_16x16;
            this.buttonSearch.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.buttonSearch.Name = "buttonSearch";
            this.buttonSearch.Size = new System.Drawing.Size(23, 22);
            this.buttonSearch.Text = "Search";
            this.buttonSearch.Click += new System.EventHandler(this.buttonSearch_Click);
            //
            // buttonClearSearch
            //
            this.buttonClearSearch.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.buttonClearSearch.Image = global::SolidEdgeSpy.Properties.Resources.ClearSearch_16x16;
            this.buttonClearSearch.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.buttonClearSearch.Name = "buttonClearSearch";
            this.buttonClearSearch.Size = new System.Drawing.Size(23, 22);
            this.buttonClearSearch.Text = "Clear Search";
            this.buttonClearSearch.Click += new System.EventHandler(this.buttonClearSearch_Click);
            //
            // toolStripSeparator1
            //
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
            //
            // CommandBrowser
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.listViewEx);
            this.Controls.Add(this.toolStrip2);
            this.Name = "CommandBrowser";
            this.Size = new System.Drawing.Size(469, 317);
            this.toolStrip2.ResumeLayout(false);
            this.toolStrip2.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private ListViewEx listViewEx;
        private System.Windows.Forms.ColumnHeader columnHeader5;
        private System.Windows.Forms.ColumnHeader columnHeader6;
        private System.Windows.Forms.ColumnHeader columnHeader7;
        private System.Windows.Forms.ToolStrip toolStrip2;
        private System.Windows.Forms.ToolStripButton buttonStart;
        private System.Windows.Forms.ToolStripTextBox textBoxCommandID;
        private System.Windows.Forms.ToolStripLabel labelCommandID;
        private ToolStripSpringTextBox textBoxSearch;
        private System.Windows.Forms.ToolStripButton buttonSearch;
        private System.Windows.Forms.ToolStripButton buttonClearSearch;
        private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
    }
}


text:
var should = require('should');
var request = require('supertest');

var uri = 'localhost:3000';
describe('user controller', function () {
    it('should get the registration page', function (done) {
        request(uri)
            .get('/signup')
            .end(function (err, res) {
                     should(err).eql(null);
                     console.log(res);
                     res.should.have.status(200);
                     done();
                 });
    });

    it('should try to create a new user', function (done) {
        var data = {email: 'test@test.com',
            password     : 'asdf',
            confirm      : 'asdf'};
        request(uri)
            .post('/signup')
            .send(data)
            .end(function (err, res) {
                     should(err).eql(null);
                     res.should.have.status(200);
                     done();
                 })
    });

    it('should try to create the same user', function (done) {
        var data = {email: 'test@test.com',
            password     : 'asdf',
            confirm      : 'asdf'};
        request(uri)
            .post('/signup')
            .send(data)
            .end(function (err, res) {
                     should(err).not.ok;
                     res.should.have.status(200);
                     done();
                 })
    });

    it('should try to login', function (done) {
        var data = {email: 'test@test.com',
            password     : 'asdf'};
        request(uri)
            .post('/login')
            .send(data)
            .end(function (err, res) {
                     should(err).eql(null);
                     res.should.have.status(200);
                     done();
                 })
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<vector android:tint="?android:colorControlNormal" android:height="24.0dip" android:width="24.0dip" android:viewportWidth="24.0" android:viewportHeight="24.0"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#ffffffff" android:pathData="M23,1v22H1V1H23 M24,0H0v24h24V0L24,0z" />
    <path android:pathData="M5,19L1,23" android:strokeColor="#ffffffff" android:strokeWidth="0.667" />
    <path android:pathData="M1,1L5,5" android:strokeColor="#ffffffff" android:strokeWidth="0.667" />
    <path android:pathData="M19,5L23,1" android:strokeColor="#ffffffff" android:strokeWidth="0.667" />
    <path android:pathData="M19,19L23,23" android:strokeColor="#ffffffff" android:strokeWidth="0.667" />
    <path android:fillColor="#ffffffff" android:pathData="M14,3.8l-4,0l-0.2,-0.8l4.4,0z" />
    <path android:fillColor="#ffffffff" android:pathData="M18.8,5.2v13.5H5.2V5.2H18.8 M19.5,4.5h-15v15h15V4.5L19.5,4.5z" />
    <path android:fillColor="#ffffffff" android:pathData="M6.5,9.5h5v11h-5z" />
    <path android:fillColor="#ffffffff" android:pathData="M12.5,16.5h5v5h-5z" />
</vector>


text:
int retry_port_ = 0;
#endif

My_Accept_Handler::My_Accept_Handler (ACE_INET_Addr &addr)
  : addr_ (addr)
{
  if (addr.get_port_number() != 0)
    this->open (addr);
}

My_Accept_Handler::~My_Accept_Handler ()
{
  this->peer_acceptor_.close ();     // Prevent handle leaks
}

int
My_Accept_Handler::open (ACE_INET_Addr &addr)
{

  if (this->peer_acceptor_.open (addr, 1) == -1)
  {
     ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"),
                 ACE_TEXT ("My_Accept_Handler open")));
     ACE_OS::exit (1);
  }

  return 0;

}

ACE_HANDLE
My_Accept_Handler::get_handle () const
{
  return this->peer_acceptor_.get_handle ();
}

int
My_Accept_Handler::handle_input (ACE_HANDLE)
{

  if (this->peer_acceptor_.accept(this->stream_, 0) == -1) {
    ACE_ERROR((LM_ERROR, ACE_TEXT ("%p\n"),
               ACE_TEXT ("peer_acceptor.accept")));
    ACE_OS::exit(1);
  }

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("My_Accept_Handler::handle_input\n")));

  // Close the opened stream, else it'll leak a handle. Don't close
  // the acceptor here, though, because get_handle() needs it to
  // correctly allow removal from the reactor later. It gets closed
  // in the destructor.
  this->stream_.close ();

  return 0;
}

u_short
My_Accept_Handler::port ()
{
  return this->addr_.get_port_number();
}

long max_connected_port = 0;

static void *
client (void *arg)
{
  ACE_INET_Addr *remote_addr = reinterpret_cast<ACE_INET_Addr *> (arg);

  ACE_INET_Addr server_addr (remote_addr->get_port_number (),
                             ACE_LOCALHOST,
                             AF_INET);

  ACE_SOCK_Stream cli_stream;
  ACE_SOCK_Connector con;
  ACE_Time_Value timeout (ACE_DEFAULT_TIMEOUT);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) Connecting to port %d\n"),
              server_addr.get_port_number()));

  // Initiate connection with server; don't wait forever
  if (con.connect (cli_stream,
                   server_addr,
                   &timeout) == -1)
    {
#if defined (ACE_VXWORKS)
      if (errno == ETIME)
        {
          if ( ++retry_port_<6 )
          {
            ACE_DEBUG ((LM_DEBUG,
                        ACE_TEXT ("(%P|%t) Going to retry port %d\n"),
                        server_addr.get_port_number()));
          }
        }
      if ( retry_port_>5 )
        {
          retry_port_ = 0;
#endif
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) %p\n"),
                      ACE_TEXT ("connection failed")));

#if defined (ACE_VXWORKS)
        }
#endif
      return 0;
    }

#if defined (ACE_VXWORKS)
  retry_port_ = 0;
#endif

  // if connect succesful, what is the max port number we connected
  // up to now.
  int connected_port = server_addr.get_port_number ();

  if (connected_port > max_connected_port)
    max_connected_port = connected_port;

  cli_stream.close ();

  return 0;
}

int
run_main (int argc, ACE_TCHAR *argv[])
{

  ACE_START_TEST (ACE_TEXT ("Max_Default_Port_Test"));

  ACE_UNUSED_ARG (argc);
  ACE_UNUSED_ARG (argv);

  u_short max_listened_port = 0;

#if defined (__Lynx__)
  // LynxOS can handle only 80 test iterations.
  // This needs to be investigated further -- olli 12.11.2007
  const u_short ports_to_test = 80;
#else
  const u_short ports_to_test = 300;
#endif

  //Ports beyond 65279 were said to bad on NT sp 3.
  for (u_short idx = USHRT_MAX; idx != USHRT_MAX - ports_to_test; --idx)
    {
#if defined (ACE_VXWORKS)
      if (retry_port_>0)
        {
          ++idx;
          ACE_OS::sleep (ACE_Time_Value (2*ACE_DEFAULT_TIMEOUT));
        }
#endif

      ACE_INET_Addr addr (idx);

      My_Accept_Handler *eh = new My_Accept_Handler (addr);

      if ( ACE_Reactor::instance()->register_handler (
                                         eh,
                                         ACE_Event_Handler::ACCEPT_MASK) == -1)
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%p\n"),
                             ACE_TEXT ("Failed to register event handler")),
                            1);
        }

      ACE_DEBUG ((LM_DEBUG, "Registered event handler at %d\n", idx));

      ACE_Time_Value tv (1);

#if defined (ACE_HAS_THREADS)

      if (ACE_Thread_Manager::instance ()->spawn_n
          (1,
           ACE_THR_FUNC (client),
           reinterpret_cast <void *> (&addr),
           THR_NEW_LWP | THR_DETACHED) == -1)

        ACE_ERROR_RETURN ((LM_ERROR,
                           ACE_TEXT ("(%P|%t) %p\n"),
                           ACE_TEXT ("thread create failed")),
                          1);

      ACE_Thread_Manager::instance ()->wait ();

#else
      ACE_UNUSED_ARG (client);
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P|%t) only one thread may be run in a process on this platform\n%a"),
                  1));
#endif //ACE_HAS_THREADS

      if (ACE_Reactor::instance()->handle_events (tv) == -1 )
        {
          ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
                             ACE_TEXT ("Reactor::handle_events")),
                            1);
        }

      // see if I can register a reactor at this port.
      if (eh->port () == idx)
        {
          if (idx > max_listened_port)
            max_listened_port = idx;
        }
      else
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("Test Fail, listening port %d\n"),
                             eh->port()),
                            1);
        }

      ACE_Reactor::instance()->remove_handler (
                                        eh,
                                        ACE_Event_Handler::ACCEPT_MASK |
                                        ACE_Event_Handler::DONT_CALL);
      delete eh;
    }

  ACE_DEBUG ((LM_DEBUG,
              "Value of ACE_MAX_DEFAULT_PORT       %d\n",
              ACE_MAX_DEFAULT_PORT));

  ACE_DEBUG ((LM_DEBUG,
              "Highest port value I can listen at  %d\n",
              max_listened_port));

  ACE_DEBUG ((LM_DEBUG,
              "Highest port value I can connect to %d\n",
              max_connected_port));

  if ((max_listened_port  == ACE_MAX_DEFAULT_PORT) &&
      (max_connected_port == ACE_MAX_DEFAULT_PORT))
    {
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("Valid ACE_MAX_DEFAULT_PORT value: %d\n"),
                  max_listened_port));
    }
  else
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Invalid ACE_MAX_DEFAULT_PORT ")
                  ACE_TEXT ("or %d port may be busy; got to %d\n"),
                  ACE_MAX_DEFAULT_PORT, max_listened_port));

    }

  ACE_END_TEST;
  return 0;
}


text:
require File.expand_path(File.dirname(__FILE__)) + '/../helper'

class PFTrackExportTest < Test::Unit::TestCase
  include ParabolicTracks

  def test_human_name
    assert_equal "PFTrack v4 .2dt file", Tracksperanto::Export::PFTrack4.human_name
  end

  def test_desc_and_ext
    assert_equal "pftrack_v4.2dt", Tracksperanto::Export::PFTrack4.desc_and_extension
  end

  P = File.dirname(__FILE__) + "/samples/ref_PFTrack.2dt"

  def test_export_output_written
    ensure_same_output Tracksperanto::Export::PFTrack4, P
  end
end


text:
SendGrid
=======

This transport layer forms the coupling between Zend\Mail and the Email Service Provider [SendGrid](http://sendgrid.com).
The transport is a drop-in component and can be used to send email messages including Cc & Bcc addresses and attachments.

Installation
------------

It is assumed this module is already installed and enabled in your Zend Framework 2 project. If not, please read first the [installation instructions](../README.md) to do so.

Copy the `./vendor/juriansluiman/slm-mail/config/slm_mail.send_grid.local.php.dist` to your `./config/autoload` folder (don't
forget to remove the .dist extension!) and update your API key.

Usage
-----

### Supported functionalities

SlmMail consumes for SendGrid just the standard `Zend\Mail\Message` object.

#### Attachments

You can add any attachment to a SendGrid message. Attachments are handled just like you normally send emails with attachments. See the [Zend Framework 2 manual](http://framework.zend.com/manual/2.0/en/modules/zend.mail.message.html) for an extensive explanation of the Message class.

```php
$text = new \Zend\Mime\Part($textContent);
$text->type = "text/plain";

$html = new \Zend\Mime\Part($htmlMarkup);
$html->type = "text/html";

$pdf = new \Zend\Mime\Part(fopen($pathToPdf, 'r'));
$pdf->type     = "application/pdf";
$pdf->filename = "my-attachment.pdf";

$body = new \Zend\Mime\Message;
$body->setParts(array($text, $html, $pdf));

$message = new \Zend\Mail\Message;
$message->setBody($body);
```

### Use service locator

If you have access to the service locator, you can retrieve the SendGrid transport:

```php
// As stated above, you can also create a specialized SendGrid message for more features
$message = new \Zend\Mail\Message();

// set up Message here

$transport = $locator->get('SlmMail\Mail\Transport\SendGridTransport');
$transport->send($message);
```

Of course, you are encouraged to inject this transport object whenever you need to send an email.

### Advanced usage

The transport layer depends on a service class `SlmMail\Service\SendGridService` which sends the requests to the SendGrid
server. However, this service implements also [the api](http://sendgrid.com/docs/API_Reference/Web_API/index.html) so you can
immediately check the state of the sent email and act upon a bounced message.

The service class is injected into the `SlmMail\Mail\Transport\HttpTransport` but you can get the service class yourself too:

```php
$sendgridService = $locator->get('SlmMail\Service\SendGridService');
$bounce          = $sendgrid->getStatistics(); // Example
```

The complete list of methods is:

* `send(Message $message)`: used by transport layer, $message instance of `Zend\Mail\Message` ([docs](http://sendgrid.com/docs/API_Reference/Web_API/mail.html))
* `getStatistics($date, $startDate, $endDate, $aggregate)`: get statistics of your account ([docs](http://sendgrid.com/docs/API_Reference/Web_API/statistics.html))
* `getBounces($date, $days, $startDate, $endDate, $email, $limit, $offset)`: get the list of bounces ([docs](http://sendgrid.com/docs/API_Reference/Web_API/bounces.html))
* `deleteBounces($startDate, $endDate, $email)`: delete an address from the bounce list ([docs](http://sendgrid.com/docs/API_Reference/Web_API/bounces.html))
* `countBounces($startDate, $endDate)`: count the number of bounces ([docs](http://sendgrid.com/docs/API_Reference/Web_API/bounces.html))
* `getSpamReports($date, $days, $startDate, $endDate, $email, $limit, $offset)`: get entries from the spam report list ([docs](http://sendgrid.com/docs/API_Reference/Web_API/spam_reports.html))
* `deleteSpamReport($email)`: delete an address from the spam report list ([docs](http://sendgrid.com/docs/API_Reference/Web_API/spam_reports.html))
* `getBlocks($date, $days, $startDate, $endDate)`: get the list of blocks ([docs](http://sendgrid.com/docs/API_Reference/Web_API/blocks.html))
* `deleteBlock($email)`: delete an address from the blocks list ([docs](http://sendgrid.com/docs/API_Reference/Web_API/blocks.html))

### Error handling

If an error occurs when a request is made to the SendGrid API using `SlmMail\Service\SendGridService`, some exceptions
are thrown. Each exception implements the `SlmMail\Exception\ExceptionInterface`, so you can easily filter each SlmMail
exceptions.

SendGrid error handling is rather poor, therefore only one, generic exception is thrown for each error:

* `SlmMail\Service\Exception\RuntimeException`: this exception is thrown for other exceptions.

You can get the exact message and error code the following way:

```php
catch (\SlmMail\Service\Exception\RuntimeException $e) {
    $message = $e->getMessage();
    $code    = $e->getCode();
}
```


text:
import os
import signal
import ssl
import threading
from contextlib import contextmanager
from textwrap import dedent

from mock import Mock
from pip._vendor.contextlib2 import nullcontext
from werkzeug.serving import WSGIRequestHandler
from werkzeug.serving import make_server as _make_server

from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
    from types import TracebackType
    from typing import (
        Any, Callable, Dict, Iterable, List, Optional, Text, Tuple, Type, Union
    )

    from werkzeug.serving import BaseWSGIServer

    Environ = Dict[str, str]
    Status = str
    Headers = Iterable[Tuple[str, str]]
    ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType]
    Write = Callable[[bytes], None]
    StartResponse = Callable[[Status, Headers, Optional[ExcInfo]], Write]
    Body = List[bytes]
    Responder = Callable[[Environ, StartResponse], Body]

    class MockServer(BaseWSGIServer):
        mock = Mock()  # type: Mock

# Applies on Python 2 and Windows.
if not hasattr(signal, "pthread_sigmask"):
    # We're not relying on this behavior anywhere currently, it's just best
    # practice.
    blocked_signals = nullcontext
else:
    @contextmanager
    def blocked_signals():
        """Block all signals for e.g. starting a worker thread.
        """
        old_mask = signal.pthread_sigmask(
            signal.SIG_SETMASK, range(1, signal.NSIG)
        )
        try:
            yield
        finally:
            signal.pthread_sigmask(signal.SIG_SETMASK, old_mask)

class _RequestHandler(WSGIRequestHandler):
    def make_environ(self):
        environ = super(_RequestHandler, self).make_environ()

        # From pallets/werkzeug#1469, will probably be in release after
        # 0.16.0.
        try:
            # binary_form=False gives nicer information, but wouldn't be
            # compatible with what Nginx or Apache could return.
            peer_cert = self.connection.getpeercert(binary_form=True)
            if peer_cert is not None:
                # Nginx and Apache use PEM format.
                environ["SSL_CLIENT_CERT"] = ssl.DER_cert_to_PEM_cert(
                    peer_cert,
                )
        except ValueError:
            # SSL handshake hasn't finished.
            self.server.log("error", "Cannot fetch SSL peer certificate info")
        except AttributeError:
            # Not using TLS, the socket will not have getpeercert().
            pass

        return environ

def _mock_wsgi_adapter(mock):
    # type: (Callable[[Environ, StartResponse], Responder]) -> Responder
    """Uses a mock to record function arguments and provide
    the actual function that should respond.
    """
    def adapter(environ, start_response):
        # type: (Environ, StartResponse) -> Body
        responder = mock(environ, start_response)
        return responder(environ, start_response)

    return adapter

def make_mock_server(**kwargs):
    # type: (Any) -> MockServer
    """Creates a mock HTTP(S) server listening on a random port on localhost.

    The `mock` property of the returned server provides and records all WSGI
    interactions, so one approach to testing could be

        server = make_mock_server()
        server.mock.side_effects = [
            page1,
            page2,
        ]

        with server_running(server):
            # ... use server...
            ...

        assert server.mock.call_count > 0
        call_args_list = server.mock.call_args_list

        # `environ` is a dictionary defined as per PEP 3333 with the associated
        # contents. Additional properties may be added by werkzeug.
        environ, _ = call_args_list[0].args
        assert environ["PATH_INFO"].startswith("/hello/simple")

    Note that the server interactions take place in a different thread, so you
    do not want to touch the server.mock within the `server_running` block.

    Note also for pip interactions that "localhost" is a "secure origin", so
    be careful using this for failure tests of `--trusted-host`.
    """
    kwargs.setdefault("request_handler", _RequestHandler)

    mock = Mock()
    app = _mock_wsgi_adapter(mock)
    server = _make_server("localhost", 0, app=app, **kwargs)
    server.mock = mock
    return server

@contextmanager
def server_running(server):
    # type: (BaseWSGIServer) -> None
    """Context manager for running the provided server in a separate thread.
    """
    thread = threading.Thread(target=server.serve_forever)
    thread.daemon = True
    with blocked_signals():
        thread.start()
    try:
        yield
    finally:
        server.shutdown()
        thread.join()

# Helper functions for making responses in a declarative way.

def text_html_response(text):
    # type: (Text) -> Responder
    def responder(environ, start_response):
        # type: (Environ, StartResponse) -> Body
        start_response("200 OK", [
            ("Content-Type", "text/html; charset=UTF-8"),
        ])
        return [text.encode('utf-8')]

    return responder

def html5_page(text):
    # type: (Union[Text, str]) -> Text
    return dedent(u"""
    <!DOCTYPE html>

        {}

    """).strip().format(text)

def index_page(spec):
    # type: (Dict[str, str]) -> Responder
    def link(name, value):
        return '{}'.format(
            value, name
        )

    links = ''.join(link(*kv) for kv in spec.items())
    return text_html_response(html5_page(links))

def package_page(spec):
    # type: (Dict[str, str]) -> Responder
    def link(name, value):
        return '{}'.format(
            value, name
        )

    links = ''.join(link(*kv) for kv in spec.items())
    return text_html_response(html5_page(links))

def file_response(path):
    # type: (str) -> Responder
    def responder(environ, start_response):
        # type: (Environ, StartResponse) -> Body
        size = os.stat(path).st_size
        start_response(
            "200 OK", [
                ("Content-Type", "application/octet-stream"),
                ("Content-Length", str(size)),
            ],
        )

        with open(path, 'rb') as f:
            return [f.read()]

    return responder


text:
var rptsochut = new baseRpt('sochut','sochut','Sổ chữ T tài khoản',{
	onLoading:function($scope,options){
		var $filter = options.$filter;
		var $location = options.$location;
		$scope.drilldown = function(row){
			if(row.tk_du){
				var url = "/bkct?tk=" + $scope.condition.tk;
				url = url + "&tk_du=" + row.tk_du;
				url = url + "&tu_ngay=" + $filter("date")($scope.condition.tu_ngay,"yyyy-MM-dd");
				url = url + "&den_ngay=" + $filter("date")($scope.condition.den_ngay,"yyyy-MM-dd");
				url = url + "&ma_dvcs=" + $scope.condition.ma_dvcs;
				url = url + "&isDrillDown=true"
				$location.url(url);

			}

		}
	}
});
rptsochut.defaultCondition = function(condition){
	var c = new Date();
	condition.tu_ngay = new Date(c.getFullYear(),c.getMonth(),1);
	condition.den_ngay = c;
}
rptsochut.afterLoadData = function($scope,data){
	$scope.title = 'Sổ chữ T tài khoản: ' + $scope.condition.tk + " - " + $scope.condition.ten_tk;
}


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

namespace CardGames
{
    [Serializable]
    public class Game : ClassExtension
    {
        public string Name { get; private set; }

        private int? _yearOfRelease;

        public string YearOfRelease
        {
            get { return _yearOfRelease == null ? "<none>" : _yearOfRelease.ToString(); }
        }
        protected Dictionary<String, Edition> Editions { get; private set; } // Asocjacja kwalifikowana

        public Game(string name, int yearOfRelease)
        {
            Name = name;
            _yearOfRelease = yearOfRelease;
            Editions = new Dictionary<string, Edition>();
        }

        /// <summary>
        /// przeciążenie metod
        /// </summary>
        public void AddEdition(Edition edition)
        {
            if (edition.Game != this)
            {
                edition.Game.RemoveEdition(edition);
            }
            if (!Editions.ContainsKey(edition.Symbol))
            {
                Editions.Add(edition.Symbol, edition);
                edition.SetGame(this);
            }
        }

        /// <summary>
        /// przeciążenie metod
        /// </summary>
        public Edition AddEdition(string symbol, string name, int yearOfRelease)
        {
            var edition = new Edition(this, symbol, name, yearOfRelease);
            AddEdition(edition);
            return edition;
        }

        public Edition GetEdition(string symbol)
        {
            return Editions.ContainsKey(symbol) ? Editions[symbol] : null;
        }

        public override string ToString()
        {
            var editionsString = Editions.Aggregate("", (current, e) => current + e.ToString());
            return String.Format("{0}.\nRelease year: {1}\nEditions: \n{2}", Name, YearOfRelease, editionsString);
        }

        public void RemoveEdition(Edition edition)
        {
            if (Editions.ContainsKey(edition.Symbol))
            {
                Editions.Remove(edition.Symbol);
            }
        }
    }
}


text:
public var texture: Texture;
public var type: int		 	= 5;
public var objName 				= "Item";
public var description			= "Description";

//Weapon Stats
public var id: int = -1;
public var power: int = 0;
public var speed: float = 0;
public var defense: float = 1;

private var showGUI: boolean = false;
static var style = new GUIStyle();

function Start()
{
	style.alignment = TextAnchor.MiddleCenter;
	style.normal.textColor = Color.green;
	style.font = Resources.Load("GothicFlames");
	style.fontSize = 24;
}

function Item()
{
	texture = null;
	type = 0;
	objName = "Item";
	id = -1;
	defense = 1;
}

function OnTriggerStay (other : Collider) {

	if (other.gameObject.tag == "Player")
	{
		showGUI = true;

		if (other.transform.localScale.y == gameControl.crouchScale)//(Input.GetKey(KeyCode.LeftShift))
		{
			Stats.score += 2;
			Inventory.giveItem(this as Item);
			gameObject.Destroy(gameObject);
			Stats.items ++;
		}
	}

}

function OnTriggerExit (other : Collider) {
	if (other.gameObject.tag == "Player")
	{
    	showGUI = false;
    }
}

function OnGUI()
{
	if (showGUI)
	{
		GUI.DrawTexture(Rect(Screen.width/2 - 50,Screen.height/2 - 50,100,100),texture);
		GUI.Label(Rect(Screen.width/2 - 100,Screen.height/2 + 50,200,100),objName,style);
	}
}