text:
<?php

namespace Cougar\Util;

# Initialize the framework (disabled; should have been done by application)
#require_once(__DIR__ . "/../../cougar.php");

class Format implements iFormat
{

    /**
     * @var Defines the strings that evalutae as a boolean true
     */
    public static $boolTrue = array("true", "t", "yes", "y", "on", "1");

    /**
     * @var Defines the strings that evalutae as a boolean false
     */
    public static $boolFalse = array("false", "f", "no", "n", "off", "0");

    /**
     * @var Defines the strings that evaluate as male
     */
    public static $genderMale = array("male", "m");

    /**
     * @var Defines the strings that evaluate as female
     */
    public static $genderFemale = array("female", "f");

    /**
     * Trims whitespace from the elements in the given object. This may seem
     * redundant when PHP already has a trim function, except that this function
     * can work on strings in an array and object, and also works by reference.
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     */
    public static function trim(&$object)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    $entry = trim($entry);
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::trim($entry);
                }
            }
        }
        else if (is_string($object))
        {
            $object = trim($object);
        }
    }

    /**
     * Converts the "null" string into a null value.
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     */
    public static function null(&$object)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    if (mb_strtolower($entry) == "null")
                    {
                        $entry = null;
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::null($entry);
                }
            }
        }
        else if (is_string($object))
        {
            if (mb_strtolower($object) == "null")
            {
                $object = null;
            }
        }
    }

    /**
     * Converts string representations of a boolean (true, false, yes, T, F,
     * etc.) to an actual boolean value. If force is set to true, it will force
     * the conversion of the value. If it doesn't have any known variations, the
     * object will be set to false.
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     * @param bool $force Whether to force the conversion to boolean
     */
    public static function strToBool(&$object, $force = false)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    if (in_array(mb_strtolower($entry), self::$boolTrue))
                    {
                        $entry = true;
                    }
                    else if (in_array(mb_strtolower($entry), self::$boolFalse)
                        || $force)
                    {
                        $entry = false;
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::strToBool($entry);
                }
            }
        }
        else if (is_string($object))
        {
            if (in_array(mb_strtolower($object), self::$boolTrue))
            {
                $object = true;
            }
            else if (in_array(mb_strtolower($object), self::$boolFalse)
                || $force)
            {
                $object = false;
            }
        }
    }

    /**
     * Converts boolean values to a string (true or false)
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     */
    public static function boolToStr(&$object)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_bool($entry))
                {
                    # We do this inline for speed
                    if ($entry)
                    {
                        $entry = "true";
                    }
                    else
                    {
                        $entry = "false";
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::boolToStr($entry);
                }
            }
        }
        else if (is_bool($object))
        {
            if ($object)
            {
                $object = "true";
            }
            else
            {
                $object = "false";
            }
        }
    }

    /**
     * Resolves gender words (M, F, Male, Female) into a single character
     * representation (M, F). If the force flag is set, values that do not match
     * will be returned as null (unspecified gender)
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     * @param bool $force Whether to return a null if the object is not gender
     */
    public static function gender(&$object, $force = false)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    if (in_array(mb_strtolower($entry), self::$genderMale))
                    {
                        $entry = "M";
                    }
                    else if (in_array(mb_strtolower($entry),
                        self::$genderFemale))
                    {
                        $entry = "F";
                    }
                    else if ($force)
                    {
                        $entry = null;
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::gender($entry);
                }
            }
        }
        else if (is_string($object))
        {
            if (in_array(mb_strtolower($object), self::$genderMale))
            {
                $object = "M";
            }
            else if (in_array(mb_strtolower($object), self::$genderFemale))
            {
                $object = "F";
            }
            else if ($force)
            {
                $object = null;
            }
        }
    }

    /**
     * Resolves gender words (M, F, Male, Female) into a word representation
     * (Male, Female). If the force flag is set, values that do not match
     * will be returned as null (unspecified gender)
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     * @param bool $force Whether to return a null if the object is not gender
     */
    public static function genderWord(&$object, $force = false)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    if (in_array(mb_strtolower($entry), self::$genderMale))
                    {
                        $entry = "Male";
                    }
                    else if (in_array(mb_strtolower($entry),
                        self::$genderFemale))
                    {
                        $entry = "Female";
                    }
                    else if ($force)
                    {
                        $entry = null;
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::genderWord($entry);
                }
            }
        }
        else if (is_string($object))
        {
            if (in_array(mb_strtolower($object), self::$genderMale))
            {
                $object = "Male";
            }
            else if (in_array(mb_strtolower($object), self::$genderFemale))
            {
                $object = "Female";
            }
            else if ($force)
            {
                $object = null;
            }
        }
    }

    /**
     * Removes the word null or NULL that may occur at the end of a string
     *
     * @history
     * 2013.09.30:
     *   (AT)  Initial release
     *
     * @version 2013.09.30
     * @author (AT) Alberto Trevino, Brigham Young Univ. <alberto@byu.edu>
     *
     * @param mixed $object Object, array or string in which to operate
     */
    public static function removeNullWord(&$object)
    {
        # See if we have an array, object or string
        if (is_array($object) || is_object($object))
        {
            foreach($object as &$entry)
            {
                if (is_string($entry))
                {
                    # We do this inline for speed
                    if (mb_strtolower(mb_substr($entry, -4)) == "null")
                    {
                        $entry = trim(mb_substr($entry, 0, -4));
                    }
                }
                else if (is_object($entry) || is_array($entry))
                {
                    # Here we call ourselves to iterate through values
                    self::removeNullWord($entry);
                }
            }
        }
        else if (is_string($object))
        {
            if (mb_strtolower(mb_substr($object, -4)) == "null")
            {
                $object = trim(mb_substr($object, 0, -4));
            }
        }
    }
}
?>


text:
import logging
import os
import re

from .. import util
from .. import parsing

logger = logging.getLogger(__name__)

