text:
import { MusicData } from 'js/types';

module.exports = <MusicData>{
	id: 'bailecito',
	title: 'Abel Figueroa — Toda la noche',
	file: 'https://res.cloudinary.com/adentro/video/upload/v1621676400/music/toda_la_noche.mp3',
	schema: require('./toda_la_noche.yaml')
};


text:
set -xeu
cd "$(dirname "$0")/.."

git add -u
git diff @
git diff-index --quiet HEAD

redpajama_set_name: RedPajamaGithub


text:
function InMemory(restoreData) {
    if (!(this instanceof InMemory)) {
        return new InMemory(restoreData);
    }

    let data = restoreData || {};

    InMemory.prototype.set = (key, value) => data[key] = value;

    InMemory.prototype.get = key => data[key];

    InMemory.prototype.delete = key => delete data[key];

    InMemory.prototype.clear = () => data = {};
}

export default InMemory;


text:
* Fixes

### 2.1.1:
* Update Brain/Hierarchy to 2.4.0 for CPT templates [#86](https://github.com/soberwp/controller/issues/86)
* Add filter sober/controller/sage/namespace to allow for a custom Sage namespace [#104](https://github.com/soberwp/controller/issues/104)
* Update ACF class to support taxonomy fields by default by using get_queried_object() [#101](https://github.com/soberwp/controller/issues/101)
* Bug fix for ACF class if no fields on page/post [#102](https://github.com/soberwp/controller/issues/102)
* Allow interaction in Controller with the $post object by using $this->post vs $this->data['post']

### 2.1.0:
* Update deps
* Pass in field data from Acf Options under App class
* Change $this->data from private to protected param
* Fix $post bug not appearing in the $this->data
* Fix Controller overriding filter $data
* Add filter to return Acf data as array
* Add __before and __after lifecycles
* @code and @codeif

### 2.0.1:
* Fix bug assuming Controllers/ folder name

### 2.0.0:
* PSR4 loading
* Template overrides for those underscores
* Pass in field data from Acf automatically
* Debugger to include static methods
* Improve Debugger results
* Dependency injection
* Bug fixes
* Change default path from resources/controllers to app/controllers

### 9.0.0-beta.3:
* Changed to Composer package
* Fix for app Controller bug
* Rename base to app
* Change default path from src/controllers to resources/controllers

### 9.0.0-beta.2.1:
* Fix for base Controller bug

### 9.0.0-beta.2:
* Align with Sage9 versioning
* Enable the use of __construct within the child Class

### 1.0.2:
* Prevent public static methods from being passed onto data
* Class alias for use in template

### 1.0.1:
* Pass on default post data for posts
* Show $post in the controller debugger

### 1.0.0:
* Release


text:
package uk.gov.nationalarchives.droid.profile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

import uk.gov.nationalarchives.droid.core.interfaces.filter.Filter;
import uk.gov.nationalarchives.droid.core.interfaces.filter.FilterCriterion;
import uk.gov.nationalarchives.droid.core.interfaces.filter.FilterValue;

/**
 * @author Alok Kumar Dash
 *
 */

@XmlAccessorType(XmlAccessType.NONE)
public class FilterImpl implements Cloneable, Filter {

    private List<FilterCriterionImpl> unmashalingCriteriaList;

    private boolean unmarshalingInprogress;

    @XmlElement(name = "Enabled", required = true)
    private boolean enabled;

    @XmlElement(name = "Narrowed", required = true)
    private boolean narrowed;

    private Map<Integer, FilterCriterionImpl> filterCriteriaMap = new TreeMap<Integer, FilterCriterionImpl>();

    /**
     * Empty bean constructor.
     */
    public FilterImpl() {
    }

    /**
     * Parameterized constructor.
     * @param criteria A list of filtercriterionimpls.
     * @param enabled Whether the filter is enabled.
     * @param narrowed Whether the filter is narrowed.
     */
    public FilterImpl(List<FilterCriterionImpl> criteria, boolean enabled, boolean narrowed) {
        setCriteria(criteria);
        setEnabled(enabled);
        setNarrowed(narrowed);
    }

    /**
     * Getter method for filter criteria list.
     *
     * @return List of filter criteria.
     */
    public List<FilterCriterion> getCriteria() {
        return new ArrayList<FilterCriterion>(filterCriteriaMap.values());
    }

    /**
     * Getter for XML filter criteria.
     *
     * @return the filter criteria
     */
    @XmlElement(name = "Criteria", required = true)
    List<FilterCriterionImpl> getFilterCriteria() {
        if (unmarshalingInprogress) {
            return unmashalingCriteriaList;
        } else {
            return Collections.unmodifiableList(new ArrayList<FilterCriterionImpl>(filterCriteriaMap.values()));
        }
    }

    /**
     * When JAXB unmarshalling List, it mutate existing list.
     * we create new list, setup flag that unmarshalling is in progress
     * and during unmarshalling we return this list which mutate.
     * When it's finished, we copy everything to Map.
     * Code is NOT thread safe!!!
     * @param u Unmarshaller.
     * @param parent Parent object.
     *
     */
    void beforeUnmarshal(Unmarshaller u, Object parent) {
        unmarshalingInprogress = true;
        unmashalingCriteriaList = new ArrayList<>();
    }

    /**
     * Called after unmarshaling.
     * @param u Unmarshaller.
     * @param parent Parent object.
     */
    void afterUnmarshal(Unmarshaller u, Object parent) {
        if (!unmarshalingInprogress || unmashalingCriteriaList == null) {
            throw new RuntimeException("unmarshalling is not in progress.");
        } else {
            filterCriteriaMap = new TreeMap<Integer, FilterCriterionImpl>();
            int index = 0;
            for (FilterCriterionImpl criterion : unmashalingCriteriaList) {
                filterCriteriaMap.put(index++, criterion);
            }
            unmashalingCriteriaList = null;
            unmarshalingInprogress = false;
        }
    }

    /**
     * Setter method for criteria list.
     *
     * @param criteria
     *            criteria list to set.
     */
    public void setCriteria(List<FilterCriterionImpl> criteria) {
        int index = 0;
        for (FilterCriterionImpl criterion : criteria) {
            filterCriteriaMap.put(index++, criterion);
        }
    }

    // this only to save in xml -- ends

    /**
     * Add filter criteria to list.
     *
     * @param filterCriteria
     *            filter criteria to add.
     * @param index
     *            position of filter criteria in selected filter dialog.
     */
    public void addFilterCiterion(FilterCriterionImpl filterCriteria, int index) {
        if (getFilterCriterion(index) == null) {
            filterCriteriaMap.put(index, filterCriteria);
        } else {
            filterCriteriaMap.remove(index);
            filterCriteriaMap.put(index, filterCriteria);
        }
    }

    /**
     * remove filter criteria from the list.
     *
     * @param rowNumber
     *            position of filter criteria in selected filter dialog.
     */
    public void removeFilterCriterion(int rowNumber) {
        filterCriteriaMap.remove(rowNumber);
    }

    /**
     * Getter method for filter criteria.
     *
     * @return Filter criteria map.
     */
    public Map<Integer, FilterCriterionImpl> getFilterCriteriaMap() {
        return filterCriteriaMap;
    }

    /**
     *
     * @param filterCriteriaMap
     */
    private void setFilterCriteriaMap(Map<Integer, FilterCriterionImpl> filterCriteriaMap) {
        this.filterCriteriaMap = filterCriteriaMap;
    }

    /**
     *
     * @param rowNumber
     *            position of this filter criteria at filter dialog.
     * @return FilterCriteria filter criteria for the given position.
     */
    public FilterCriterionImpl getFilterCriterion(int rowNumber) {
        return filterCriteriaMap.get(rowNumber);
    }

    /**
     * @return Object Filter. Deep copy.
     */
    @Override
    public Filter clone() {
        Map<Integer, FilterCriterionImpl> clonedFilterCriteriaMap = new TreeMap<Integer, FilterCriterionImpl>();
        try {
            super.clone();
            FilterImpl clone = new FilterImpl();
            for (int i = 0; i < filterCriteriaMap.size(); i++) {
                FilterCriterionImpl cloneFilterCriteria = new FilterCriterionImpl();

                FilterCriterionImpl filterCriteria = filterCriteriaMap.get(i);

                cloneFilterCriteria.setField(filterCriteria.getField());

                cloneFilterCriteria.setOperator(filterCriteria.getOperator());
                cloneFilterCriteria.setValueFreeText(new String(filterCriteria.getValueFreeText()));

                cloneFilterCriteria.setRowNumber(new Integer(filterCriteria.getRowNumber()));

                List<FilterValue> selectedValues = filterCriteria.getSelectedValues();

                if (selectedValues != null) {
                    List<FilterValue> clonedSelectedValues = new ArrayList<FilterValue>();
                    for (int j = 0; j < selectedValues.size(); j++) {
                        FilterValue values = selectedValues.get(j);
                        FilterValue clonedValues = new FilterValue(values.getId(), values.getDescription(), values
                                .getQueryParameter());
                        clonedSelectedValues.add(clonedValues);
                    }
                    cloneFilterCriteria.setSelectedValues(clonedSelectedValues);
                }

                clonedFilterCriteriaMap.put(i, cloneFilterCriteria);
            }
            clone.setFilterCriteriaMap(clonedFilterCriteriaMap);
            clone.setEnabled(new Boolean(enabled));
            clone.setNarrowed(new Boolean(narrowed));
            return clone;
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }

    /**
     * getter method for filter enabled.
     *
     * @return boolean true if enabled.
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Setter method for filter enabled.
     *
     * @param enabled
     *            enabled filag.
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * Getter method for Any or All flag.
     * @return boolean Any or All flag in filter dialog.
     */
    public boolean isNarrowed() {
        return narrowed;
    }

    /**
     * Setter method for Any or All flag.
     * @param narrowed
     *            any or All flag in filter dialog.
     */
    public void setNarrowed(boolean narrowed) {
        this.narrowed = narrowed;
    }

    /**
     * Checks if filter is empty or filter criteria list exists.
     * @return boolean
     */
    public boolean hasCriteria() {
        boolean hasCriteria = false;
        if (filterCriteriaMap != null && !filterCriteriaMap.isEmpty()) {
            hasCriteria =  true;
        }
        return hasCriteria;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getNumberOfFilterCriterion() {
        return filterCriteriaMap.size();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <display-name>Certificate-Webapp</display-name>
    <servlet>
        <description>JAX-WS/JAX-RS Certificate Management Endpoint</description>
        <display-name>JAX-WS/JAX-RS Servlet</display-name>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>
    <context-param>
        <param-name>doAuthentication</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>isDefault</param-name>
        <param-value>false</param-value>
    </context-param>

    <!--publish to apim-->
    <context-param>
        <param-name>managed-api-enabled</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>managed-api-owner</param-name>
        <param-value>admin</param-value>
    </context-param>
	<context-param>
		<param-name>isSharedWithAllTenants</param-name>
		<param-value>true</param-value>
	</context-param>

    <filter>
        <filter-name>HttpHeaderSecurityFilter</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <init-param>
            <param-name>hstsEnabled</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
        <filter-class>org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
        <init-param>
            <param-name>patterns</param-name>
            <param-value>text/html" ,application/json" ,text/plain</param-value>
        </init-param>
        <init-param>
            <param-name>filterAction</param-name>
            <param-value>enforce</param-value>
        </init-param>
        <init-param>
            <param-name>httpHeaders</param-name>
            <param-value>Cache-Control: no-store, no-cache, must-revalidate, private</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>HttpHeaderSecurityFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>


text:
<?php
	return [
		'User not found' => 'User not found',
		'You are not allowed to access this page' => 'You are not allowed to access this resource',
		'Email already in use by another account' => 'Email already in use by another account',
		'Unknown Error. Try again later.' => 'Unknown Error. Try again later.',
	];


text:
class RubyLexer

  # :stopdoc:
  RUBY19 = "".respond_to? :encoding

  IDENT_CHAR = if RUBY19 then
                 /[\w\u0080-\u{10ffff}]/u
               else
                 /[\w\x80-\xFF]/n
               end

  EOF = :eof_haha!

  # ruby constants for strings (should this be moved somewhere else?)

  STR_FUNC_BORING = 0x00
  STR_FUNC_ESCAPE = 0x01 # TODO: remove and replace with REGEXP
  STR_FUNC_EXPAND = 0x02
  STR_FUNC_REGEXP = 0x04
  STR_FUNC_QWORDS = 0x08
  STR_FUNC_SYMBOL = 0x10
  STR_FUNC_INDENT = 0x20 # <<-HEREDOC

  STR_SQUOTE = STR_FUNC_BORING
  STR_DQUOTE = STR_FUNC_BORING | STR_FUNC_EXPAND
  STR_XQUOTE = STR_FUNC_BORING | STR_FUNC_EXPAND
  STR_REGEXP = STR_FUNC_REGEXP | STR_FUNC_ESCAPE | STR_FUNC_EXPAND
  STR_SSYM   = STR_FUNC_SYMBOL
  STR_DSYM   = STR_FUNC_SYMBOL | STR_FUNC_EXPAND

  ESCAPES = {
    "a"    => "\007",
    "b"    => "\010",
    "e"    => "\033",
    "f"    => "\f",
    "n"    => "\n",
    "r"    => "\r",
    "s"    => " ",
    "t"    => "\t",
    "v"    => "\13",
    "\\"   => '\\',
    "\n"   => "",
    "C-\?" => 127.chr,
    "c\?"  => 127.chr,
  }

  TOKENS = {
    "!"   => :tBANG,
    "!="  => :tNEQ,
    # "!@"  => :tUBANG,
    "!~"  => :tNMATCH,
    ","   => :tCOMMA,
    ".."  => :tDOT2,
    "..." => :tDOT3,
    "="   => :tEQL,
    "=="  => :tEQ,
    "===" => :tEQQ,
    "=>"  => :tASSOC,
    "=~"  => :tMATCH,
    "->"  => :tLAMBDA,
  }

  @@regexp_cache = Hash.new { |h,k| h[k] = Regexp.new(Regexp.escape(k)) }
  @@regexp_cache[nil] = nil

  # :startdoc:

  attr_accessor :lineno # we're bypassing oedipus' lineno handling.
  attr_accessor :brace_nest
  attr_accessor :cmdarg
  attr_accessor :command_start
  attr_accessor :command_state
  attr_accessor :last_state
  attr_accessor :cond
  attr_accessor :extra_lineno

  ##
  # Additional context surrounding tokens that both the lexer and
  # grammar use.

  attr_accessor :lex_state
  attr_accessor :lex_strterm
  attr_accessor :lpar_beg
  attr_accessor :paren_nest
  attr_accessor :parser # HACK for very end of lexer... *sigh*
  attr_accessor :space_seen
  attr_accessor :string_buffer
  attr_accessor :string_nest

  # Last token read via next_token.
  attr_accessor :token

  ##
  # What version of ruby to parse. 18 and 19 are the only valid values
  # currently supported.

  attr_accessor :version

  attr_writer :comments

  def initialize v = 18
    self.version = v

    reset
  end

  def arg_ambiguous
    self.warning("Ambiguous first argument. make sure.")
  end

  def arg_state
    in_arg_state? ? :expr_arg : :expr_beg
  end

  def beginning_of_line?
    ss.bol?
  end
  alias :bol? :beginning_of_line? # to make .rex file more readable

  def comments # TODO: remove this... maybe comment_string + attr_accessor
    c = @comments.join
    @comments.clear
    c
  end

  def end_of_stream?
    ss.eos?
  end

  def expr_dot?
    lex_state == :expr_dot
  end

  def expr_fname?
    lex_state == :expr_fname
  end

  def expr_result token, text
    cond.push false
    cmdarg.push false
    result :expr_beg, token, text
  end

  def heredoc here # TODO: rewrite / remove
    _, eos, func, last_line = here

    indent  = (func & STR_FUNC_INDENT) != 0 ? "[ \t]*" : nil
    expand  = (func & STR_FUNC_EXPAND) != 0
    eos_re  = /#{indent}#{Regexp.escape eos}(\r*\n|\z)/
    err_msg = "can't match #{eos_re.inspect} anywhere in "

    rb_compile_error err_msg if end_of_stream?

    if beginning_of_line? && scan(eos_re) then
      self.lineno += 1
      ss.unread_many last_line # TODO: figure out how to remove this
      return :tSTRING_END, eos
    end

    self.string_buffer = []

    if expand then
      case
      when scan(/#[$@]/) then
        ss.pos -= 1 # FIX omg stupid
        return :tSTRING_DVAR, matched
      when scan(/#[{]/) then
        return :tSTRING_DBEG, matched
      when scan(/#/) then
        string_buffer << '#'
      end

      begin
        c = tokadd_string func, "\n", nil

        rb_compile_error err_msg if
          c == RubyLexer::EOF

        if c != "\n" then
          return :tSTRING_CONTENT, string_buffer.join.delete("\r")
        else
          string_buffer << scan(/\n/)
        end

        rb_compile_error err_msg if end_of_stream?
      end until check(eos_re)
    else
      until check(eos_re) do
        string_buffer << scan(/.*(\n|\z)/)
        rb_compile_error err_msg if end_of_stream?
      end
    end

    self.lex_strterm = [:heredoc, eos, func, last_line]

    return :tSTRING_CONTENT, string_buffer.join.delete("\r")
  end

  def heredoc_identifier # TODO: remove / rewrite
    term, func = nil, STR_FUNC_BORING
    self.string_buffer = []

    case
    when scan(/(-?)([\'\"\`])(.*?)\2/) then
      term = ss[2]
      func |= STR_FUNC_INDENT unless ss[1].empty?
      func |= case term
              when "\'" then
                STR_SQUOTE
              when '"' then
                STR_DQUOTE
              else
                STR_XQUOTE
              end
      string_buffer << ss[3]
    when scan(/-?([\'\"\`])(?!\1*\Z)/) then
      rb_compile_error "unterminated here document identifier"
    when scan(/(-?)(#{IDENT_CHAR}+)/) then
      term = '"'
      func |= STR_DQUOTE
      unless ss[1].empty? then
        func |= STR_FUNC_INDENT
      end
      string_buffer << ss[2]
    else
      return nil
    end

    if scan(/.*\n/) then
      # TODO: think about storing off the char range instead
      line = matched
    else
      line = nil
    end

    self.lex_strterm = [:heredoc, string_buffer.join, func, line]

    if term == '`' then
      result nil, :tXSTRING_BEG, "`"
    else
      result nil, :tSTRING_BEG, "\""
    end
  end

  def in_fname?
    in_lex_state? :expr_fname
  end

  def in_arg_state? # TODO: rename is_after_operator?
    in_lex_state? :expr_fname, :expr_dot
  end

  def in_lex_state?(*states)
    states.include? lex_state
  end

  def int_with_base base
    rb_compile_error "Invalid numeric format" if matched =~ /__/
    return result(:expr_end, :tINTEGER, matched.to_i(base))
  end

  def is_arg?
    in_lex_state? :expr_arg, :expr_cmdarg
  end

  def is_beg?
    in_lex_state? :expr_beg, :expr_value, :expr_mid, :expr_class, :expr_labelarg
  end

  def is_end?
    in_lex_state? :expr_end, :expr_endarg, :expr_endfn
  end

  def ruby22_label?
    ruby22? and is_label_possible?
  end

  def is_label_possible?
    (in_lex_state?(:expr_beg, :expr_endfn) && !command_state) || is_arg?
  end

  def is_label_suffix?
    check(/:(?!:)/)
  end

  def is_space_arg? c = "x"
    is_arg? and space_seen and c !~ /\s/
  end

  def matched
    ss.matched
  end

  def not_end?
    not is_end?
  end

  def process_amper text
    token = if is_arg? && space_seen && !check(/\s/) then
               warning("`&' interpreted as argument prefix")
               :tAMPER
             elsif in_lex_state? :expr_beg, :expr_mid then
               :tAMPER
             else
               :tAMPER2
             end

    return result(:arg_state, token, "&")
  end

  def process_backref text
    token = ss[1].to_sym
    # TODO: can't do lineno hack w/ symbol
    result :expr_end, :tBACK_REF, token
  end

  def process_begin text
    @comments << matched

    unless scan(/.*?\n=end( |\t|\f)*[^\n]*(\n|\z)/m) then
      @comments.clear
      rb_compile_error("embedded document meets end of file")
    end

    @comments << matched
    self.lineno += matched.count("\n")

    nil # TODO
  end

  def process_bracing text
    cond.lexpop
    cmdarg.lexpop

    case matched
    when "}" then
      self.brace_nest -= 1
      self.lex_state   = :expr_endarg

      # TODO
      # if (c == '}') {
      #     if (!brace_nest--) c = tSTRING_DEND;
      # }

      return :tRCURLY, matched
    when "]" then
      self.paren_nest -= 1
      self.lex_state   = :expr_endarg
      return :tRBRACK, matched
    when ")" then
      self.paren_nest -= 1
      self.lex_state   = :expr_endfn
      return :tRPAREN, matched
    else
      raise "Unknown bracing: #{matched.inspect}"
    end
  end

  def process_colon1 text
    # ?: / then / when
    if is_end? || check(/\s/) then
      return result :expr_beg, :tCOLON, text
    end

    case
    when scan(/\'/) then
      string STR_SSYM
    when scan(/\"/) then
      string STR_DSYM
    end

    result :expr_fname, :tSYMBEG, text
  end

  def process_colon2 text
    if is_beg? || in_lex_state?(:expr_class) || is_space_arg? then
      result :expr_beg, :tCOLON3, text
    else
      result :expr_dot, :tCOLON2, text
    end
  end

  def process_curly_brace text
    self.brace_nest += 1
    if lpar_beg && lpar_beg == paren_nest then
      self.lpar_beg = nil
      self.paren_nest -= 1

      return expr_result(:tLAMBEG, "{")
    end

    token = if is_arg? || in_lex_state?(:expr_end, :expr_endfn) then
               :tLCURLY      #  block (primary)
             elsif in_lex_state?(:expr_endarg) then
               :tLBRACE_ARG  #  block (expr)
             else
               :tLBRACE      #  hash
             end

    self.command_start = true unless token == :tLBRACE

    return expr_result(token, "{")
  end

  def process_float text
    rb_compile_error "Invalid numeric format" if text =~ /__/
    return result(:expr_end, :tFLOAT, text.to_f)
  end

  def process_gvar text
    text.lineno = self.lineno
    result(:expr_end, :tGVAR, text)
  end

  def process_gvar_oddity text
    return result :expr_end, "$", "$" if text == "$" # TODO: wtf is this?
    rb_compile_error "#{text.inspect} is not allowed as a global variable name"
  end

  def process_ivar text
    tok_id = text =~ /^@@/ ? :tCVAR : :tIVAR
    text.lineno = self.lineno
    return result(:expr_end, tok_id, text)
  end

  def process_lchevron text
    if (!in_lex_state?(:expr_dot, :expr_class) &&
        !is_end? &&
        (!is_arg? || space_seen)) then
      tok = self.heredoc_identifier
      return tok if tok
    end

    return result(:arg_state, :tLSHFT, "\<\<")
  end

  def process_newline_or_comment text
    c = matched
    hit = false

    if c == '#' then
      ss.pos -= 1

      while scan(/\s*\#.*(\n+|\z)/) do
        hit = true
        self.lineno += matched.lines.to_a.size
        @comments << matched.gsub(/^ +#/, '#').gsub(/^ +$/, '')
      end

      return nil if end_of_stream?
    end

    self.lineno += 1 unless hit

    # Replace a string of newlines with a single one
    self.lineno += matched.lines.to_a.size if scan(/\n+/)

    return if in_lex_state?(:expr_beg, :expr_value, :expr_class,
                            :expr_fname, :expr_dot, :expr_labelarg)

    if scan(/([\ \t\r\f\v]*)\./) then
      self.space_seen = true unless ss[1].empty?

      ss.pos -= 1
      return unless check(/\.\./)
    end

    self.command_start = true

    return result(:expr_beg, :tNL, nil)
  end

  def process_nthref text
    # TODO: can't do lineno hack w/ number
    result :expr_end, :tNTH_REF, ss[1].to_i
  end

  def process_paren text
    token = if ruby18 then
              process_paren18
            else
              process_paren19
            end

    self.paren_nest += 1

    return expr_result(token, "(")
  end

  def process_paren18
    self.command_start = true
    token = :tLPAREN2

    if in_lex_state? :expr_beg, :expr_mid then
      token = :tLPAREN
    elsif space_seen then
      if in_lex_state? :expr_cmdarg then
        token = :tLPAREN_ARG
      elsif in_lex_state? :expr_arg then
        warning "don't put space before argument parentheses"
      end
    else
      # not a ternary -- do nothing?
    end

    token
  end

  def process_paren19
    if is_beg? then
      :tLPAREN
    elsif is_space_arg? then
      :tLPAREN_ARG
    else
      :tLPAREN2 # plain '(' in parse.y
    end
  end

  def process_percent text
    return parse_quote if is_beg?

    return result(:expr_beg, :tOP_ASGN, "%") if scan(/\=/)

    return parse_quote if is_arg? && space_seen && ! check(/\s/)

    return result(:arg_state, :tPERCENT, "%")
  end

  def process_plus_minus text
    sign = matched
    utype, type = if sign == "+" then
                    [:tUPLUS, :tPLUS]
                  else
                    [:tUMINUS, :tMINUS]
                  end

    if in_arg_state? then
      if scan(/@/) then
        return result(:expr_arg, utype, "#{sign}@")
      else
        return result(:expr_arg, type, sign)
      end
    end

    return result(:expr_beg, :tOP_ASGN, sign) if scan(/\=/)

    if (is_beg? || (is_arg? && space_seen && !check(/\s/))) then
      arg_ambiguous if is_arg?

      if check(/\d/) then
        return nil if utype == :tUPLUS
        return result(:expr_beg, :tUMINUS_NUM, sign)
      end

      return result(:expr_beg, utype, sign)
    end

    return result(:expr_beg, type, sign)
  end

  def process_questionmark text
    if is_end? then
      state = ruby18 ? :expr_beg : :expr_value # HACK?
      return result(state, :tEH, "?")
    end

    if end_of_stream? then
      rb_compile_error "incomplete character syntax: parsed #{text.inspect}"
    end

    if check(/\s|\v/) then
      unless is_arg? then
        c2 = { " " => 's',
              "\n" => 'n',
              "\t" => 't',
              "\v" => 'v',
              "\r" => 'r',
              "\f" => 'f' }[matched]

        if c2 then
          warning("invalid character syntax; use ?\\" + c2)
        end
      end

      # ternary
      state = ruby18 ? :expr_beg : :expr_value # HACK?
      return result(state, :tEH, "?")
    elsif check(/\w(?=\w)/) then # ternary, also
      return result(:expr_beg, :tEH, "?")
    end

    c = if scan(/\\/) then
          self.read_escape
        else
          ss.getch
        end

    if version == 18 then
      return result(:expr_end, :tINTEGER, c[0].ord & 0xff)
    else
      return result(:expr_end, :tSTRING, c)
    end
  end

  def process_slash text
    if is_beg? then
      string STR_REGEXP

      return result(nil, :tREGEXP_BEG, "/")
    end

    if scan(/\=/) then
      return result(:expr_beg, :tOP_ASGN, "/")
    end

    if is_arg? && space_seen then
      unless scan(/\s/) then
        arg_ambiguous
        string STR_REGEXP, "/"
        return result(nil, :tREGEXP_BEG, "/")
      end
    end

    return result(:arg_state, :tDIVIDE, "/")
  end

  def process_square_bracket text
    self.paren_nest += 1

    token = nil

    if in_arg_state? then
      case
      when scan(/\]\=/) then
        self.paren_nest -= 1 # HACK? I dunno, or bug in MRI
        return result(:expr_arg, :tASET, "[]=")
      when scan(/\]/) then
        self.paren_nest -= 1 # HACK? I dunno, or bug in MRI
        return result(:expr_arg, :tAREF, "[]")
      else
        rb_compile_error "unexpected '['"
      end
    elsif is_beg? then
      token = :tLBRACK
    elsif is_arg? && space_seen then
      token = :tLBRACK
    else
      token = :tLBRACK2
    end

    return expr_result(token, "[")
  end

  def process_symbol text
    symbol = match[1].gsub(ESC) { unescape $1 }

    rb_compile_error "symbol cannot contain '\\0'" if
      ruby18 && symbol =~ /\0/

    return result(:expr_end, :tSYMBOL, symbol)
  end

  def was_label?
    @was_label = ruby22_label?
    true
  end

  def process_label_or_string text
    if @was_label && text =~ /:$/ then
      @was_label = nil
      return process_label text
    elsif text =~ /:$/ then
      ss.pos -= 1 # put back ":"
      text = text[0..-2]
    end

    result :expr_end, :tSTRING, text[1..-2].gsub(/\\\\/, "\\").gsub(/\\'/, "'")
  end

  def process_label text
    result = process_symbol text
    result[0] = :tLABEL
    result
  end

  def process_token text
    # TODO: make this always return [token, lineno]
    token = self.token = text
    token << matched if scan(/[\!\?](?!=)/)

    tok_id =
      case
      when token =~ /[!?]$/ then
        :tFID
      when in_lex_state?(:expr_fname) && scan(/=(?:(?![~>=])|(?==>))/) then
        # ident=, not =~ => == or followed by =>
        # TODO test lexing of a=>b vs a==>b
        token << matched
        :tIDENTIFIER
      when token =~ /^[A-Z]/ then
        :tCONSTANT
      else
        :tIDENTIFIER
      end

    if !ruby18 and is_label_possible? and is_label_suffix? then
      scan(/:/)
      return result(:expr_labelarg, :tLABEL, [token, self.lineno])
    end

    unless in_lex_state? :expr_dot then
      # See if it is a reserved word.
      keyword = if ruby18 then # REFACTOR need 18/19 lexer subclasses
                  RubyParserStuff::Keyword.keyword18 token
                else
                  RubyParserStuff::Keyword.keyword19 token
                end

      return process_token_keyword keyword if keyword
    end # unless in_lex_state? :expr_dot

    # TODO:
    # if (mb == ENC_CODERANGE_7BIT && lex_state != EXPR_DOT) {

    state = if is_beg? or is_arg? or in_lex_state? :expr_dot then
              command_state ? :expr_cmdarg : :expr_arg
            elsif not ruby18 and in_lex_state? :expr_fname then
              :expr_endfn
            else
              :expr_end
            end

    if not [:expr_dot, :expr_fname].include? last_state and
        self.parser.env[token.to_sym] == :lvar then
      state = :expr_end
    end

    token.lineno = self.lineno # yes, on a string. I know... I know...

    return result(state, tok_id, token)
  end

  def process_token_keyword keyword
    state = keyword.state

    value = [token, self.lineno]

    self.command_start = true if state == :expr_beg and lex_state != :expr_fname

    case
    when lex_state == :expr_fname then
      result(state, keyword.id0, keyword.name)
    when keyword.id0 == :kDO then
      case
      when lpar_beg && lpar_beg == paren_nest then
        self.lpar_beg = nil
        self.paren_nest -= 1
        result(state, :kDO_LAMBDA, value)
      when cond.is_in_state then
        result(state, :kDO_COND, value)
      when cmdarg.is_in_state && lex_state != :expr_cmdarg then
        result(state, :kDO_BLOCK, value)
      when in_lex_state?(:expr_beg, :expr_endarg) then
        result(state, :kDO_BLOCK, value)
      else
        result(state, :kDO, value)
      end
    when in_lex_state?(:expr_beg, :expr_value) then # TODO: :expr_labelarg
      result(state, keyword.id0, value)
    when keyword.id0 != keyword.id1 then
      result(:expr_beg, keyword.id1, value)
    else
      result(state, keyword.id1, value)
    end
  end

  def process_underscore text
    ss.unscan # put back "_"

    if beginning_of_line? && scan(/\__END__(\r?\n|\Z)/) then
      return [RubyLexer::EOF, RubyLexer::EOF]
    elsif scan(/\_\w*/) then
      return process_token matched
    end
  end

  def rb_compile_error msg
    msg += ". near line #{self.lineno}: #{ss.rest[/^.*/].inspect}"
    raise RubyParser::SyntaxError, msg
  end

  def read_escape # TODO: remove / rewrite
    case
    when scan(/\\/) then                  # Backslash
      '\\'
    when scan(/n/) then                   # newline
      "\n"
    when scan(/t/) then                   # horizontal tab
      "\t"
    when scan(/r/) then                   # carriage-return
      "\r"
    when scan(/f/) then                   # form-feed
      "\f"
    when scan(/v/) then                   # vertical tab
      "\13"
    when scan(/a/) then                   # alarm(bell)
      "\007"
    when scan(/e/) then                   # escape
      "\033"
    when scan(/b/) then                   # backspace
      "\010"
    when scan(/s/) then                   # space
      " "
    when scan(/[0-7]{1,3}/) then          # octal constant
      (matched.to_i(8) & 0xFF).chr
    when scan(/x([0-9a-fA-F]{1,2})/) then # hex constant
      ss[1].to_i(16).chr
    when check(/M-\\[\\MCc]/) then
      scan(/M-\\/) # eat it
      c = self.read_escape
      c[0] = (c[0].ord | 0x80).chr
      c
    when scan(/M-(.)/) then
      c = ss[1]
      c[0] = (c[0].ord | 0x80).chr
      c
    when check(/(C-|c)\\[\\MCc]/) then
      scan(/(C-|c)\\/) # eat it
      c = self.read_escape
      c[0] = (c[0].ord & 0x9f).chr
      c
    when scan(/C-\?|c\?/) then
      127.chr
    when scan(/(C-|c)(.)/) then
      c = ss[2]
      c[0] = (c[0].ord & 0x9f).chr
      c
    when scan(/^[89]/i) then # bad octal or hex... MRI ignores them :(
      matched
    when scan(/u([0-9a-fA-F]{2,4}|\{[0-9a-fA-F]{2,6}\})/) then
      [ss[1].delete("{}").to_i(16)].pack("U")
    when scan(/[McCx0-9]/) || end_of_stream? then
      rb_compile_error("Invalid escape character syntax")
    else
      ss.getch
    end
  end

  def regx_options # TODO: rewrite / remove
    good, bad = [], []

    if scan(/[a-z]+/) then
      good, bad = matched.split(//).partition { |s| s =~ /^[ixmonesu]$/ }
    end

    unless bad.empty? then
      rb_compile_error("unknown regexp option%s - %s" %
                       [(bad.size > 1 ? "s" : ""), bad.join.inspect])
    end

    return good.join
  end

  def reset
    self.brace_nest    = 0
    self.command_start = true
    self.comments      = []
    self.lex_state     = nil
    self.lex_strterm   = nil
    self.lineno        = 1
    self.lpar_beg      = nil
    self.paren_nest    = 0
    self.space_seen    = false
    self.string_nest   = 0
    self.token         = nil
    self.extra_lineno  = 0

    self.cmdarg = RubyParserStuff::StackState.new(:cmdarg)
    self.cond   = RubyParserStuff::StackState.new(:cond)
  end

  def result lex_state, token, text # :nodoc:
    lex_state = self.arg_state if lex_state == :arg_state
    self.lex_state = lex_state if lex_state
    [token, text]
  end

  def ruby18
    Ruby18Parser === parser
  end

  def ruby19
    Ruby19Parser === parser
  end

  def scan re
    ss.scan re
  end

  def check re
    ss.check re
  end

  def scanner_class # TODO: design this out of oedipus_lex. or something.
    RPStringScanner
  end

  def space_vs_beginning space_type, beg_type, fallback
    if is_space_arg? check(/./m) then
      warning "`**' interpreted as argument prefix"
      space_type
    elsif is_beg? then
      beg_type
    else
      # TODO: warn_balanced("**", "argument prefix");
      fallback
    end
  end

  def string type, beg = matched, nnd = "\0"
    self.lex_strterm = [:strterm, type, beg, nnd]
  end

  # TODO: consider
  # def src= src
  #   raise "bad src: #{src.inspect}" unless String === src
  #   @src = RPStringScanner.new(src)
  # end

  def tokadd_escape term # TODO: rewrite / remove
    case
    when scan(/\\\n/) then
      # just ignore
    when scan(/\\([0-7]{1,3}|x[0-9a-fA-F]{1,2})/) then
      self.string_buffer << matched
    when scan(/\\([MC]-|c)(?=\\)/) then
      self.string_buffer << matched
      self.tokadd_escape term
    when scan(/\\([MC]-|c)(.)/) then
      self.string_buffer << matched
    when scan(/\\[McCx]/) then
      rb_compile_error "Invalid escape character syntax"
    when scan(/\\(.)/m) then
      self.string_buffer << matched
    else
      rb_compile_error "Invalid escape character syntax"
    end
  end

  def tokadd_string(func, term, paren) # TODO: rewrite / remove
    qwords = (func & STR_FUNC_QWORDS) != 0
    escape = (func & STR_FUNC_ESCAPE) != 0
    expand = (func & STR_FUNC_EXPAND) != 0
    regexp = (func & STR_FUNC_REGEXP) != 0
    symbol = (func & STR_FUNC_SYMBOL) != 0

    paren_re = @@regexp_cache[paren]
    term_re  = @@regexp_cache[term]

    until end_of_stream? do
      c = nil
      handled = true

      case
      when paren_re && scan(paren_re) then
        self.string_nest += 1
      when scan(term_re) then
        if self.string_nest == 0 then
          ss.pos -= 1
          break
        else
          self.string_nest -= 1
        end
      when expand && scan(/#(?=[\$\@\{])/) then
        ss.pos -= 1
        break
      when qwords && scan(/\s/) then
        ss.pos -= 1
        break
      when expand && scan(/#(?!\n)/) then
        # do nothing
      when check(/\\/) then
        case
        when qwords && scan(/\\\n/) then
          string_buffer << "\n"
          next
        when qwords && scan(/\\\s/) then
          c = ' '
        when expand && scan(/\\\n/) then
          next
        when regexp && check(/\\/) then
          self.tokadd_escape term
          next
        when expand && scan(/\\/) then
          c = self.read_escape
        when scan(/\\\n/) then
          # do nothing
        when scan(/\\\\/) then
          string_buffer << '\\' if escape
          c = '\\'
        when scan(/\\/) then
          unless scan(term_re) || paren.nil? || scan(paren_re) then
            string_buffer << "\\"
          end
        else
          handled = false
        end # inner /\\/ case
      else
        handled = false
      end # top case

      unless handled then
        t = Regexp.escape term
        x = Regexp.escape(paren) if paren && paren != "\000"
        re = if qwords then
               if RUBY19 then
                 /[^#{t}#{x}\#\0\\\s]+|./ # |. to pick up whatever
               else
                 /[^#{t}#{x}\#\0\\\s\v]+|./ # argh. 1.8's \s doesn't pick up \v
               end
             else
               /[^#{t}#{x}\#\0\\]+|./
             end

        scan re
        c = matched

        rb_compile_error "symbol cannot contain '\\0'" if symbol && c =~ /\0/
      end # unless handled

      c ||= matched
      string_buffer << c
    end # until

    c ||= matched
    c = RubyLexer::EOF if end_of_stream?

    return c
  end

  def unescape s
    r = ESCAPES[s]

    self.extra_lineno -= 1 if r && s == "n"

    return r if r

    x = case s
        when /^[0-7]{1,3}/ then
          ($&.to_i(8) & 0xFF).chr
        when /^x([0-9a-fA-F]{1,2})/ then
          $1.to_i(16).chr
        when /^M-(.)/ then
          ($1[0].ord | 0x80).chr
        when /^(C-|c)(.)/ then
          ($2[0].ord & 0x9f).chr
        when /^[89a-f]/i then # bad octal or hex... ignore? that's what MRI does :(
          s
        when /^[McCx0-9]/ then
          rb_compile_error("Invalid escape character syntax")
        when /u([0-9a-fA-F]{2,4}|\{[0-9a-fA-F]{2,6}\})/ then
          [$1.delete("{}").to_i(16)].pack("U")
        else
          s
        end
    x.force_encoding "UTF-8" if RUBY19
    x
  end

  def warning s
    # do nothing for now
  end

  def ruby22?
    Ruby22Parser === parser
  end

  def process_string # TODO: rewrite / remove
    token = if lex_strterm[0] == :heredoc then
              self.heredoc lex_strterm
            else
              self.parse_string lex_strterm
            end

    token_type, c = token

    if ruby22? && token_type == :tSTRING_END && ["'", '"'].include?(c) then
      if (([:expr_beg, :expr_endfn].include?(lex_state) &&
           !cond.is_in_state) || is_arg?) &&
          is_label_suffix? then
        scan(/:/)
        token_type = token[0] = :tLABEL_END
      end
    end

    if [:tSTRING_END, :tREGEXP_END, :tLABEL_END].include? token_type then
      self.lex_strterm = nil
      self.lex_state   = (token_type == :tLABEL_END) ? :expr_labelarg : :expr_end
    end

    return token
  end

  def parse_quote # TODO: remove / rewrite
    beg, nnd, short_hand, c = nil, nil, false, nil

    if scan(/[a-z0-9]{1,2}/i) then # Long-hand (e.g. %Q{}).
      rb_compile_error "unknown type of %string" if ss.matched_size == 2
      c, beg, short_hand = matched, ss.getch, false
    else                               # Short-hand (e.g. %{, %., %!, etc)
      c, beg, short_hand = 'Q', ss.getch, true
    end

    if end_of_stream? or c == RubyLexer::EOF or beg == RubyLexer::EOF then
      rb_compile_error "unterminated quoted string meets end of file"
    end

    # Figure nnd-char.  "\0" is special to indicate beg=nnd and that no nesting?
    nnd = { "(" => ")", "[" => "]", "{" => "}", "<" => ">" }[beg]
    nnd, beg = beg, "\0" if nnd.nil?

    token_type, text = nil, "%#{c}#{beg}"
    token_type, string_type = case c
                              when 'Q' then
                                ch = short_hand ? nnd : c + beg
                                text = "%#{ch}"
                                [:tSTRING_BEG,   STR_DQUOTE]
                              when 'q' then
                                [:tSTRING_BEG,   STR_SQUOTE]
                              when 'W' then
                                scan(/\s*/)
                                [:tWORDS_BEG,    STR_DQUOTE | STR_FUNC_QWORDS]
                              when 'w' then
                                scan(/\s*/)
                                [:tQWORDS_BEG,   STR_SQUOTE | STR_FUNC_QWORDS]
                              when 'x' then
                                [:tXSTRING_BEG,  STR_XQUOTE]
                              when 'r' then
                                [:tREGEXP_BEG,   STR_REGEXP]
                              when 's' then
                                self.lex_state  = :expr_fname
                                [:tSYMBEG,       STR_SSYM]
                              when 'I' then
                                scan(/\s*/)
                                [:tSYMBOLS_BEG, STR_DQUOTE | STR_FUNC_QWORDS]
                              when 'i' then
                                scan(/\s*/)
                                [:tQSYMBOLS_BEG, STR_SQUOTE | STR_FUNC_QWORDS]
                              end

    rb_compile_error "Bad %string type. Expected [QqWwIixrs], found '#{c}'." if
      token_type.nil?

    raise "huh" unless string_type

    string string_type, nnd, beg

    return token_type, text
  end

  def parse_string quote # TODO: rewrite / remove
    _, string_type, term, open = quote

    space = false # FIX: remove these
    func = string_type
    paren = open
    term_re = @@regexp_cache[term]

    qwords = (func & STR_FUNC_QWORDS) != 0
    regexp = (func & STR_FUNC_REGEXP) != 0
    expand = (func & STR_FUNC_EXPAND) != 0

    unless func then # nil'ed from qwords below. *sigh*
      return :tSTRING_END, nil
    end

    space = true if qwords and scan(/\s+/)

    if self.string_nest == 0 && scan(/#{term_re}/) then
      if qwords then
        quote[1] = nil
        return :tSPACE, nil
      elsif regexp then
        return :tREGEXP_END, self.regx_options
      else
        return :tSTRING_END, term
      end
    end

    return :tSPACE, nil if space

    self.string_buffer = []

    if expand
      case
      when scan(/#(?=\$(-.|[a-zA-Z_0-9~\*\$\?!@\/\\;,\.=:<>\"\&\`\'+]))/) then
        # TODO: !ISASCII
        # ?! see parser_peek_variable_name
        return :tSTRING_DVAR, nil
      when scan(/#(?=\@\@?[a-zA-Z_])/) then
        # TODO: !ISASCII
        return :tSTRING_DVAR, nil
      when scan(/#[{]/) then
        return :tSTRING_DBEG, nil
      when scan(/#/) then
        string_buffer << '#'
      end
    end

    if tokadd_string(func, term, paren) == RubyLexer::EOF then
      rb_compile_error "unterminated string meets end of file"
    end

    return :tSTRING_CONTENT, string_buffer.join
  end
end

require "ruby_lexer.rex"

if ENV["RP_LINENO_DEBUG"] then
  class RubyLexer
    alias :old_lineno= :lineno=

    def d o
      $stderr.puts o.inspect
    end

    def lineno= n
      self.old_lineno= n
      where = caller.first.split(/:/).first(2).join(":")
      d :lineno => [n, where, ss && ss.rest[0,40]]
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jimbo.mengwa"
    >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/icon2"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".ui.ImageActivity" />

        <activity
            android:name="com.umeng.update.UpdateDialogActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" >
        </activity>

        <activity android:name=".ui.AboutActivity" />

        <service
            android:name="com.umeng.update.net.DownloadingService"
            android:process=":DownloadingService" >
        </service>

        <!-- 友盟统计 -->

        <meta-data android:value="56151059e0f55a95b3001119" android:name="UMENG_APPKEY" />
        <meta-data android:value="ALLIN" android:name="UMENG_CHANNEL"/>

    </application>

</manifest>


text:
namespace ash {

namespace {

using ::chromeos::WindowStateType;

// WindowState based on a given initial state. Records the last resize bounds.
class FakeWindowState : public WindowState::State {
 public:
  explicit FakeWindowState(WindowStateType initial_state_type)
      : state_type_(initial_state_type) {}

  FakeWindowState(const FakeWindowState&) = delete;
  FakeWindowState& operator=(const FakeWindowState&) = delete;

  ~FakeWindowState() override = default;

  // WindowState::State overrides:
  void OnWMEvent(WindowState* window_state, const WMEvent* event) override {
    if (event->IsBoundsEvent()) {
      if (event->type() == WM_EVENT_SET_BOUNDS) {
        const auto* set_bounds_event =
            static_cast<const SetBoundsWMEvent*>(event);
        last_bounds_ = set_bounds_event->requested_bounds();
        last_window_state_ = window_state;
      }
    }
  }
  WindowStateType GetType() const override { return state_type_; }
  void AttachState(WindowState* window_state,
                   WindowState::State* previous_state) override {}
  void DetachState(WindowState* window_state) override {}

  const gfx::Rect& last_bounds() const { return last_bounds_; }
  WindowState* last_window_state() { return last_window_state_; }

 private:
  WindowStateType state_type_;
  gfx::Rect last_bounds_;
  WindowState* last_window_state_ = nullptr;
};

}  // namespace

using Sample = base::HistogramBase::Sample;

class PipWindowResizerTest : public AshTestBase,
                             public ::testing::WithParamInterface<
                                 std::tuple<std::string, std::size_t>> {
 public:
  PipWindowResizerTest() = default;

  PipWindowResizerTest(const PipWindowResizerTest&) = delete;
  PipWindowResizerTest& operator=(const PipWindowResizerTest&) = delete;

  ~PipWindowResizerTest() override = default;

  void SetUp() override {
    AshTestBase::SetUp();
    SetVirtualKeyboardEnabled(true);

    const std::string& display_string = std::get<0>(GetParam());
    const std::size_t root_window_index = std::get<1>(GetParam());
    UpdateWorkArea(display_string);
    ASSERT_LT(root_window_index, Shell::GetAllRootWindows().size());
    scoped_display_ = std::make_unique<display::ScopedDisplayForNewWindows>(
        Shell::GetAllRootWindows()[root_window_index]);
    ForceHideShelvesForTest();
  }

  void TearDown() override {
    scoped_display_.reset();
    SetVirtualKeyboardEnabled(false);
    AshTestBase::TearDown();
  }

 protected:
  views::Widget* widget() { return widget_.get(); }
  aura::Window* window() { return window_; }
  FakeWindowState* test_state() { return test_state_; }
  base::HistogramTester& histograms() { return histograms_; }

  std::unique_ptr<views::Widget> CreateWidgetForTest(const gfx::Rect& bounds) {
    auto* root_window = Shell::GetRootWindowForNewWindows();
    gfx::Rect screen_bounds = bounds;
    ::wm::ConvertRectToScreen(root_window, &screen_bounds);

    std::unique_ptr<views::Widget> widget(new views::Widget);
    views::Widget::InitParams params;
    params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
    params.bounds = screen_bounds;
    params.z_order = ui::ZOrderLevel::kFloatingWindow;
    params.context = root_window;
    widget->Init(std::move(params));
    widget->Show();
    return widget;
  }

  PipWindowResizer* CreateResizerForTest(int window_component) {
    return CreateResizerForTest(window_component, window(),
                                window()->bounds().CenterPoint());
  }

  PipWindowResizer* CreateResizerForTest(int window_component,
                                         const gfx::Point& point_in_parent) {
    return CreateResizerForTest(window_component, window(), point_in_parent);
  }

  PipWindowResizer* CreateResizerForTest(int window_component,
                                         aura::Window* window,
                                         const gfx::Point& point_in_parent) {
    WindowState* window_state = WindowState::Get(window);
    window_state->CreateDragDetails(gfx::PointF(point_in_parent),
                                    window_component,
                                    ::wm::WINDOW_MOVE_SOURCE_MOUSE);
    return new PipWindowResizer(window_state);
  }

  gfx::PointF CalculateDragPoint(const WindowResizer& resizer,
                                 int delta_x,
                                 int delta_y) const {
    gfx::PointF location = resizer.GetInitialLocation();
    location.set_x(location.x() + delta_x);
    location.set_y(location.y() + delta_y);
    return location;
  }

  void Fling(std::unique_ptr<WindowResizer> resizer,
             float velocity_x,
             float velocity_y) {
    aura::Window* target_window = resizer->GetTarget();
    base::TimeTicks timestamp = base::TimeTicks::Now();
    ui::GestureEventDetails details = ui::GestureEventDetails(
        ui::ET_SCROLL_FLING_START, velocity_x, velocity_y);
    ui::GestureEvent event = ui::GestureEvent(
        target_window->bounds().origin().x(),
        target_window->bounds().origin().y(), ui::EF_NONE, timestamp, details);
    ui::Event::DispatcherApi(&event).set_target(target_window);
    resizer->FlingOrSwipe(&event);
  }

  void PreparePipWindow(const gfx::Rect& bounds) {
    widget_ = CreateWidgetForTest(bounds);
    window_ = widget_->GetNativeWindow();
    test_state_ = new FakeWindowState(WindowStateType::kPip);
    WindowState::Get(window_)->SetStateObject(
        std::unique_ptr<WindowState::State>(test_state_));
  }

 private:
  std::unique_ptr<views::Widget> widget_;
  aura::Window* window_;
  FakeWindowState* test_state_;
  base::HistogramTester histograms_;
  std::unique_ptr<display::ScopedDisplayForNewWindows> scoped_display_;

  void UpdateWorkArea(const std::string& bounds) {
    UpdateDisplay(bounds);
    for (aura::Window* root : Shell::GetAllRootWindows()) {
      WorkAreaInsets::ForWindow(root)->UpdateWorkAreaInsetsForTest(
          root, gfx::Rect(), gfx::Insets(), gfx::Insets());
    }
  }
};

TEST_P(PipWindowResizerTest, PipWindowCanDrag) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));

  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
  EXPECT_EQ(gfx::Rect(200, 210, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowCanResize) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTBOTTOM));
  ASSERT_TRUE(resizer.get());

  resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
  EXPECT_EQ(gfx::Rect(200, 200, 100, 110), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowDragIsRestrictedToWorkArea) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  // Specify point in parent as center so the drag point does not leave the
  // display. If the drag point is not in any display bounds, it causes the
  // window to be moved to the default display.
  auto landscape =
      display::Screen::GetScreen()->GetPrimaryDisplay().is_landscape();
  int right_x = landscape ? 392 : 292;
  int bottom_y = landscape ? 292 : 392;

  std::unique_ptr<PipWindowResizer> resizer(
      CreateResizerForTest(HTCAPTION, gfx::Point(250, 250)));
  ASSERT_TRUE(resizer.get());

  // Drag to the right.
  resizer->Drag(CalculateDragPoint(*resizer, 250, 0), 0);
  EXPECT_EQ(gfx::Rect(right_x, 200, 100, 100), test_state()->last_bounds());

  // Drag down.
  resizer->Drag(CalculateDragPoint(*resizer, 0, 250), 0);
  EXPECT_EQ(gfx::Rect(200, bottom_y, 100, 100), test_state()->last_bounds());

  // Drag to the left.
  resizer->Drag(CalculateDragPoint(*resizer, -250, 0), 0);
  EXPECT_EQ(gfx::Rect(8, 200, 100, 100), test_state()->last_bounds());

  // Drag up.
  resizer->Drag(CalculateDragPoint(*resizer, 0, -250), 0);
  EXPECT_EQ(gfx::Rect(200, 8, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowCanBeDraggedInTabletMode) {
  Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true);

  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
  EXPECT_EQ(gfx::Rect(200, 210, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowCanBeResizedInTabletMode) {
  Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true);

  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTBOTTOM));
  ASSERT_TRUE(resizer.get());

  resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
  EXPECT_EQ(gfx::Rect(200, 200, 100, 110), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, ResizingPipWindowDoesNotTriggerFling) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTBOTTOM));
  ASSERT_TRUE(resizer.get());

  Fling(std::move(resizer), 0.f, 4000.f);

  // Ensure that the PIP window isn't flung to the bottom edge during resize.
  EXPECT_EQ(gfx::Point(8, 8), test_state()->last_bounds().origin());
}

TEST_P(PipWindowResizerTest, PipWindowCanBeSwipeDismissed) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Drag to the left.
  resizer->Drag(CalculateDragPoint(*resizer, -100, 0), 0);

  // Should be dismissed when the drag completes.
  resizer->CompleteDrag();
  EXPECT_TRUE(widget()->IsClosed());
}

TEST_P(PipWindowResizerTest, PipWindowPartiallySwipedDoesNotDismiss) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Drag to the left, but only a little bit.
  resizer->Drag(CalculateDragPoint(*resizer, -30, 0), 0);

  // Should not be dismissed when the drag completes.
  resizer->CompleteDrag();
  EXPECT_FALSE(widget()->IsClosed());
  EXPECT_EQ(gfx::Rect(8, 8, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowInSwipeToDismissGestureLocksToAxis) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(
      CreateResizerForTest(HTCAPTION, gfx::Point(50, 50)));
  ASSERT_TRUE(resizer.get());

  // Drag to the left, but only a little bit, to start a swipe-to-dismiss.
  resizer->Drag(CalculateDragPoint(*resizer, -30, 0), 0);
  EXPECT_EQ(gfx::Rect(-22, 8, 100, 100), test_state()->last_bounds());

  // Now try to drag down, it should be locked to the horizontal axis.
  resizer->Drag(CalculateDragPoint(*resizer, -30, 30), 0);
  EXPECT_EQ(gfx::Rect(-22, 8, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest,
       PipWindowMovedAwayFromScreenEdgeNoLongerCanSwipeToDismiss) {
  PreparePipWindow(gfx::Rect(8, 16, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Drag to the right and up a bit.
  resizer->Drag(CalculateDragPoint(*resizer, 30, -8), 0);
  EXPECT_EQ(gfx::Rect(38, 8, 100, 100), test_state()->last_bounds());

  // Now try to drag to the left start a swipe-to-dismiss. It should stop
  // at the edge of the work area.
  resizer->Drag(CalculateDragPoint(*resizer, -30, -8), 0);
  EXPECT_EQ(gfx::Rect(8, 8, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowAtCornerLocksToOneAxisOnSwipeToDismiss) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Try dragging up and to the left. It should lock onto the axis with the
  // largest displacement.
  resizer->Drag(CalculateDragPoint(*resizer, -30, -40), 0);
  EXPECT_EQ(gfx::Rect(8, -32, 100, 100), test_state()->last_bounds());
}

TEST_P(
    PipWindowResizerTest,
    PipWindowMustBeDraggedMostlyInDirectionOfDismissToInitiateSwipeToDismiss) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Try a lot downward and a bit to the left. Swiping should not be initiated.
  resizer->Drag(CalculateDragPoint(*resizer, -30, 50), 0);
  EXPECT_EQ(gfx::Rect(8, 58, 100, 100), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest,
       PipWindowDoesNotMoveUntilStatusOfSwipeToDismissGestureIsKnown) {
  PreparePipWindow(gfx::Rect(8, 8, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Move a small amount - this should not trigger any bounds change, since
  // we don't know whether a swipe will start or not.
  resizer->Drag(CalculateDragPoint(*resizer, -4, 0), 0);
  EXPECT_TRUE(test_state()->last_bounds().IsEmpty());
}

TEST_P(PipWindowResizerTest, PipWindowIsFlungToEdge) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  auto landscape =
      display::Screen::GetScreen()->GetPrimaryDisplay().is_landscape();

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
    Fling(std::move(resizer), 0.f, 4000.f);

    auto origin = landscape ? gfx::Point(200, 292) : gfx::Point(200, 392);

    // Flung downwards.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 0, -10), 0);
    Fling(std::move(resizer), 0.f, -4000.f);

    // Flung upwards.
    EXPECT_EQ(gfx::Rect(200, 8, 100, 100), test_state()->last_bounds());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 10, 0), 0);
    Fling(std::move(resizer), 4000.f, 0.f);

    auto origin = landscape ? gfx::Point(392, 200) : gfx::Point(292, 200);
    // Flung to the right.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, -10, 0), 0);
    Fling(std::move(resizer), -4000.f, 0.f);

    // Flung to the left.
    EXPECT_EQ(gfx::Rect(8, 200, 100, 100), test_state()->last_bounds());
  }
}

TEST_P(PipWindowResizerTest, PipWindowIsFlungDiagonally) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  auto landscape =
      display::Screen::GetScreen()->GetPrimaryDisplay().is_landscape();

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 10, 10), 0);
    Fling(std::move(resizer), 3000.f, 3000.f);

    // Flung downward and to the right, into the corner.
    EXPECT_EQ(gfx::Rect(292, 292, 100, 100), test_state()->last_bounds());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 3, 4), 0);
    Fling(std::move(resizer), 3000.f, 4000.f);
    gfx::Point origin = landscape ? gfx::Point(269, 292) : gfx::Point(292, 322);

    // Flung downward and to the right, but reaching the bottom edge first.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }
  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 4, 3), 0);
    Fling(std::move(resizer), 4000.f, 3000.f);
    gfx::Point origin = landscape ? gfx::Point(322, 292) : gfx::Point(292, 269);
    // Flung downward and to the right, but reaching the right edge first.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, -3, -4), 0);
    Fling(std::move(resizer), -3000.f, -4000.f);

    // Flung upward and to the left, but reaching the top edge first.
    EXPECT_EQ(gfx::Point(56, 8), test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, -4, -3), 0);
    Fling(std::move(resizer), -4000.f, -3000.f);

    // Flung upward and to the left, but reaching the left edge first.
    EXPECT_EQ(gfx::Rect(8, 56, 100, 100), test_state()->last_bounds());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 3, -9), 0);
    Fling(std::move(resizer), 3000.f, -9000.f);

    // Flung upward and to the right, but reaching the top edge first.
    EXPECT_EQ(gfx::Rect(264, 8, 100, 100), test_state()->last_bounds());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 3, -3), 0);
    Fling(std::move(resizer), 3000.f, -3000.f);

    gfx::Point origin = landscape ? gfx::Point(392, 8) : gfx::Point(292, 108);
    // Flung upward and to the right, but reaching the right edge first.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, -3, 3), 0);
    Fling(std::move(resizer), -3000.f, 3000.f);

    gfx::Point origin = landscape ? gfx::Point(108, 292) : gfx::Point(8, 392);
    // Flung downward and to the left, but reaching the bottom edge first.
    EXPECT_EQ(origin, test_state()->last_bounds().origin());
  }

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, -9, 3), 0);
    Fling(std::move(resizer), -9000.f, 3000.f);

    // Flung downward and to the left, but reaching the left edge first.
    EXPECT_EQ(gfx::Rect(8, 264, 100, 100), test_state()->last_bounds());
  }
}

TEST_P(PipWindowResizerTest, PipWindowFlungAvoidsFloatingKeyboard) {
  PreparePipWindow(gfx::Rect(200, 200, 75, 75));

  auto* keyboard_controller = keyboard::KeyboardUIController::Get();
  keyboard_controller->SetContainerType(keyboard::ContainerType::kFloating,
                                        gfx::Rect(0, 0, 1, 1),
                                        base::DoNothing());
  const display::Display display = WindowState::Get(window())->GetDisplay();
  keyboard_controller->ShowKeyboardInDisplay(display);
  ASSERT_TRUE(keyboard::WaitUntilShown());

  aura::Window* keyboard_window = keyboard_controller->GetKeyboardWindow();
  keyboard_window->SetBounds(gfx::Rect(8, 150, 100, 100));

  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());

  // Fling to the left - but don't intersect with the floating keyboard.
  resizer->Drag(CalculateDragPoint(*resizer, -10, 0), 0);
  Fling(std::move(resizer), -4000.f, 0.f);

  // Appear below the keyboard.
  EXPECT_EQ(gfx::Rect(8, 258, 75, 75), test_state()->last_bounds());
}

TEST_P(PipWindowResizerTest, PipWindowDoesNotChangeDisplayOnDrag) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  const display::Display display = WindowState::Get(window())->GetDisplay();
  gfx::Rect rect_in_screen = window()->bounds();
  ::wm::ConvertRectToScreen(window()->parent(), &rect_in_screen);
  EXPECT_TRUE(display.bounds().Contains(rect_in_screen));

  // Drag inside the display.
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
  ASSERT_TRUE(resizer.get());
  resizer->Drag(CalculateDragPoint(*resizer, 10, 10), 0);

  // Ensure the position is still in the display.
  EXPECT_EQ(gfx::Rect(210, 210, 100, 100), test_state()->last_bounds());
  EXPECT_EQ(display.id(), test_state()->last_window_state()->GetDisplay().id());
  rect_in_screen = window()->bounds();
  ::wm::ConvertRectToScreen(window()->parent(), &rect_in_screen);
  EXPECT_TRUE(display.bounds().Contains(rect_in_screen));
}

TEST_P(PipWindowResizerTest, PipRestoreBoundsSetOnFling) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 10, 10), 0);
    Fling(std::move(resizer), 3000.f, 3000.f);
  }

  WindowState* window_state = WindowState::Get(window());
  EXPECT_TRUE(PipPositioner::HasSnapFraction(window_state));
}

TEST_P(PipWindowResizerTest, PipStartAndFinishFreeResizeUmaMetrics) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTBOTTOM));
  ASSERT_TRUE(resizer.get());

  EXPECT_EQ(1, histograms().GetBucketCount(kAshPipEventsHistogramName,
                                           Sample(AshPipEvents::FREE_RESIZE)));
  histograms().ExpectTotalCount(kAshPipEventsHistogramName, 1);

  resizer->Drag(CalculateDragPoint(*resizer, 100, 0), 0);
  resizer->CompleteDrag();

  histograms().ExpectTotalCount(kAshPipEventsHistogramName, 1);
}

TEST_P(PipWindowResizerTest, PipFreeResizeAreaUmaMetrics) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTBOTTOM));
  ASSERT_TRUE(resizer.get());

  EXPECT_EQ(1, histograms().GetBucketCount(
                   kAshPipFreeResizeInitialAreaHistogramName, Sample(5)));
  histograms().ExpectTotalCount(kAshPipFreeResizeInitialAreaHistogramName, 1);

  window()->layer()->SetBounds(gfx::Rect(200, 200, 100, 190));
  resizer->CompleteDrag();

  EXPECT_EQ(1, histograms().GetBucketCount(
                   kAshPipFreeResizeFinishAreaHistogramName, Sample(10)));
  histograms().ExpectTotalCount(kAshPipFreeResizeFinishAreaHistogramName, 1);
}

TEST_P(PipWindowResizerTest, DragDetailsAreDestroyed) {
  PreparePipWindow(gfx::Rect(200, 200, 100, 100));
  WindowState* window_state = WindowState::Get(window());

  {
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());

    resizer->Drag(CalculateDragPoint(*resizer, 0, 10), 0);
    EXPECT_NE(nullptr, window_state->drag_details());

    resizer->CompleteDrag();
    EXPECT_NE(nullptr, window_state->drag_details());
  }
  EXPECT_EQ(nullptr, window_state->drag_details());
}

// TODO: UpdateDisplay() doesn't support different layouts of multiple displays.
// We should add some way to try multiple layouts.
INSTANTIATE_TEST_SUITE_P(All,
                         PipWindowResizerTest,
                         testing::Values(std::make_tuple("500x400", 0u),
                                         std::make_tuple("500x400/r", 0u),
                                         std::make_tuple("500x400/u", 0u),
                                         std::make_tuple("500x400/l", 0u),
                                         std::make_tuple("1000x800*2", 0u),
                                         std::make_tuple("500x400,500x400", 0u),
                                         std::make_tuple("500x400,500x400",
                                                         1u)));

using PipWindowResizerNonSquareAspectRatioTest = PipWindowResizerTest;

TEST_P(PipWindowResizerNonSquareAspectRatioTest, PipPositionUmaMetrics) {
  histograms().ExpectTotalCount(kAshPipPositionHistogramName, 0);

  {
    // Check TOP_LEFT.
    PreparePipWindow(gfx::Rect(0, 0, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                             Sample(AshPipPosition::TOP_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 1);
  }

  {
    // Check TOP_MIDDLE.
    PreparePipWindow(gfx::Rect(100, 0, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::TOP_MIDDLE)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 2);
  }

  {
    // Check TOP_RIGHT.
    PreparePipWindow(gfx::Rect(250, 0, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::TOP_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 3);
  }

  {
    // Check MIDDLE_LEFT.
    PreparePipWindow(gfx::Rect(0, 100, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::MIDDLE_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 4);
  }

  {
    // Check MIDDLE.
    PreparePipWindow(gfx::Rect(100, 100, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                             Sample(AshPipPosition::MIDDLE)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 5);
  }

  {
    // Check MIDDLE_RIGHT.
    PreparePipWindow(gfx::Rect(250, 100, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::MIDDLE_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 6);
  }

  {
    // Check BOTTOM_LEFT.
    PreparePipWindow(gfx::Rect(0, 250, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::BOTTOM_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 7);
  }

  {
    // Check BOTTOM_MIDDLE.
    PreparePipWindow(gfx::Rect(100, 250, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::BOTTOM_MIDDLE)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 8);
  }

  {
    // Check BOTTOM_RIGHT.
    PreparePipWindow(gfx::Rect(250, 250, 100, 100));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::BOTTOM_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 9);
  }
}

TEST_P(PipWindowResizerNonSquareAspectRatioTest,
       PipPositionUmaMetricsCornerPriority) {
  histograms().ExpectTotalCount(kAshPipPositionHistogramName, 0);

  // Check corners are priotised over edges and middle.
  {
    // Check TOP_LEFT.
    PreparePipWindow(gfx::Rect(0, 0, 300, 210));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                             Sample(AshPipPosition::TOP_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 1);
  }

  {
    // Check TOP_RIGHT.
    PreparePipWindow(gfx::Rect(100, 0, 300, 210));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::TOP_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 2);
  }

  {
    // Check BOTTOM_LEFT.
    PreparePipWindow(gfx::Rect(0, 190, 300, 210));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::BOTTOM_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 3);
  }

  {
    // Check BOTTOM_RIGHT.
    PreparePipWindow(gfx::Rect(100, 190, 300, 210));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::BOTTOM_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 4);
  }
}

TEST_P(PipWindowResizerNonSquareAspectRatioTest,
       PipPositionUmaMetricsEdgePriority) {
  histograms().ExpectTotalCount(kAshPipPositionHistogramName, 0);

  // Test that edges are prioritised over middle.
  {
    // Check TOP_MIDDLE.
    PreparePipWindow(gfx::Rect(100, 0, 200, 220));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::TOP_MIDDLE)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 1);
  }

  {
    // Check BOTTOM_MIDDLE.
    PreparePipWindow(gfx::Rect(100, 80, 200, 220));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::BOTTOM_MIDDLE)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 2);
  }

  {
    // Check MIDDLE_LEFT.
    PreparePipWindow(gfx::Rect(0, 90, 300, 120));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(1,
              histograms().GetBucketCount(kAshPipPositionHistogramName,
                                          Sample(AshPipPosition::MIDDLE_LEFT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 3);
  }

  {
    // Check MIDDLE_RIGHT.
    PreparePipWindow(gfx::Rect(100, 90, 300, 120));
    std::unique_ptr<PipWindowResizer> resizer(CreateResizerForTest(HTCAPTION));
    ASSERT_TRUE(resizer.get());
    resizer->Drag(CalculateDragPoint(*resizer, 0, 0), 0);
    resizer->CompleteDrag();

    EXPECT_EQ(
        1, histograms().GetBucketCount(kAshPipPositionHistogramName,
                                       Sample(AshPipPosition::MIDDLE_RIGHT)));
    histograms().ExpectTotalCount(kAshPipPositionHistogramName, 4);
  }
}

INSTANTIATE_TEST_SUITE_P(
    All,
    PipWindowResizerNonSquareAspectRatioTest,
    testing::Values(std::make_tuple("400x300", 0u),
                    std::make_tuple("400x300,4000x3000", 0u),
                    std::make_tuple("4000x3000,400x300", 1u)));

}  // namespace ash


text:
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User

from home.forms import registration
from post.models import Channel, Question
from root.email import render_email, send_email
from threads.models import Answer
from user.models import student, Notification

def logout_view(request):
	logout(request)
	return HttpResponseRedirect(reverse('home'))

def home(request, tab="home"):
	if request.method == 'GET':
		if request.user.is_authenticated:
			username = request.user.username
			Question.objects.popularity_update()
			if tab == "home":
				question_list = Question.objects.order_by("-hot")
			elif tab == "questions":
				question_list = Question.objects.filter(
					metatype="question").order_by("-hot")
			elif tab == "unsolved":
				question_list = Question.objects.filter(
					metatype="question", solved=False).order_by("-hot")
			elif tab == "discussions":
				question_list = Question.objects.filter(
					metatype="discussion").order_by("-hot")
			trending_channels = Channel.objects.filter(trending=True)
			return render(
				request,
				'home.html',
				{
					'tab': tab,
					'question_list': question_list,
					'trending': trending_channels,
				})
		else:
			question_list = Question.objects.all().order_by("-hot")[:3]
			no_of_questions = Question.objects.filter(
				metatype="question").count()
			no_of_answers = Answer.objects.filter(
				metatype="question").count()
			no_of_discussions = Answer.objects.filter(metatype="discussion").count()
			no_of_solved = Question.objects.filter(
				metatype="question", solved=True).count()
			no_of_solved_percentage = round(
				((no_of_solved + 1) / (no_of_questions + 1)) * 100)
			return render(
				request,
				'login.html',
				{'tab': tab,
					'question_list': question_list,
					'no_of_questions': no_of_questions,
					'no_of_answers': no_of_answers,
					'no_of_discussions': no_of_discussions,
					'no_of_solved_percentage': no_of_solved_percentage})

	if request.method == 'POST' and request.POST:
		username = request.POST['username']
		password = request.POST['password']
		try:
			user = User._default_manager.get(username__iexact=username)
			user_auth = authenticate(username=user.username, password=password)
		except User.DoesNotExist:
			user_auth = None
		if user_auth is not None:
			login(request, user_auth)
			return HttpResponseRedirect(reverse('home'))
		else:
			question_list = Question.objects.all().order_by("-hot")[:3]
			return render(request, "login.html", {
				"failed": True,
				"question_list": question_list,
			})

def register(request):
	navtext = "Register!"
	if request.method == 'POST' and request.POST:
		reg_form = registration(request.POST)
		if reg_form.is_valid():
			cd = reg_form.cleaned_data
			new_user = User.objects.create_user(
				username=cd["username"],
				email=cd["email"],
				password=cd["password"])
			new_profile = student(
				bio=cd["bio"],)
			new_profile.user = new_user
			new_profile.save()
			login(request, new_user)
			mail_html = render_email("welcome.html", {'username': new_user.username, })
			opts = {
				"recipents": new_user.email,
				"subject": "Welcome aboard 🎉",
				"body": mail_html
			}
			send_email(opts)
			return HttpResponseRedirect(reverse('home'))
		else:
			return render(
				request,
				'register.html',
				{
					'regform': reg_form,
					'navtext': navtext
				})

	elif request.user.is_authenticated:
		return HttpResponseRedirect(reverse('home'))
	else:
		reg_form = registration()
		return render(
			request,
			'register.html',
			{'regform': reg_form, 'navtext': navtext})

def channel_view(request, channel_name):
	try:
		channel_name = str(channel_name)
	except ValueError:
		raise Http404()
	channel_instance = get_object_or_404(Channel, name=channel_name)
	return render(
		request,
		"channel.html",
		{'channel': channel_instance})

def notifications_view(request):
	if not request.user.is_authenticated:
		return HttpResponseRedirect(reverse('home'))
	else:
		return render(request, "notifications.html")

def notification_redirect(request, pk):
	notif = get_object_or_404(Notification, pk=pk)
	if request.user != notif.user:
		raise Http404()
	if not notif.read:
		notif.read = True
		notif.save()
	# the answer object
	answer_instance = get_object_or_404(Answer, pk=notif.object_id)
	url = answer_instance.get_absolute_url()
	return HttpResponseRedirect(url)

def test_email_templates(request):
	return render(request, "email_templates/invite.html")