class BatchParameterizer(object):
    """
    Defines workflow batch parameters for a list of input samples,
    given a list of parsed parameters for a Galaxy workflow.

    :type sample_paths: list
    :param sample_paths: List of paths to sample folders, where each
        folder contains one or more lane-specifc FASTQ file(s).
    :type parameters: list
    :param parameters: List of workflow parameters, parsed from a
        workflow template file, where each parameter is represented
        by a dict with fields ``tag``, ``type``, and ``name``.
    :type target_dir: str
    :param target_dir: Path to folder where outputs are to be saved.
        Subfolders will be created within the ``target_dir`` based
        on output type.
    :type endpoint: str
    :param endpoint: Globus endpoint where input files are accessed
        and output files will be sent (e.g., 'benaroyaresearch#BRIGridFTP').
    :type build: str
    :param build: ID string of reference genome build to be used
        for processing current set of samples.
    """
    def __init__(self, sample_paths, parameters, endpoint, target_dir,
                 build='GRCh38.77', stranded=False):
        logger.debug("creating `BatchParametizer` instance ")
        self.sample_paths = sample_paths
        self.parameters = parameters
        self.endpoint = endpoint
        self.target_dir = target_dir
        self.build = build
        self.stranded = stranded

    def _get_lane_order(self):
        """
        Return the list of lane numbers (1-8) based on the order in
        which they appear for input FASTQs in the parameter list.
        """
        logger.debug("identifying lane order for input FASTQs")
        return [re.search('[1-8]', p['name']).group()
                for p in self.parameters
                if p['tag'] == 'fastq_in'
                and re.search('from_path', p['name'])]

    def _get_lane_fastq(self, sample_path, lane, read_number="R1"):
        """
        Retrieve the path for the FASTQ file from the specified lane
        within the sample folder. If no file exists, create and return
        the path of an empty FASTQ file.
        """

        logger.debug("retrieving FASTQ path for sample '{}' and lane {}"
                     .format(sample_path, lane))
        fastq_paths = [os.path.join(sample_path, f)
                       for f in os.listdir(sample_path)
                       if re.search(r'L00{}_{}'.format(lane, read_number), f)]
        if len(fastq_paths):
            fastq_path = fastq_paths[0]

        else:
            logger.debug("no FASTQ found for lane {}; creating empty file"
                         .format(lane))
            empty_fastq = 'empty_L00{}_{}.fastq.gz'.format(lane, read_number)
            fastq_path = os.path.join(sample_path, empty_fastq)

            if not os.path.exists(fastq_path):
                open(fastq_path, 'a').close()

        return fastq_path

    def _build_reference_path(self, parameter):
        """
        Given a parameter for an input annotation dataset stored in a
        library on Globus Galaxy, return the path to the dataset based
        on the current build and annotation type.
        """
        ref_dict = {
            'GRCh38.77': {
                'gtf': 'GRCh38/Homo_sapiens.GRCh38.77.gtf',
                'refflat': 'GRCh38/Homo_sapiens.GRCh38.77.refflat.txt',
                'ribosomal_intervals':
                    ('GRCh38/Homo_sapiens.GRCh38.77'
                     '.ribosomalIntervalsWheader_reorder.txt'),
                'snp-bed': 'GRCh38_NGSCheckMate_andInterestingSNP.bed',
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'GRCh38.91': {
                'gtf': 'GRCh38/Homo_sapiens.GRCh38.91.gtf',
                'refflat': 'GRCh38/Homo_sapiens.GRCh38.91.refflat.txt',
                'ribosomal_intervals':
                    ('GRCh38/Homo_sapiens.GRCh38.91'
                     '.ribosomalIntervalsWheader.txt'),
                'snp-bed': 'GRCh38_NGSCheckMate_andInterestingSNP.bed',
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'NCBIM37.67': {
                'gtf': 'NCBIM37/Mus_musculus.NCBIM37.67.gtf',
                'refflat': 'NCBIM37/Mus_musculus.NCBIM37.67.refflat.txt',
                'ribosomal_intervals':
                    ('NCBIM37/Mus_musculus.NCBIM37.67'
                     '.ribosomalIntervalsWheader_reorder.txt'),
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'GRCm38.91': {
                'gtf': 'GRCm38/Mus_musculus.GRCm38.91.gtf',
                'refflat': 'GRCm38/Mus_musculus.GRCm38.91.refflat.txt',
                'ribosomal_intervals':
                    ('GRCm38/Mus_musculus.GRCm38.91'
                     '.ribosomalIntervalsWheader.txt'),
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'hg19': {
                'mtfilter-bed': 'hg19/hg19_mitofilter.bed',
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'mm10': {
                'mtfilter-bed': 'mm10/mm10_mitofilter.bed',
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'mm9': {
                'mtfilter-bed': 'mm9/mm9_mitofilter.bed',
                'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            },
            'ebv': {
                 'gtf': 'EBV_HHV4/EBV_HHV4.gtf',
                 'refflat': 'EBV_HHV4/EBV_HHV4.refflat.txt',
                 'ribosomal_intervals': ('EBV_HHV4/EBV_HHV4'
                                         '.ribosomalIntervalsEmpty.txt'),
                 'adapters': 'adapters/smarter_adapter_seqs_3p_5p.fasta'
            }
        }

        ref_type = re.sub('^annotation_', '', parameter['tag'])
        logger.debug("retrieving reference path for build '{}' and type '{}'"
                     .format(self.build, ref_type))
        return 'library::annotation::{}'.format(
            ref_dict[self.build][ref_type]
        )

    def _set_option_value(self, parameter):
        opt_dict = {
            'GRCh38': {
                'tophat': {
                    'index': 'GRCh38',
                    'library_type': {False: 'fr-unstranded',
                                     True: 'fr-firststrand'}
                },
                'hisat2': {
                    'index': 'hg38'
                },
                'salmon': {
                    'index': 'GRCh38',
                    'strandedness': {False: 'U', True: 'SR'}
                },
                'reorderbam': {
                    'ref': 'GRCh38'
                },
                'samtools-mpileup': {
                    'ref_file': 'hg38'
                },
                'mixcr': {
                    'species': 'hsa'
                },
                'picard-align': {
                    'index': 'GRCh38'
                },
                'picard-rnaseq': {
                    'index': 'GRCh38',
                    'strand_specificity': {
                        False: 'NONE',
                        True: 'FIRST_READ_TRANSCRIPTION_STRAND'
                    }
                },
                'htseq': {
                    'stranded': {False: 'no',
                                 True: 'reverse'}
                },
                'trinity': {
                    'library_type': {False: 'None',
                                     True: 'F'}
                }
            },
            'NCBIM37': {
                'tophat': {
                    'index': 'NCBIM37',
                    'library_type': {False: 'fr-unstranded',
                                     True: 'fr-firststrand'}
                },
                'hisat2': {
                    'index': 'NCBIM37'
                },
                'salmon': {
                    'index': 'NCBIM37',
                    'strandedness': {False: 'U', True: 'SR'}
                },
                'reorderbam': {
                    'ref': 'NCBIM37'
                },
                'mixcr': {
                    'species': 'mus'
                },
                'picard-align': {
                    'index': 'NCBIM37'
                },
                'picard-rnaseq': {
                    'index': 'NCBIM37',
                    'strand_specificity': {
                        False: 'NONE',
                        True: 'FIRST_READ_TRANSCRIPTION_STRAND'
                    }
                },
                'htseq': {
                    'stranded': {False: 'no',
                                 True: 'reverse'}
                },
                'trinity': {
                    'library_type': {False: 'None',
                                     True: 'F'}
                }
            },
            'ebv': {
                'tophat': {
                    'index': 'EBV',
                    'library_type': {False: 'fr-unstranded',
                                     True: 'fr-firststrand'}
                },
                'salmon': {
                    'index': 'EBV'
                },
                'reorderbam': {
                    'ref': 'EBV'
                },
                'mixcr': {
                    'species': 'EBV'
                },
                'picard-align': {
                    'index': 'EBV'
                },
                'picard-rnaseq': {
                    'index': 'EBV',
                    'strand_specificity': {
                        False: 'NONE',
                        True: 'FIRST_READ_TRANSCRIPTION_STRAND'
                    }
                },
                'htseq': {
                    'stranded': {False: 'no',
                                 True: 'reverse'}
                },
                'trinity': {
                    'library_type': {False: 'None',
                                     True: 'F'}
                }
            },
            'hg19': {
                'bowtie2': {
                    'index': 'hg19'
                },
                'picard-align': {
                    'index': 'hg19'
                },
                'macs2': {
                    'gsize': '2451960000'
                }
            },
            'mm10': {
                'bowtie2': {
                    'index': 'mm10'
                },
                'picard-align': {
                    'index': 'mm10'
                },
                'macs2': {
                    'gsize': '2150570000'
                }
            }
        }
        opt_tool = re.sub('^option_', '', parameter['tag'])
        opt_name = parameter['name']
        logger.debug("retrieving option value for build '{}', tool '{}', "
                     "and option name '{}'"
                     .format(self.build, opt_tool, opt_name))
        try:
            opt_val = opt_dict[self.build][opt_tool][opt_name]
            if type(opt_val) is dict:
                return opt_val[self.stranded]
            else:
                return opt_val

        except KeyError:
            logger.exception(("no option value available for option '{}' "
                              "of tool '{}' for build '{}'; build '{}' is "
                              "probably unsupported for selected workflow")
                             .format(opt_name, opt_tool,
                                     self.build, self.build))
            raise

    def _prep_output_dir(self, output_type):
        """
        Create a subfolder in the ``target_dir`` to store outputs of
        the specified type, return folder path.
        """
        output_dir = os.path.join(self.target_dir, output_type)
        logger.debug("creating folder '{}' to store outputs of type '{}'"
                     .format(output_dir, output_type))
        if not os.path.isdir(output_dir):
            os.makedirs(output_dir)

        return output_dir

    def _build_output_path(self, sample_name, parameter):
        """
        Construct the full path of the current output file, formatted
        with the sample name and source/type-specific file label (as
        well as the appropriate extension).
        """
        output_type_map = {'trimmed': 'TrimmedFastqs',
                           'counts': 'counts',
                           'quant': 'quant',
                           'alignments': 'alignments',
                           'metrics': 'metrics',
                           'qc': 'QC',
                           'trinity': 'Trinity',
                           'assembly': 'assembly',
                           'clones': 'clones',
                           'snps': 'snps',
                           'peaks': 'peaks',
                           'log': 'logs',
                           'unmapped': 'unmapped'}

        logger.debug("building output path of parameter '{}' for sample '{}'"
                     .format(parameter['tag'], sample_name))
        output_items = parsing.parse_output_name(parameter['tag'])
        output_dir = self._prep_output_dir(
            output_type_map[output_items['type']]
        )

        out_file = '{}_{}_{}.{}'.format(
            sample_name, output_items['source'], output_items['label'],
            output_items['extension']
        )

        return util.swap_root(os.path.join(output_dir, out_file),
                              'pipeline', '/mnt/bioinformatics/')

    def _build_sample_parameters(self, sample_path):
        """
        For a given input sample folder, create and set all parameter
        values for input paths, output paths, and other options.
        """
        sample_id = parsing.get_sample_id(sample_path)
        fc_id = parsing.get_flowcell_id(sample_path)
        sample_name = '{}_{}'.format(sample_id, fc_id).rstrip('_')

        logger.debug("setting parameter values for sample '{}'"
                     .format(sample_name))
        param_values = []
        for param in self.parameters:
            logger.debug("... current parameter: {}".format(param))
            if re.search('endpoint', param['name']):
                param_values.append(self.endpoint)
            elif param['type'] == 'sample':
                param_values.append(sample_name)
            elif param['type'] == 'input':
                if re.search('^fastq_in', param['tag']):
                    lane = re.search('[1-8]', param['name']).group()
                    param_values.append(
                        util.swap_root(
                            self._get_lane_fastq(sample_path, lane),
                            'pipeline', '/mnt/bioinformatics/'
                        )
                    )
                elif re.search('^fastq-r1_in', param['tag']):
                    lane = re.search('[1-8]', param['name']).group()
                    param_values.append(
                        util.swap_root(
                            self._get_lane_fastq(sample_path, lane, "R1"),
                            'pipeline', '/mnt/bioinformatics/'
                        )
                    )
                elif re.search('^fastq-r2_in', param['tag']):
                    lane = re.search('[1-8]', param['name']).group()
                    param_values.append(
                        util.swap_root(
                            self._get_lane_fastq(sample_path, lane, "R2"),
                            'pipeline', '/mnt/bioinformatics/'
                        )
                    )
            elif param['type'] == 'annotation':
                param_values.append(self._build_reference_path(param))
            elif param['type'] == 'option':
                param_values.append(self._set_option_value(param))
            elif param['type'] == 'output':
                if re.search('^fastq_out', param['tag']):
                    final_fastq = '{}_R1-final.fastq.gz'.format(sample_name)
                    output_path = os.path.join(
                        util.swap_root(self.target_dir, 'pipeline', '/mnt/bioinformatics/'),
                        'inputFastqs', final_fastq
                    )
                    self._prep_output_dir('inputFastqs')
                elif re.search('^fastq-r1_out', param['tag']):
                    final_fastq = '{}_R1-final.fastq.gz'.format(sample_name)
                    output_path = os.path.join(
                        util.swap_root(self.target_dir, 'pipeline', '/mnt/bioinformatics/'),
                        'inputFastqs', final_fastq
                    )
                    self._prep_output_dir('inputFastqs')
                elif re.search('^fastq-r2_out', param['tag']):
                    final_fastq = '{}_R2-final.fastq.gz'.format(sample_name)
                    output_path = os.path.join(
                        util.swap_root(self.target_dir, 'pipeline', '/mnt/bioinformatics/'),
                        'inputFastqs', final_fastq
                    )
                    self._prep_output_dir('inputFastqs')
                else:
                    output_path = self._build_output_path(sample_name, param)
                param_values.append(output_path)
            logger.debug("... value set: '{}'".format(param_values[-1]))

        return param_values

    def parameterize(self):
        """
        Set all parameter values for the current workflow and input
        samples and return as list of sample parameters.

        :rtype: list
        :return: List of lists, where the original input list of
            parameter dicts has been replicated for each sample and
            updated to include values specific for that sample.
        """
        sample_params = []
        for s in self.sample_paths:
            logger.debug("setting parameters for input sample file '{}'"
                         .format(s))
            s_values = self._build_sample_parameters(s)
            s_params = []
            for idx, v in enumerate(s_values):
                s_param = self.parameters[idx].copy()
                s_param['value'] = s_values[idx]
                s_params.append(s_param)
            sample_params.append(s_params)

        self.samples = sample_params

redpajama_set_name: RedPajamaGithub


text:
AStealthyAssessmentCharacter::AStealthyAssessmentCharacter()
{
	// Set size for collision capsule
	GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

	// set our turn rates for input
	BaseTurnRate = 45.f;
	BaseLookUpRate = 45.f;

	// Don't rotate when the controller rotates. Let that just affect the camera.
	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw = false;
	bUseControllerRotationRoll = false;

	// Configure character movement
	GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
	GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
	GetCharacterMovement()->JumpZVelocity = 600.f;
	GetCharacterMovement()->AirControl = 0.2f;

	// Create a camera boom (pulls in towards the player if there is a collision)
	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	CameraBoom->AttachTo(RootComponent);
	CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character
	CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller

	// Create a follow camera
	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
	FollowCamera->AttachTo(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
	FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

	// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
	// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}

void AStealthyAssessmentCharacter::BeginPlay()
{
	// Fetch all pointlights in the level and add them to the TArray
	for (TActorIterator<APointLight> AItr(GetWorld()); AItr; ++AItr)
	{
		PointLights.Emplace(*AItr);
	}

    Super::BeginPlay();
}

void AStealthyAssessmentCharacter::Tick(float DeltaSeconds)
{
	CurrentTraceTime += DeltaSeconds;
	if (CurrentTraceTime >= MaxTraceTime)
	{
		PerformLightTraces();
		CurrentTraceTime = 0;
	}
}

void AStealthyAssessmentCharacter::PerformLightTraces()
{
	FCollisionQueryParams TraceParams = FCollisionQueryParams(false);
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = false;

	FHitResult Hit(ForceInit);

	auto Start = GetActorLocation();

	for (auto& Light : PointLights)
	{
		auto End = Cast<APointLight>(Light)->GetActorLocation();

		// Perform a line trace between the player and the current PointLight
		GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility, TraceParams);

		if (!Hit.bBlockingHit)
		{

		}
	}
}

//////////////////////////////////////////////////////////////////////////
// Input

void AStealthyAssessmentCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
	// Set up gameplay key bindings
	check(InputComponent);
	InputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
	InputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);

	InputComponent->BindAxis("MoveForward", this, &AStealthyAssessmentCharacter::MoveForward);
	InputComponent->BindAxis("MoveRight", this, &AStealthyAssessmentCharacter::MoveRight);

	// We have 2 versions of the rotation bindings to handle different kinds of devices differently
	// "turn" handles devices that provide an absolute delta, such as a mouse.
	// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
	InputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
	InputComponent->BindAxis("TurnRate", this, &AStealthyAssessmentCharacter::TurnAtRate);
	InputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
	InputComponent->BindAxis("LookUpRate", this, &AStealthyAssessmentCharacter::LookUpAtRate);

	// handle touch devices
	InputComponent->BindTouch(IE_Pressed, this, &AStealthyAssessmentCharacter::TouchStarted);
	InputComponent->BindTouch(IE_Released, this, &AStealthyAssessmentCharacter::TouchStopped);
}

void AStealthyAssessmentCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
	// jump, but only on the first touch
	if (FingerIndex == ETouchIndex::Touch1)
	{
		Jump();
	}
}

void AStealthyAssessmentCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
	if (FingerIndex == ETouchIndex::Touch1)
	{
		StopJumping();
	}
}

void AStealthyAssessmentCharacter::TurnAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}

void AStealthyAssessmentCharacter::LookUpAtRate(float Rate)
{
	// calculate delta for this frame from the rate information
	AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}

void AStealthyAssessmentCharacter::MoveForward(float Value)
{
	if ((Controller != NULL) && (Value != 0.0f))
	{
		// find out which way is forward
		const FRotator Rotation = Controller->GetControlRotation();
		const FRotator YawRotation(0, Rotation.Yaw, 0);

		// get forward vector
		const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		AddMovementInput(Direction, Value);
	}
}

void AStealthyAssessmentCharacter::MoveRight(float Value)
{
	if ((Controller != NULL) && (Value != 0.0f))
	{
		// find out which way is right
		const FRotator Rotation = Controller->GetControlRotation();
		const FRotator YawRotation(0, Rotation.Yaw, 0);

		// get right vector
		const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		// add movement in that direction
		AddMovementInput(Direction, Value);
	}
}


text:
{% extends "base.html" %}
{% set active_page = "configuration" %}
{% block head %}
    {{ super() }}

{% endblock %}

{% block content %}

Error.

		<form id="configForm">

						Plant
						Enabled
						Dry
						Index

					{% for row in configTable %}

							<input type="text" name={{ 'name%d' % row['plant'] }} value={{ row['name'] }} class="textField" />
							{% if row['enabled'] == 0 %}
								<input type="checkbox" name={{ 'enabled%d' % row['plant'] }} />
							{% else %}
								<input type="checkbox" name={{ 'enabled%d' % row['plant'] }} checked/>
							{% endif %}
							<input type="text" name={{ 'dry%d' % row['plant'] }} value={{ row['dry'] }} class="textField" />
							{{ '%d' % row['plant'] }}

					{% endfor %}

					{% for i in range(configSize, NUM_PLANTS) %}

							<input type="text" name={{ 'name%d' % i }} value={{ 'plant%d' % i}} class="textField" />
							<input type="checkbox" name={{ 'enabled%d' % i }}/>
							<input type="text" name={{ 'dry%d' % i }} value="200" class="textField" />
							{{ i }}

					{% endfor %}

				<input type="button" value="Save" class="button" id="submit_btn" style="margin-left: auto; margin-right: auto;"/>

		</form>
{% endblock %}


text:
using System;
using Robust.Shared.Serialization;

namespace Content.Shared.GameObjects.Components.Morgue
{
    [Serializable, NetSerializable]
    public enum MorgueVisuals
    {
        Open,
        HasContents,
        HasMob,
        HasSoul,
    }

    [Serializable, NetSerializable]
    public enum CrematoriumVisuals
    {
        Burning,
    }

    [Serializable, NetSerializable]
    public enum BodyBagVisuals
    {
        Label,
    }
}


text:
"""Tests for the batch sim client and worker modules.

Testing either component independently doesn't offer much benefit since you end
up having to mock or fake the behavior of the other.
"""

import contextlib
import json
import os
import unittest

import gflags
import h5py
import makani
from makani.lib.python import os_util
from makani.lib.python import test_util
from makani.lib.python.batch_sim import client as client_module
from makani.lib.python.batch_sim import testing_fakes
from makani.lib.python.batch_sim import worker as worker_module
import mock
import numpy as np

FLAGS = gflags.FLAGS

_SIM_TIME = 120.0

class TestSimClient(client_module.BatchSimClient):

  _BASE_PATH = 'path/to/base_target'

  def __init__(self, **kwargs):
    super(TestSimClient, self).__init__('fake_worker_main.py', **kwargs)
    self.total_sim_time = 0.0

  def _GenerateConfigs(self):
    for i in xrange(10):
      yield {
          'config_index': i,
          'sim': {'phys_sim': {'wind_database': {'name': ''}},
                  'sim_time': _SIM_TIME}
          }

  @client_module.JsonReducer
  def _ReduceWorkerOutput(self, outputs):
    for output in outputs:
      self.total_sim_time += output['final_time']

class FakeBinaries(testing_fakes.FakeBinaries):

  def Controller(self, args):
    self._config_file = self._ParseArg(args, '--all_params')
    # Simulate being terminated with SIGINT.
    return -2

  def GroundEstimator(self, args):
    self._config_file = self._ParseArg(args, '--all_params')
    # Simulate being terminated with SIGINT.
    return -2

  def Simulator(self, args):
    self._config = json.load(open(self._config_file, 'r'))
    return 0

  def PcapToHdf5(self, args):
    input_filename = self._ParsePositionalArg(args, 0)
    if not os.path.isfile(input_filename):
      raise ValueError('First positional arg to pcap_to_hdf5 (%s) is '
                       'not a file.' % input_filename)

    self._output_file = self._ParseArg(args, '--output_file')
    num_samples = 10  # Arbitrary
    telem_time = np.linspace(0.0, self._config['sim']['sim_time'], num_samples)

    with contextlib.closing(test_util.CreateSampleHDF5File(
        self._output_file, num_samples)) as log_file:
      sim_node = log_file['messages']['kAioNodeSimulator']
      with test_util.H5DatasetWriter(sim_node['kMessageTypeSimTelemetry']) as s:
        s['message']['time'] = telem_time

      control_node = log_file['messages']['kAioNodeControllerA']
      with test_util.H5DatasetWriter(
          control_node['kMessageTypeControlDebug']) as c:
        c['message']['time'] = telem_time

    return 0

class GoodWorker(worker_module.BatchSimWorker):
  """This worker performs a simple transformation of the log file."""

  def _ProcessSimOutput(self, unused_config_id, sim_success, log_file_name):
    assert sim_success
    with contextlib.closing(h5py.File(log_file_name, 'r')) as log_file:
      sim_time = (log_file['messages']['kAioNodeSimulator']
                  ['kMessageTypeSimTelemetry']['message']['time'])
      return json.dumps({'final_time': sim_time[-1]})

class BadWorker(worker_module.BatchSimWorker):
  """This worker dies horribly so we can test the client's error-handling."""

  def _ProcessSimOutput(self, unused_config_id, unused_sim_success,
                        log_file_name):
    raise testing_fakes._FakeError('Oh no!')

class BatchSimClientTest(unittest.TestCase):

  SIM_NAME = 'test_sim'
  NUM_WORKERS = 3

  BINARY_MAP = {os.path.join(makani.HOME, k): v for k, v in [
      ('control/sim_controller', 'Controller'),
      ('lib/pcap_to_hdf5/pcap_to_hdf5', 'PcapToHdf5'),
      ('sim/sim', 'Simulator'),
      ('control/sim_ground_estimator', 'GroundEstimator')]}

  def testSuccess(self):
    patch = testing_fakes.PatchAllFakes(
        binary_map=self.BINARY_MAP, binaries=FakeBinaries(),
        worker_factory=GoodWorker, client_class=TestSimClient)

    with patch:
      client = TestSimClient(sim_name=self.SIM_NAME,
                             num_workers=self.NUM_WORKERS)
      client.Run()

    self.assertAlmostEqual(10 * _SIM_TIME, client.total_sim_time)

  @test_util.FlagValueSaver()
  def testMaxJobsPerWorker(self):
    for max_jobs, expected_num_workers in zip([1, 2, 3, 4, 5],
                                              [10, 5, 4, 3, 2]):
      FLAGS.max_jobs_per_worker = max_jobs

      patch = testing_fakes.PatchAllFakes(
          binary_map=self.BINARY_MAP, binaries=FakeBinaries(),
          worker_factory=GoodWorker, client_class=TestSimClient)

      with patch:
        client = TestSimClient(sim_name=self.SIM_NAME)
        client.Run()

      self.assertAlmostEqual(10 * _SIM_TIME, client.total_sim_time)
      self.assertEqual(expected_num_workers, client._num_workers)

  @test_util.FlagValueSaver()
  def testReduceOnly(self):
    with os_util.TempDir() as temp_dir:
      FLAGS.local_output_dir = temp_dir

      # Run a normal batch sim to generate local worker outputs.
      with testing_fakes.PatchAllFakes(
          binary_map=self.BINARY_MAP, binaries=FakeBinaries(),
          worker_factory=GoodWorker, client_class=TestSimClient):
        client = TestSimClient(sim_name=self.SIM_NAME,
                               num_workers=self.NUM_WORKERS)
        client.Run()
      self.assertAlmostEqual(10 * _SIM_TIME, client.total_sim_time)

      # Run a reduce-only client with patches that will make it crash horribly
      # if it does anything other than reducing.
      FLAGS.reduce_only = True
      with testing_fakes.PatchAllFakes(binary_map=None,
                                       binaries=None,
                                       worker_factory=None,
                                       client_class=TestSimClient):
        reducer_client = TestSimClient(sim_name=self.SIM_NAME,
                                       num_workers=self.NUM_WORKERS)
        reducer_client.Run()
      self.assertAlmostEqual(10 * _SIM_TIME, client.total_sim_time)

  def testError(self):
    patch = testing_fakes.PatchAllFakes(
        binary_map=self.BINARY_MAP, binaries=FakeBinaries(),
        worker_factory=BadWorker, client_class=TestSimClient)

    with patch, mock.patch(
        'makani.lib.python.batch_sim.client.logging') as mock_log:
      client = TestSimClient(sim_name=self.SIM_NAME,
                             num_workers=self.NUM_WORKERS)
      client.Run()

    self.assertTrue(mock_log.error.called)
    self.assertEqual(0.0, client.total_sim_time)
    self.assertEqual({}, client._gcompute.metadata_by_instance_name)

  def testNoDeleteWorkersOnError(self):
    patch = testing_fakes.PatchAllFakes(
        binary_map=self.BINARY_MAP, binaries=FakeBinaries(),
        worker_factory=BadWorker, client_class=TestSimClient)

    with patch, mock.patch(
        'makani.lib.python.batch_sim.client.logging') as mock_log:
      with test_util.FlagValueSaver():
        FLAGS.delete_workers_on_error = False
        client = TestSimClient(sim_name=self.SIM_NAME,
                               num_workers=self.NUM_WORKERS)
        client.Run()

    self.assertTrue(mock_log.error.called)
    self.assertEqual(0.0, client.total_sim_time)
    self.assertEqual(self.NUM_WORKERS,
                     len(client._gcompute.metadata_by_instance_name))

if __name__ == '__main__':
  unittest.main()


text:
package citrus.scheme.base;

import citrus.type.*;
import citrus.scheme.base.equivalence.Eqv;

import static citrus.util.List.*;

import java.lang.IllegalArgumentException;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

public class EqvTest {
    private Eqv eqv;

    @Before
    public void beforeTest() {
        eqv = new Eqv();
    }

    @Test(expected= IllegalArgumentException.class)
    public void eqvWhenGivenOneArgumentThrowsException() {
        SchemeList args = list(new TestObject());
        eqv.apply(args);
    }

    @Test(expected= IllegalArgumentException.class)
    public void eqvWhenGivenThreeArgumentsThrowsException() {
        SchemeList args = list(new TestObject(), new TestObject(), new TestObject());
        eqv.apply(args);
    }

    @Test
    public void eqvWhenGivenTwoTrueBoolsThenReturnsTrue() {
        SchemeList args = list(new Bool(true), new Bool(true));
        assertEquals(new Bool(true), eqv.apply(args));
    }

    @Test
    public void eqvWhenGivenTwoFalseBoolsThenReturnsTrue() {
        SchemeList args = list(new Bool(false), new Bool(false));
        assertEquals(new Bool(true), eqv.apply(args));
    }

    @Test
    public void eqvWhenGivenOneTrueAndOneFalseBoolThenReturnsFalse() {
        SchemeList args = list(new Bool(true), new Bool(false));
        assertEquals(new Bool(false), eqv.apply(args));
    }

    @Test
    public void eqvWhenGivenTwoSymbolsAndAreTheSameThenReturnsTrue() {
        SchemeList args = list(new Symbol("test"), new Symbol("test"));
        assertEquals(new Bool(true), eqv.apply(args));
    }

    @Test
    public void eqvWhenGiveTwoSymbolsAndAreDifferentThenReturnsFalse() {
        SchemeList args = list(new Symbol("foo"), new Symbol("false"));
        assertEquals(new Bool(false), eqv.apply(args));
    }
}


text:
package io.werval.doc;

import java.io.IOException;
import java.nio.CharBuffer;

import org.sitemesh.builder.SiteMeshOfflineBuilder;
import org.sitemesh.offline.SiteMeshOffline;
import org.sitemesh.offline.directory.Directory;
import org.sitemesh.offline.directory.InMemoryDirectory;

import static io.werval.util.Charsets.UTF_8;
import static io.werval.util.InputStreams.BUF_SIZE_4K;
import static io.werval.util.InputStreams.readAllAsString;

/**
 * SiteMesh Helper.
 *
 * Use SiteMesh to decorate HTML pages.
 * <p>
 * Damn simple, pretty slow, but this is not production code so ... optimize only if needed.
 */
/* package */ final class SiteMeshHelper
{
    /* package */ static String decorate( String path, String html )
        throws IOException
    {
        Directory source = new InMemoryDirectory( UTF_8 );
        Directory destination = new InMemoryDirectory( UTF_8 );

        String decorator = readAllAsString(
            SiteMeshHelper.class.getResourceAsStream( "decorator.html" ),
            BUF_SIZE_4K,
            UTF_8
        );
        source.save( "decorator.html", CharBuffer.wrap( decorator.toCharArray() ) );

        SiteMeshOffline sitemesh = new SiteMeshOfflineBuilder()
            .setSourceDirectory( source )
            .setDestinationDirectory( destination )
            .addDecoratorPath( "/*", "decorator.html" )
            .create();

        CharBuffer result = sitemesh.processContent( path, CharBuffer.wrap( html.toCharArray() ) );

        return result.toString();
    }

    private SiteMeshHelper()
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <Costura IncludeDebugSymbols='false' />
</Weavers>


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome.css">

        Aidan O'Gorman

Home

My Work

Skills

Blog

Contact


text:
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

class Profile(models.Model):

    user = models.OneToOneField(User)
    name = models.CharField(max_length=100, blank=True, verbose_name="name", db_index=True)
    secret = models.CharField(max_length=100, blank=True, verbose_name="secret_key", db_index=True)
    device_id = models.CharField(max_length=400, blank=True, verbose_name="device_id", db_index=True)
    picture_url = models.URLField(blank=True, verbose_name="User Avatar / Company Logo")

    street_address_1 = models.CharField(max_length=100, blank=True, verbose_name="street_address_1")
    street_address_2 = models.CharField(max_length=100, blank=True, verbose_name="street_address_2")
    street_address_3 = models.CharField(max_length=100, blank=True, verbose_name="street_address_3")


text:
<!DOCTYPE html>

      <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="shortcut icon" href="https://iigkid.github.io/jekyll-mexpro-roxanna/images/favicon.ico">

  <title>Mexican Insurance Site Map | Mexpro</title>
  <meta name="description" content="Use Mexpro's site map to learn about Mexico auto, home, international health, motorcycle and RV insurance. Get your questions answered and find what you're l...">

  <link rel="canonical" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/sitemap.html">

  <link rel="alternate" hreflang="en" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/sitemap.html">

  <link rel="alternate" hreflang="es-MX" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mx/mapa-sitio.html">

  <link rel="alternate" type="application/rss+xml" title="Mexpro Mexico Insurance Professionals" href="https://iigkid.github.io/jekyll-mexpro-roxanna/feed.xml">

    <link type="text/css" rel="stylesheet" href="/jekyll-mexpro-roxanna/assets/main-bd695a7df6bba672e6a620e2dc0cedd0a81c0283a40307b363cdec8b408b2272.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>

        <button type="button" onclick="location.href='tel:+18556397761'" class="btn btn-mobile"> 1-855-MEXPRO1</button>

              Español

             1-855-MexPro1

             Search Mexpro

                Home

                Español

<button class="btn btn-buy btn-xs" onclick="location.href='https://www.mexpro.com/en-US/quotes/new/?agtdst=buytopnav#/'" type="button"> BUY NOW</button>

<button type="button" class="btn btn-login btn-xs" data-href="#customer-login-topnav" data-toggle="modal" data-target="#customer-login-topnav"> LOG IN</button>

                Insurance

Auto

Motorcycle

RV

USA Tourist Auto

Mexico Resident Auto

Homeowners

Boat/Watercraft

Travel Health

Travel Medical Evacuation

                Customer Service

                Claims

                About

                 1-855-MexPro1

<button type="button" class="btn btn-login btn-xs" data-href="#customer-login-topnav" data-toggle="modal" data-target="#customer-login-topnav"> LOG IN</button>

<button class="btn btn-buy btn-xs" onclick="location.href='https://www.mexpro.com/en-US/quotes/new/?agtdst=buytopnav#/'" type="button"> BUY NOW</button>

    <form action="https://www.mexpro.com/client_login/do/login.mhtml?aff_id=2149&agtdst=logintopnav" method="POST" name="log-in">

          <button type="button" class="close" data-dismiss="modal">x</button>

Purchased With Us Before?

If you purchased with us before, you can quickly re-issue a new policy.
Click here to set up a password.

Already Have Your Password?

          <fieldset>
            <input type="text" class="form-control cl_username" name="username" placeholder="Email">

            <input type="password" class="form-control cl_password" name="password" placeholder="Password">
          </fieldset>

          <button type="button" class="btn btn-close" data-dismiss="modal" aria-hidden="true">Close</button>
          <input type="submit" class="btn btn-primary" value="Login" >

    </form>

Mexpro Mexican Insurance Site Map / Directory of Web Pages

Mexpro Home Page

Our Products

Mexico Auto/SUV/RV/Motorcycle Insurance

Mexico Auto/SUV/RV/Motorcycle Insurance QUOTE

Mexican Auto Insurance

New 2014 Mexico Insurance Auto Law

Why Mexpro Supports New Mexico Insurance Laws

Three New Mexico Auto Insurance Laws & Their Descriptions

Comparison of all Auto Companies/Coverage

Why Buy Mexico Auto Insurance from Mexpro?

Does US/Canada Auto Insurance Provide Coverage in Mexico?

Two Reasons you need Mexico Auto Insurance

Driver's License Policy

Coverage on a Driver's License Policy

Mexico Motorcycle Insurance

Motorcycle Coverage for Mexico

Mexico RV Insurance

More on RV Insurance Mexico

Towed Units on a Mexico Insurance Policy

Mexico Homeowners Insurance Mexico

Mexico Homeowners Insurance Quote

Home Owners Coverage

Condo Coverage

Home Insurance FAQs

Homeowners Insurance Partners

Reliable & Affordable Mexico Homeowners Insurance

Why Home owners Insurance with Mexpro

Mexico Boat Insurance

Mexico Boat/Watercraft/Jet Ski Insurance Quote

Mexico Boat Insurance FAQs

Mexico Travel Health Insurance

Mexico Travel Health Insurance Quote

More on Travel Health Insurance

Insuring a Mexican Vehicle in the US

Northbound Auto Insurance Quote

Short Term US Auto Insurance Coverage

Accident Claims

More Information About US Insurance

The Safety of Your Online Transaction

U.S. RV Insurance

FAQs - Frequently Asked Questions on Mexican Insurance.

Buying Insurance FAQs

Coverage FAQs

Driving to Mexico - questions on driving a vehicle to Mexico.

Vehicle Importation FAQs

Site Functionality - completing applications, website functionality, safety of personal information.

Coverage

More Coverage Information

What type of insurance coverage do I need?

What type of Coverage is Needed for Persons and Legal/Travel?

What type of Coverage do I need for my car?

Coverage Overview

Basic Liability Package

Legal Assistance

Medical Payments

MexVisit Travel Assistance

MexVisit Benefits

Driver's License Policy

Coverage Comparisons

Standard Mexico Insurance Coverage Comparison

Extended Mexican Insurance Coverage Comparison

Comparison of all Coverage

Physical Damage

Travel Assistance

Deductibles

Determining Vehicle Value

Auto Insurance Differences, Exclusions, Quirks

Lay-up Provision for Extended Mexico Trips

Insurers / Insurance Partners

ABA Seguros

ABA Seguros Plus Insurance Package

ABA Seguros Claims Instructions

El Aguila

El Aguila Extended Coverage Auto Insurance

El Aguila Claims Instructions

Grupo Nacional Provincial (GNP)

Grupo Nacional Provincial (GNP) Deluxe Insurance Package

GNP Homeowners Insurance

GNP Press Release / A.M. Best.

GNP Claims Instructions.

Mexico Insurance Company Rankings

Comparison of all Auto Companies/Coverage

"A Rated" - What it Means

Claims

Instructions on Making a Claim

What to Expect when Making a Claim

Customer Service

Service Center Requests at a Glance

In Effect Policy Cancellations

Not Yet In Effect Policy Cancellations

Auto Policy Refunds

About Mexpro

Meet Mexpro

Our Licensed Agents

Mexpro Blog

Why Mexpro?

Mexpro Press Releases

Articles about Mexpro

Mexpro Customer Testimonials

Driving to Mexico

Before you go to Mexico

Mexico Vehicle Importation Permits

RV/Travel Trailer Vehicle Import Permit (for up to 10 Years)

Sonora Only Vehicle Import Permit

Vehicle Import Permit FAQs

Mexico Maps

Mexico Road Logs

Mexico Survival Kit

How to Handle a Traffic Incident in Baja, Mexico

Blog / News

Handy Resources & Links

Other

About Purchasing Mexico Insurance - for your protection

Getting Quality Mexico Insurance

Contact Mexpro

Customer Login - previous customers.

Retrieve a Previous Mexpro Quote

PRIVACY STATEMENT

Agents / Brokers & Advertisers - sell our Mexico Insurance online products.

Mexico Insurance

Vehicle Insurance

Mexico Tourist Auto

USA Tourist Auto

Mexico Resident Auto

Specialty Insurance

Boat & Personal Watercraft

Mexico Homeowners

Travel Health Insurance

Travel Medical Evacuation

Mexico Travel Tips

Temporary Importation Permits

MexVisit Travel Assistance

Before You Go

About Mexpro

About Us

Customer Service

Claims

FAQs

Blog

Contact Us

Buy Online

Call Us

Visit Our Office

 1-855-MexPro1 Toll Free

©1999 - 2018 Mexpro - Mexico Insurance Professionals

DBA Mexico & RV Insurance Services

CA License Number 0D06599

214 East Birch Avenue, Flagstaff, Arizona 86001

+1-928-214-9750

Site Map

 1-855-MexPro1 Toll Free

    <link type="text/css" rel="stylesheet" href="/jekyll-mexpro-roxanna/assets/bottom-5e274eb7234ad380d4e9aec88919e1c21649e8009a6d9a1175534c7756b173f1.css">


text:
package org.elasticsearch.index.query;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType;

import java.io.IOException;

/**
 * A Span Query that matches documents containing a term.
 * @see SpanTermQuery
 */
public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuilder> implements SpanQueryBuilder {
    public static final String NAME = "span_term";

    private static final ParseField TERM_FIELD = new ParseField("term");

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, String) */
    public SpanTermQueryBuilder(String name, String value) {
        super(name, (Object) value);
    }

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, int) */
    public SpanTermQueryBuilder(String name, int value) {
        super(name, (Object) value);
    }

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, long) */
    public SpanTermQueryBuilder(String name, long value) {
        super(name, (Object) value);
    }

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, float) */
    public SpanTermQueryBuilder(String name, float value) {
        super(name, (Object) value);
    }

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, double) */
    public SpanTermQueryBuilder(String name, double value) {
        super(name, (Object) value);
    }

    /** @see BaseTermQueryBuilder#BaseTermQueryBuilder(String, Object) */
    public SpanTermQueryBuilder(String name, Object value) {
        super(name, value);
    }

    /**
     * Read from a stream.
     */
    public SpanTermQueryBuilder(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    protected SpanQuery doToQuery(QueryShardContext context) throws IOException {
        MappedFieldType mapper = context.fieldMapper(fieldName);
        Term term;
        if (mapper == null) {
            term = new Term(fieldName, BytesRefs.toBytesRef(value));
        } else {
            Query termQuery = mapper.termQuery(value, context);
            term = MappedFieldType.extractTerm(termQuery);
        }
        return new SpanTermQuery(term);
    }

    public static SpanTermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
        XContentParser parser = parseContext.parser();
        String fieldName = null;
        Object value = null;
        float boost = AbstractQueryBuilder.DEFAULT_BOOST;
        String queryName = null;
        String currentFieldName = null;
        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
                fieldName = currentFieldName;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else {
                        if (parseContext.getParseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
                            value = parser.objectBytes();
                        } else if (parseContext.getParseFieldMatcher().match(currentFieldName, BaseTermQueryBuilder.VALUE_FIELD)) {
                            value = parser.objectBytes();
                        } else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
                            boost = parser.floatValue();
                        } else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
                            queryName = parser.text();
                        } else {
                            throw new ParsingException(parser.getTokenLocation(),
                                    "[span_term] query does not support [" + currentFieldName + "]");
                        }
                    }
                }
            } else {
                throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, parser.currentName());
                fieldName = parser.currentName();
                value = parser.objectBytes();
            }
        }

        SpanTermQueryBuilder result = new SpanTermQueryBuilder(fieldName, value);
        result.boost(boost).queryName(queryName);
        return result;
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }
}


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

<title>Preconditions (orchestrate-java-client 0.11.1 API)</title>
<meta name="date" content="2015-09-01">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.orchestrate.client

Class Preconditions

java.lang.Object

io.orchestrate.client.Preconditions

public final class Preconditions
extends java.lang.Object

A helper class to handle precondition checking in method calls.

Constructor Summary

Constructors

Constructor and Description

Preconditions()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
checkArgument(boolean condition,
             java.lang.String errorMsg)

Checks that the condition is true.

static java.lang.String[]
checkNoneEmpty(java.lang.String[] values,
              java.lang.String paramName,
              java.lang.String itemName)

Checks that the values are not empty.

static int
checkNotNegative(int value,
                java.lang.String paramName)

Checks that the value is not negative.

static long
checkNotNegative(long value,
                java.lang.String paramName)

Checks that the value is not negative.

static <T> T
checkNotNull(T value,
            java.lang.String paramName)

Checks that the value is not null.

static java.lang.String
checkNotNullOrEmpty(java.lang.String value,
                   java.lang.String paramName)

Checks that the value is not empty.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Preconditions

public Preconditions()

Method Detail

checkNotNull

public static <T> T checkNotNull(T value,
                                 java.lang.String paramName)

Checks that the value is not null. Returns the value
 directly, so you can use checkNotNull(value) inline.

Type Parameters:

T - The type of the value being checked.

Parameters:

value - The object to perform the null check.

paramName - The name of the parameter that cannot be null.

Returns:

The value that was checked.

checkNotNullOrEmpty

public static java.lang.String checkNotNullOrEmpty(java.lang.String value,
                                                   java.lang.String paramName)

Checks that the value is not empty.

Parameters:

value - The object to perform the check on.

paramName - The name of the parameter that can't be empty.

Returns:

The value that was checked.

checkArgument

public static void checkArgument(boolean condition,
                                 java.lang.String errorMsg)

Checks that the condition is true. Use for validating arguments
 to methods.

Parameters:

condition - The condition to check.

errorMsg - The error message to display if the check was false.

checkNotNegative

public static int checkNotNegative(int value,
                                   java.lang.String paramName)

Checks that the value is not negative.

Parameters:

value - The object to perform the check on.

paramName - The name of the parameter that can't be negative.

Returns:

The value that was checked.

checkNotNegative

public static long checkNotNegative(long value,
                                    java.lang.String paramName)

Checks that the value is not negative.

Parameters:

value - The object to perform the check on.

paramName - The name of the parameter that can't be negative.

Returns:

The value that was checked.

checkNoneEmpty

public static java.lang.String[] checkNoneEmpty(java.lang.String[] values,
                                                java.lang.String paramName,
                                                java.lang.String itemName)

Checks that the values are not empty.

Parameters:

values - The values to check.

paramName - The name of the parameter that is to be checked.

itemName - The name of an item from the values.

Returns:

The value that was checked.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System;

namespace Encog
{
    /// <summary>
    /// A report object that does nothing.
    /// </summary>
    public class NullStatusReportable : IStatusReportable
    {
        #region IStatusReportable Members

        /// <summary>
        /// Simply ignore any status reports.
        /// </summary>
        /// <param name="total">Not used.</param>
        /// <param name="current">Not used.</param>
        /// <param name="message">Not used.</param>
        public void Report(int total, int current,
                           String message)
        {
        }

        #endregion
    }
}


text:
"""
Contains classes and utilities related to hyde urls.
"""
import re

from hyde.fs import File, Folder
from hyde.model import Expando
from hyde.plugin import Plugin
from hyde.site import Site, Node, Resource

from functools import wraps

class UrlCleanerPlugin(Plugin):
    """
    Url Cleaner plugin for hyde. Adds to hyde the ability to generate clean
    urls.

    Configuration example
    ---------------------
    #yaml
    urlcleaner:
        index_file_names:
            # Identifies the files that represents a directory listing.
            # These file names are automatically stripped away when
            # the content_url function is called.
            - index.html
        strip_extensions:
            # The following extensions are automatically removed when
            # generating the urls using content_url function.
            - html
        # This option will append a slash to the end of directory paths
        append_slash: true
    """

    def __init__(self, site):
        super(UrlCleanerPlugin, self).__init__(site)

    def begin_site(self):
        """
        Replace the content_url method in the site object with a custom method
        that cleans urls based on the given configuration.
        """
        config = self.site.config

        if not hasattr(config, 'urlcleaner'):
            return

        if (hasattr(Site, '___url_cleaner_patched___')):
            return

        settings = config.urlcleaner

        print settings.to_dict()

        def clean_url(urlgetter):
            @wraps(urlgetter)
            def wrapper(site, path):
                url = urlgetter(site, path)
                index_file_names = getattr(settings,
                                        'index_file_names',
                                        ['index.html'])
                rep = File(url)
                if rep.name in index_file_names:
                    url = rep.parent.path.rstrip('/')
                    if hasattr(settings, 'append_slash') and \
                        settings.append_slash:
                        url += '/'
                elif hasattr(settings, 'strip_extensions'):
                    if rep.kind in settings.strip_extensions:
                        url = rep.parent.child(rep.name_without_extension)
                return url or '/'
            return wrapper

        Site.___url_cleaner_patched___ = True
        Site.content_url = clean_url(Site.content_url)


text:
require 'spec_helper'

module TrainingApp
  module Api
    describe SessionsController do
      describe "GET sessions" do
        before do
          get :index, registration_code: "123", use_route: :training
          @payload = JSON.parse(response.body)
        end

        it "sets the registration code on the session" do
          expect(session[:registration_code]).to eq("123")
        end

        it "returns the stripe public key token" do
          expect(@payload['stripe_public_key']).to be_a(String)
        end

        it "returns an authenticity token" do
          expect(@payload['authenticity_token']).to be_a(String)
        end
      end
    end
  end
end


text:
package org.paumard.spliterators;

import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * See the documentation and patterns to be used in this class in the {@link MoreSpliterators} factory class.
 *
 * @author José
 */
public class ValidatingSpliterator<E, R> implements Spliterator<R> {

    private final Spliterator<E> spliterator;
    private final Function<E, R> transformIfValid, transformIfNotValid;
    private final Predicate<E> validator;

    public static class Builder<E, R> {

        private Spliterator<E> spliterator;
        private Function<E, R> transformIfValid, transformIfNotValid;
        private Predicate<E> validator;

        public Builder() {
        }

        public Builder<E, R> with(Spliterator<E> spliterator) {
            this.spliterator = Objects.requireNonNull(spliterator);
            return this;
        }

        public Builder<E, R> validatedBy(Predicate<E> validator) {
            this.validator = Objects.requireNonNull(validator);
            return this;
        }

        public Builder<E, R> withValidFunction(Function<E, R> validFunction) {
            this.transformIfValid = Objects.requireNonNull(validFunction);
            return this;
        }

        public Builder<E, R> withNotValidFunction(Function<E, R> notValidFunction) {
            this.transformIfNotValid = Objects.requireNonNull(notValidFunction);
            return this;
        }

        public ValidatingSpliterator<E, R> build() {
            return new ValidatingSpliterator<>(spliterator, validator, transformIfValid, transformIfNotValid);
        }
    }

    private ValidatingSpliterator(
            Spliterator<E> spliterator, Predicate<E> validator,
            Function<E, R> transformIfValid, Function<E, R> transformIfNotValid) {
        this.spliterator = spliterator;
        this.validator = validator;
        this.transformIfValid = transformIfValid;
        this.transformIfNotValid = transformIfNotValid;
    }

    @Override
    public boolean tryAdvance(Consumer<? super R> action) {

        return this.spliterator.tryAdvance(
               e -> {
                   if (validator.test(e)) {
                       action.accept(transformIfValid.apply(e));
                   } else {
                       action.accept(transformIfNotValid.apply(e));
                   }
               }
        );
    }

    @Override
    public Spliterator<R> trySplit() {
        Spliterator<E> split = this.spliterator.trySplit();
        return split == null ? null : new ValidatingSpliterator<>(split, validator, transformIfValid, transformIfNotValid);
    }

    @Override
    public long estimateSize() {
        return spliterator.estimateSize();
    }

    @Override
    public int characteristics() {
        return this.spliterator.characteristics();
    }
}


text:
package credentials

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestECSRamRole(t *testing.T) {
	c := NewEcsRamRoleCredential("rolename")
	assert.Equal(t, "rolename", c.RoleName)
	s := NewStsRoleNameOnEcsCredential("rolename")
	assert.Equal(t, "rolename", s.RoleName)
	r := s.ToEcsRamRoleCredential()
	assert.Equal(t, "rolename", r.RoleName)
}


text:
package vecnet

import (
	"io"
	"runtime"
	"syscall"
	"unsafe"
)

var readFromBuffers = readFromBuffersLinux

func readFromBuffersLinux(bufs Buffers, conn syscall.Conn) (int64, error) {
	rc, err := conn.SyscallConn()
	if err != nil {
		return 0, err
	}

	length := int64(0)
	for _, buf := range bufs {
		length += int64(len(buf))
	}

	for n := int64(0); n < length; {
		cur, err := recvmsg(bufs, rc)
		if err != nil && (cur == 0 || err != io.EOF) {
			return n, err
		}
		n += int64(cur)

		// Consume iovecs to retry.
		for consumed := 0; consumed < cur; {
			if len(bufs[0]) <= cur-consumed {
				consumed += len(bufs[0])
				bufs = bufs[1:]
			} else {
				bufs[0] = bufs[0][cur-consumed:]
				break
			}
		}
	}
	return length, nil
}

// buildIovec builds an iovec slice from the given []byte slice.
//
// iovecs is used as an initial slice, to avoid excessive allocations.
func buildIovec(bufs Buffers, iovecs []syscall.Iovec) ([]syscall.Iovec, int) {
	var length int
	for _, buf := range bufs {
		if l := len(buf); l > 0 {
			iovecs = append(iovecs, syscall.Iovec{
				Base: &buf[0],
				Len:  iovlen(l),
			})
			length += l
		}
	}
	return iovecs, length
}

func recvmsg(bufs Buffers, rc syscall.RawConn) (int, error) {
	iovecs, length := buildIovec(bufs, make([]syscall.Iovec, 0, 2))

	var msg syscall.Msghdr
	if len(iovecs) != 0 {
		msg.Iov = &iovecs[0]
		msg.Iovlen = iovlen(len(iovecs))
	}

	// n is the bytes received.
	var n uintptr
	var e syscall.Errno
	err := rc.Read(func(fd uintptr) bool {
		n, _, e = syscall.Syscall(syscall.SYS_RECVMSG, fd, uintptr(unsafe.Pointer(&msg)), syscall.MSG_DONTWAIT)
		// Return false if EINTR, EAGAIN, or EWOULDBLOCK to retry.
		return !(e == syscall.EINTR || e == syscall.EAGAIN || e == syscall.EWOULDBLOCK)
	})
	runtime.KeepAlive(iovecs)
	if err != nil {
		return 0, err
	}
	if e != 0 {
		return 0, e
	}

	// The other end is closed by returning a 0 length read with no error.
	if n == 0 {
		return 0, io.EOF
	}

	if int(n) > length {
		return length, io.ErrShortBuffer
	}
	return int(n), nil
}


text:
<?php

	$search_user = preg_replace("/[^a-zA-Z0-9_ -]/", "", $_GET["user"]);

	$title = "$search_user";
	$scripts = '<script type="text/javascript" src="' . swarmpath( 'js/jquery.js' ) . '"></script>' .
		'<script type="text/javascript" src="' . swarmpath( 'js/pretty.js' ) . '"></script>' .
		'<script type="text/javascript" src="' . swarmpath( 'js/view.js' ) . '"></script>';


text:
// [START earthengine__apidocs__ee_geometry_bbox_dissolve]
// Define a BBox object.
var bBox = ee.Geometry.BBox(-122.09, 37.42, -122.08, 37.43);

// Apply the dissolve method to the BBox object.
var bBoxDissolve = bBox.dissolve({'maxError': 1});

// Print the result to the console.
print('bBox.dissolve(...) =', bBoxDissolve);

// Display relevant geometries on the map.
Map.setCenter(-122.085, 37.422, 15);
Map.addLayer(bBox,
             {'color': 'black'},
             'Geometry [black]: bBox');
Map.addLayer(bBoxDissolve,
             {'color': 'red'},
             'Result [red]: bBox.dissolve');
// [END earthengine__apidocs__ee_geometry_bbox_dissolve]


text:
		</div>
		<div style='border-top:1px solid #eeeeee;background:#ffffff;padding:20px;font-size:11px;color:#666'>
				{{trans("crudbooster.email_footer")}}
		</div>
</div>


text:
php-cache
=========

This is just example of create cache in PHP with example.


text:
---
layout: post
title: UI-Fragment-Analist
tags: [Android-UI]
published: true
---
Fragment为不同的屏幕尺寸生成不同的布局(一个小的屏幕布一次只放一个Fragment,大的则可以两个或以上的)

# 如何使用Fragment
### 1.继承Fragment

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.ViewGroup;

    public class ArticleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.article_view, container, false);
    }
    }

## 2.Fragment的使用

### 2.1.使用xml布局使用
  注:此处省略了layout_height,layout_width,这两个必要的属性

    <fragment android:name="com.example.android.fragments.HeadlinesFragment"/>

    <fragment android:name="com.example.android.fragments.ArticleFragment"/>

### 2.2使用java代码实现的-建立灵活动态的UI

1. 在activity运行时添加或者移除fragment,必须使用 Fragment创建一个FragmentTransaction对象, FragmentTransaction提供了用来增加、移除、替换以及其它一些操作的APIs。
2. 在activity的onCreate()方法中添加初始化fragment(s).
3. 运用fragment(特别是那些你在运行时添加的)的一个很重要的规则就是在布局中你必须有一个容器view,fragment的layout将会放在这个view里面。(例如:res/layout/news_articles.xml:FramLayout布局)

4.获取FragmentManager的两种方式:
> 用Support Library APIs(android.support.v4.app.Fragment)调用 getSupportFragmentManager()方法获取
> 用android.app.Fragment(对Android 3.0下版本不兼容)调用getFragmentManager()即可.

5.Fragment的事务(添加、替换、)

        WhiteFragment whiteFragment =
        new WhiteFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().
		add(R.id.FramLayout,whiteFragment).
		addToBackStack(null).commit();

在res/layout/activity_main.xml布局中添加如下代码

	<FrameLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/FramLayout">
    </FrameLayout>

记住当你执行fragment事务的时候,例如移除或者替换,你经常要适当地让用户可以向后导航与"撤销"这次改变。为了让用户向后导航fragment事务,你必须在FragmentTransaction提交前调用addToBackStack(String name)方法。
	addToBackStack(String name)方法提供了一个可选的String参数为事务指定了一个唯一的名字。这个名字不是必须的,除非你打算用FragmentManager.BackStackEntry APIs来进行一些高级的fragments操作。

> Note:当你移除或者替换一个fragment并把它放入返回栈中时,被移除的fragment的生命周期是stopped(不是destoryed).当用户返回重新恢复这个fragment,它的生命周期是restarts。如果你没把fragment放入返回栈中,那么当他被移除或者替换时,它的生命周期是destoryed。

### 2.3Fragments之间的交互

- 定义好这些模块化的Fragment,你就可以让他们关联activity,使他们与application的逻辑结合起来,实现全局的复合的UI。
- 通常,你想fragment之间能相互交互,比如基于用户事件改变fragment的内容。所有fragment之间的交互需要通过他们关联的activity,两个fragment之间不应该直接交互。

# 2.3.1定义接口

> 为了让fragment与activity交互,你可以在Fragment 类中定义一个接口,并且在activity中实现这个接口。Fragment在他们生命周期的**onAttach()**方法中获取接口的实现,然后调用接口的方法来与Activity交互。

    /**
     * A simple {@link Fragment} subclass.
     * Activities that contain this fragment must implement the
     * to handle interaction events.
     * Use the {@link WhiteFragment#newInstance} factory method to
     * create an instance of this fragment.
     */

    public class WhiteFragment extends Fragment {

	...

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView textView = null;
    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment WhiteFragment.
     */

    // TODO: Rename and change types and number of parameters

    public static WhiteFragment newInstance(String param1, String param2) {

        WhiteFragment fragment = new WhiteFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private WhiteFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            Log.d(getActivity().getPackageName(),mParam1+"--------"+mParam2);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
            textView.setText(this.mParam1+"-----"+this.mParam2);
        }
    }

	// TODO: Get HookMethod from  implemented activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    /**
     * This interface must be implemented by *activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    }

# **2.3.2实现接口**

    public class MainActivity extends ActionBarActivity implements WhiteFragment.OnFragmentInteractionListener{
	...
	//... 省略非关键代码

    @Override
    public void onFragmentInteraction(Uri uri) {
        Toast.makeText(MainActivity.this,"Test Main Activity can be resolved!",Toast.LENGTH_LONG).show();
    }
    }

# **2.3.3传递消息给Fragment**
- 宿主activity通过findFragmentById()方法来获取fragment的实例,然后直接调用Fragment的public方法来向fragment传递消息。

- 例如,假设上面所示的activity可能包含另外一个fragment,这个fragment用来展示从上面的回调方法中返回的指定的数据。在这种情况下,activity可以把从回调方法中接收到的信息传递给这个展示数据的Fragment.

        public class MainActivity extends ActionBarActivity implements WhiteFragment.OnFragmentInteractionListener{

	       ...

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final WhiteFragment whiteFragment =WhiteFragment.newInstance("why i can't get param","what's the fuck parmaB");
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().add(R.id.FramLayout,whiteFragment).addToBackStack(null).commit();

        //error use way
        //whiteFragment.setArguments(args);
        btnNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
		//传参数
                whiteFragment.onButtonPressed(new Uri.Builder().path("www.baidu.com").build());
            }
        });
    }
    }

# 参考文献
[1]Android官方培训课程中文版(v0.9.2).[FragmentAndroid](http://hukai.me/android-training-course-in-chinese/basics/fragments/)


text:
package uk.ac.man.documentparser.input;

import java.io.File;
import java.util.Set;

public class MedlinePMCIndexFactory implements InputFactory {

	File medlineBaseDir;
	private File pmcBaseDir;

	private int minYearFilter=-1;
	private Set<String> validIDs = null;
	private String[] dtds;

	public MedlinePMCIndexFactory(File medlineBaseDir, File pmcBaseDir, String[] dtds, Set<String> validIDs){
		this.medlineBaseDir = medlineBaseDir;
		this.pmcBaseDir = pmcBaseDir;
		this.dtds = dtds;
		this.validIDs = validIDs;
	}

	public MedlinePMCIndexFactory(File baseDir){
		this.medlineBaseDir = baseDir;
	}

	public DocumentIterator parse(StringBuffer data) {
		throw new IllegalStateException("not implemented");
	}

	public DocumentIterator parse(String file) {
		return parse(new File(file));
	}

	public DocumentIterator parse(File file) {
		return new MedlinePMCIndex(medlineBaseDir,pmcBaseDir,file,dtds, minYearFilter, validIDs);
	}

	public void setMinYearFilter(int minYearFilter) {
		this.minYearFilter = minYearFilter;
	}
}


text:
@interface ForecastController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView         *tableView;
@property (nonatomic)         CGFloat              cellHeight;
@property (nonatomic, strong) NSMutableArray      *weatherDataArray;
@property (nonatomic, strong) ShowDownView        *showDownView;
@property (nonatomic, strong) ForecastWeatherView *forecastView;

@end

@implementation ForecastController

- (void)viewDidLoad {

    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self initTableView];

    // 加载动画并动画显示
    [GCDQueue executeInMainQueue:^{

        self.weatherDataArray = [NSMutableArray arrayWithArray:self.weatherCondition.list];

        NSMutableArray *indexPathArray = [NSMutableArray array];

        for (int count = 0; count < self.weatherDataArray.count; count++) {

            NSIndexPath *path = [NSIndexPath indexPathForRow:count inSection:0];
            [indexPathArray addObject:path];
        }

        [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];

    } afterDelaySecs:0.30f];

    // 显示进入更多天气的view的提示信息
    self.showDownView        = [[ShowDownView alloc] initWithFrame:CGRectMake(0, 0, 30.f, 30.f / 3.f)];
    self.showDownView.center = self.view.center;
    self.showDownView.y      = -30.f;
    [self.tableView addSubview:self.showDownView];
}

- (void)initTableView {

    // cell高度
    self.cellHeight           = Width / 4.f;
    self.tableView            = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate   = self;
    self.tableView.dataSource = self;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator   = NO;
    self.tableView.separatorStyle                 = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[ForecastCell class] forCellReuseIdentifier:@"ForecastCell"];

    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.weatherDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ForecastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ForecastCell"];
    [cell acccessData:self.weatherDataArray[indexPath.row] indexPath:indexPath];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return self.cellHeight;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    if (scrollView.contentOffset.y <= -60) {

        [UIView animateWithDuration:0.5 animations:^{

            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }];

        [GCDQueue executeInMainQueue:^{

            [self dismissViewControllerAnimated:YES completion:nil];

        } afterDelaySecs:0.15f];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat percent = (-scrollView.contentOffset.y) / 60.f;
    [self.showDownView showPercent:percent];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    ForecastCell *forecastCell = (ForecastCell *)cell;
    [forecastCell show];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath {

    ForecastCell *forecastCell = (ForecastCell *)cell;
    [forecastCell hide];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    if (section == 0) {

        ForecastWeatherView *titleView = [[ForecastWeatherView alloc] initWithFrame:CGRectMake(0, 0, Width, Height - Width * 1.5)];
        [titleView buildView];

        titleView.cityName    = self.weatherCondition.city.name;
        titleView.countryCode = self.weatherCondition.city.country;

        UIView *line         = [[UIView alloc] initWithFrame:CGRectMake(0, Height - Width * 1.5 - 1, Width, 0.5)];
        line.backgroundColor = [UIColor blackColor];
        line.alpha           = 0.1f;
        [titleView addSubview:line];

        return titleView;

    } else {

        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return Height - Width * 1.5;
}

@end