text:
"""implements an hgvs data provider interface using UTA
(https://github.com/biocommons/uta)

"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import contextlib
import inspect
import logging
import os
import re
import weakref

import psycopg2
import psycopg2.extras
import psycopg2.pool
import six
from bioutils.assemblies import make_ac_name_map
from bioutils.digests import seq_md5
from six.moves.urllib import parse as urlparse

import hgvs

from ..dataproviders.interface import Interface
from ..exceptions import HGVSDataNotAvailableError, HGVSError
from .seqfetcher import SeqFetcher

_logger = logging.getLogger(__name__)

def _stage_from_version(version):
    """return "prd", "stg", or "dev" for the given version string.  A value is always returned"""
    if version:
        m = re.match(r"^(?P<xyz>\d+\.\d+\.\d+)(?P<extra>.*)", version)
        if m:
            return "stg" if m.group("extra") else "prd"
    return "dev"

def _get_uta_db_url():
    """returns UTA DB URL based on environment variables and code version

    * if UTA_DB_URL is set, use that
    * Otherwise, if _UTA_URL_KEY is set, use that as the name of a
      config file entry and use the corresponding URL
    * Otherwise,

    """

    if "UTA_DB_URL" in os.environ:
        return os.environ["UTA_DB_URL"]

    if "_UTA_URL_KEY" in os.environ:
        url_key = os.environ["_UTA_URL_KEY"]
    else:
        sdlc = _stage_from_version(hgvs.__version__)
        url_key = "public_{sdlc}".format(sdlc=sdlc)
    return hgvs.global_config["uta"][url_key]

def connect(db_url=None, pooling=hgvs.global_config.uta.pooling, application_name=None, mode=None, cache=None):
    """Connect to a UTA database instance and return a UTA interface instance.

    :param db_url: URL for database connection
    :type db_url: string
    :param pooling: whether to use connection pooling (postgresql only)
    :type pooling: bool
    :param application_name: log application name in connection (useful for debugging; PostgreSQL only)
    :type application_name: str

    When called with an explicit db_url argument, that db_url is used for connecting.

    When called without an explicit argument, the function default is
    determined by the environment variable UTA_DB_URL if it exists, or
    hgvs.datainterface.uta.public_db_url otherwise.

    >>> hdp = connect()
    >>> hdp.schema_version()
    '1.1'

    The format of the db_url is driver://user:pass@host/database/schema (the same
    as that used by SQLAlchemy).  Examples:

    A remote public postgresql database:
        postgresql://anonymous:anonymous@uta.biocommons.org/uta/uta_20170707'

    A local postgresql database:
        postgresql://localhost/uta_dev/uta_20170707

    For postgresql db_urls, pooling=True causes connect to use a
    psycopg2.pool.ThreadedConnectionPool.
    """

    _logger.debug("connecting to " + str(db_url) + "...")

    if db_url is None:
        db_url = _get_uta_db_url()

    if "PYTEST_CURRENT_TEST" in os.environ and "localhost" not in db_url:
        _logger.warning(f"You are executing tests using remote data ({db_url})")

    url = _parse_url(db_url)
    if url.scheme == "sqlite":
        conn = UTA_sqlite(url, mode, cache)
    elif url.scheme == "postgresql":
        conn = UTA_postgresql(url=url, pooling=pooling, application_name=application_name, mode=mode, cache=cache)
    else:
        # fell through connection scheme cases
        raise RuntimeError("{url.scheme} in {url} is not currently supported".format(url=url))
    _logger.info("connected to " + str(db_url) + "...")
    return conn

class UTABase(Interface):
    required_version = "1.1"

    _queries = {
        "acs_for_protein_md5": """
            select ac
            from seq_anno
            where seq_id=?
            """,
        "gene_info": """
            select *
            from gene
            where hgnc=?
            """,
        # TODO: reconcile tx_exons query and build_tx_cigar
        # built_tx_cigar says it expects exons in transcript order,
        # but tx_exons isn't do that (on the - strand).
        "tx_exons": """
            select *
            from tx_exon_aln_v
            where tx_ac=? and alt_ac=? and alt_aln_method=?
            order by alt_start_i
            """,
        "tx_for_gene": """
            select hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method
            from transcript T
            join exon_set ES on T.ac=ES.tx_ac where alt_aln_method != 'transcript' and hgnc=?
            """,
        "alignments_for_region": """
            select tx_ac,alt_ac,alt_strand,alt_aln_method,min(start_i) as start_i,max(end_i) as end_i
            from exon_set ES
            join exon E on ES.exon_set_id=E.exon_set_id
            where alt_ac=?
            group by tx_ac,alt_ac,alt_strand,alt_aln_method
            having min(start_i) < ? and ? <= max(end_i)
            """,
        "tx_identity_info": """
            select distinct(tx_ac), alt_ac, alt_aln_method, cds_start_i, cds_end_i, lengths, hgnc
            from tx_def_summary_v
            where tx_ac=?
            """,
        "tx_info": """
            select hgnc, cds_start_i, cds_end_i, tx_ac, alt_ac, alt_aln_method
            from transcript T
            join exon_set ES on T.ac=ES.tx_ac
            where tx_ac=? and alt_ac=? and alt_aln_method=?
            """,
        "tx_mapping_options": """
            select distinct tx_ac,alt_ac,alt_aln_method
            from tx_exon_aln_v where tx_ac=? and exon_aln_id is not NULL
            """,
        "tx_seq": """
            select seq
            from seq S
            join seq_anno SA on S.seq_id=SA.seq_id
            where ac=?
            """,
        "tx_similar": """
            select *
            from tx_similarity_v
            where tx_ac1 = ?
            """,
        "tx_to_pro": """
            select * from associated_accessions where tx_ac = ? order by pro_ac desc
            """,
    }

    def __init__(self, url, mode=None, cache=None):
        self.url = url
        self.seqfetcher = SeqFetcher()
        if mode != "run":
            self._connect()
        super(UTABase, self).__init__(mode, cache)

    def __str__(self):
        return (
            "{n} <data_version:{dv}; schema_version:{sv}; application_name={self.application_name};"
            " url={self.url}; sequences-from={sf}>"
        ).format(
            n=type(self).__name__,
            self=self,
            dv=self.data_version(),
            sv=self.schema_version(),
            sf=self.sequence_source(),
        )

    def _fetchone(self, sql, *args):
        with self._get_cursor() as cur:
            cur.execute(sql, *args)
            return cur.fetchone()

    def _fetchall(self, sql, *args):
        with self._get_cursor() as cur:
            cur.execute(sql, *args)
            return cur.fetchall()

    ############################################################################
    # Queries

    def data_version(self):
        return self.url.schema

    def schema_version(self):
        return self._fetchone("select * from meta where key = 'schema_version'")["value"]

    @staticmethod
    def sequence_source():
        seqrepo_dir = os.environ.get("HGVS_SEQREPO_DIR")
        seqrepo_url = os.environ.get("HGVS_SEQREPO_URL")
        if seqrepo_dir:
            return seqrepo_dir
        elif seqrepo_url:
            return seqrepo_url
        else:
            return "seqfetcher"

    def get_seq(self, ac, start_i=None, end_i=None):
        return self.seqfetcher.fetch_seq(ac, start_i, end_i)

    def get_acs_for_protein_seq(self, seq):
        """
        returns a list of protein accessions for a given sequence.  The
        list is guaranteed to contain at least one element with the
        MD5-based accession (MD5_01234abc...def56789) at the end of the
        list.
        """
        md5 = seq_md5(seq)
        return [r["ac"] for r in self._fetchall(self._queries["acs_for_protein_md5"], [md5])] + ["MD5_" + md5]

    def get_gene_info(self, gene):
        """
        returns basic information about the gene.

        :param gene: HGNC gene name
        :type gene: str

        # database results
        hgnc    | ATM
        maploc  | 11q22-q23
        descr   | ataxia telangiectasia mutated
        summary | The protein encoded by this gene belongs to the PI3/PI4-kinase family. This...
        aliases | AT1,ATA,ATC,ATD,ATE,ATDC,TEL1,TELO1
        added   | 2014-02-04 21:39:32.57125

        """
        return self._fetchone(self._queries["gene_info"], [gene])

    def get_tx_exons(self, tx_ac, alt_ac, alt_aln_method):
        """
        return transcript exon info for supplied accession (tx_ac, alt_ac, alt_aln_method), or None if not found

        :param tx_ac: transcript accession with version (e.g., 'NM_000051.3')
        :type tx_ac: str

        :param alt_ac: specific genomic sequence (e.g., NC_000011.4)
        :type alt_ac: str

        :param alt_aln_method: sequence alignment method (e.g., splign, blat)
        :type alt_aln_method: str

        # tx_exons = db.get_tx_exons('NM_199425.2', 'NC_000020.10', 'splign')
        # len(tx_exons)
        3

        tx_exons have the following attributes::

            {
                'tes_exon_set_id' : 98390
                'aes_exon_set_id' : 298679
                'tx_ac'           : 'NM_199425.2'
                'alt_ac'          : 'NC_000020.10'
                'alt_strand'      : -1
                'alt_aln_method'  : 'splign'
                'ord'             : 2
                'tx_exon_id'      : 936834
                'alt_exon_id'     : 2999028
                'tx_start_i'      : 786
                'tx_end_i'        : 1196
                'alt_start_i'     : 25059178
                'alt_end_i'       : 25059588
                'cigar'           : '410='
            }

        For example:

        # tx_exons[0]['tx_ac']
        'NM_199425.2'

        """
        rows = self._fetchall(self._queries["tx_exons"], [tx_ac, alt_ac, alt_aln_method])
        if len(rows) == 0:
            raise HGVSDataNotAvailableError(
                "No tx_exons for (tx_ac={tx_ac},alt_ac={alt_ac},alt_aln_method={alt_aln_method})".format(
                    tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method
                )
            )

        # TODO: Check that end == transcript sequence length (but length N/A in current hdp)
        ex0 = 0 if (rows[0]["alt_strand"] == 1) else -1
        if rows[ex0]["tx_start_i"] != 0:
            raise HGVSDataNotAvailableError(
                "Alignment is incomplete; cannot use transcript for mapping"
                "(tx_ac={tx_ac},alt_ac={alt_ac},alt_aln_method={alt_aln_method})".format(
                    tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method
                )
            )
        return rows

    def get_tx_for_gene(self, gene):
        """
        return transcript info records for supplied gene, in order of decreasing length

        :param gene: HGNC gene name
        :type gene: str
        """
        return self._fetchall(self._queries["tx_for_gene"], [gene])

    def get_tx_for_region(self, alt_ac, alt_aln_method, start_i, end_i):
        """
        return transcripts that overlap given region

        :param str alt_ac: reference sequence (e.g., NC_000007.13)
        :param str alt_aln_method: alignment method (e.g., splign)
        :param int start_i: 5' bound of region
        :param int end_i: 3' bound of region
        """

        return self.get_alignments_for_region(
            alt_ac=alt_ac, start_i=start_i, end_i=end_i, alt_aln_method=alt_aln_method
        )

    def get_alignments_for_region(self, alt_ac, start_i, end_i, alt_aln_method=None):
        """
        return transcripts that overlap given region

        :param str alt_ac: reference sequence (e.g., NC_000007.13)
        :param int start_i: 5' bound of region
        :param int end_i: 3' bound of region
        :param str alt_aln_method: OPTIONAL alignment method (e.g., splign)
        """

        alignments = self._fetchall(self._queries["alignments_for_region"], [alt_ac, start_i, end_i])
        if alt_aln_method is not None:
            alignments = [a for a in alignments if a["alt_aln_method"] == alt_aln_method]
        return alignments

    def get_tx_identity_info(self, tx_ac):
        """returns features associated with a single transcript.

        :param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
        :type tx_ac: str

        # database output
        -[ RECORD 1 ]--+-------------
        tx_ac          | NM_199425.2
        alt_ac         | NM_199425.2
        alt_aln_method | transcript
        cds_start_i    | 283
        cds_end_i      | 1003
        lengths        | {707,79,410}
        hgnc           | VSX1

        """
        rows = self._fetchall(self._queries["tx_identity_info"], [tx_ac])
        if len(rows) == 0:
            raise HGVSDataNotAvailableError("No transcript definition for (tx_ac={tx_ac})".format(tx_ac=tx_ac))
        return rows[0]

    def get_tx_info(self, tx_ac, alt_ac, alt_aln_method):
        """return a single transcript info for supplied accession (tx_ac, alt_ac, alt_aln_method), or None if not found

        :param tx_ac: transcript accession with version (e.g., 'NM_000051.3')
        :type tx_ac: str

        :param alt_ac: specific genomic sequence (e.g., NC_000011.4)
        :type alt_ac: str

        :param alt_aln_method: sequence alignment method (e.g., splign, blat)
        :type alt_aln_method: str

        # database output
        -[ RECORD 1 ]--+------------
        hgnc           | ATM
        cds_start_i    | 385
        cds_end_i      | 9556
        tx_ac          | NM_000051.3
        alt_ac         | AC_000143.1
        alt_aln_method | splign

        """
        rows = self._fetchall(self._queries["tx_info"], [tx_ac, alt_ac, alt_aln_method])
        if len(rows) == 0:
            raise HGVSDataNotAvailableError(
                "No tx_info for (tx_ac={tx_ac},alt_ac={alt_ac},alt_aln_method={alt_aln_method})".format(
                    tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method
                )
            )
        elif len(rows) == 1:
            return rows[0]
        else:
            raise HGVSError(
                "Multiple ({n}) replies for tx_info(tx_ac="
                "{tx_ac},alt_ac={alt_ac},alt_aln_method={alt_aln_method})".format(
                    n=len(rows), tx_ac=tx_ac, alt_ac=alt_ac, alt_aln_method=alt_aln_method
                )
            )

    def get_tx_mapping_options(self, tx_ac):
        """Return all transcript alignment sets for a given transcript
        accession (tx_ac); returns empty list if transcript does not
        exist.  Use this method to discovery possible mapping options
        supported in the database

        :param tx_ac: transcript accession with version (e.g., 'NM_000051.3')
        :type tx_ac: str

        # database output
        -[ RECORD 1 ]--+------------
        hgnc           | ATM
        cds_start_i    | 385
        cds_end_i      | 9556
        tx_ac          | NM_000051.3
        alt_ac         | AC_000143.1
        alt_aln_method | splign
        -[ RECORD 2 ]--+------------
        hgnc           | ATM
        cds_start_i    | 385
        cds_end_i      | 9556
        tx_ac          | NM_000051.3
        alt_ac         | NC_000011.9
        alt_aln_method | blat

        """
        rows = self._fetchall(self._queries["tx_mapping_options"], [tx_ac])
        return rows

    def get_similar_transcripts(self, tx_ac):
        """Return a list of transcripts that are similar to the given
        transcript, with relevant similarity criteria.

        >> sim_tx = hdp.get_similar_transcripts('NM_001285829.1')
        >> dict(sim_tx[0])
        { 'cds_eq': False,
        'cds_es_fp_eq': False,
        'es_fp_eq': True,
        'tx_ac1': 'NM_001285829.1',
        'tx_ac2': 'ENST00000498907' }

        where:

        * cds_eq means that the CDS sequences are identical
        * es_fp_eq means that the full exon structures are identical
          (i.e., incl. UTR)
        * cds_es_fp_eq means that the cds-clipped portions of the exon
          structures are identical (i.e., ecluding. UTR)
        * Hint: "es" = "exon set", "fp" = "fingerprint", "eq" = "equal"

        "exon structure" refers to the start and end coordinates on a
        specified reference sequence. Thus, having the same exon
        structure means that the transcripts are defined on the same
        reference sequence and have the same exon spans on that
        sequence.

        """

        rows = self._fetchall(self._queries["tx_similar"], [tx_ac])
        return rows

    def get_pro_ac_for_tx_ac(self, tx_ac):
        """Return the (single) associated protein accession for a given transcript
        accession, or None if not found."""

        rows = self._fetchall(self._queries["tx_to_pro"], [tx_ac])
        try:
            return rows[0]["pro_ac"]
        except IndexError:
            return None

    def get_assembly_map(self, assembly_name):
        """return a list of accessions for the specified assembly name (e.g., GRCh38.p5)"""
        return make_ac_name_map(assembly_name)

class UTA_postgresql(UTABase):
    def __init__(self, url, pooling=hgvs.global_config.uta.pooling, application_name=None, mode=None, cache=None):
        if url.schema is None:
            raise Exception("No schema name provided in {url}".format(url=url))
        self.application_name = application_name
        self.pooling = pooling
        self._conn = None
        # If we're using connection pooling, track the set of DB
        # connections we've seen; on first use we set the schema
        # search path. Use weak references to avoid keeping connection
        # objects alive unnecessarily.
        self._conns_seen = weakref.WeakSet()
        super(UTA_postgresql, self).__init__(url, mode, cache)

    def __del__(self):
        self.close()

    def close(self):
        if self.pooling:
            self._pool.closeall()
        else:
            if self._conn is not None:
                self._conn.close()

    def _connect(self):
        if self.application_name is None:
            st = inspect.stack()
            self.application_name = os.path.basename(st[-1][1])
        conn_args = dict(
            host=self.url.hostname,
            port=self.url.port,
            database=self.url.database,
            user=self.url.username,
            password=self.url.password,
            application_name=self.application_name + "/" + hgvs.__version__,
        )
        if self.pooling:
            _logger.info("Using UTA ThreadedConnectionPool")
            self._pool = psycopg2.pool.ThreadedConnectionPool(
                hgvs.global_config.uta.pool_min, hgvs.global_config.uta.pool_max, **conn_args
            )
        else:
            self._conn = psycopg2.connect(**conn_args)
            self._conn.autocommit = True
            with self._get_cursor() as cur:
                self._set_search_path(cur)

        self._ensure_schema_exists()

        # remap sqlite's ? placeholders to psycopg2's %s
        self._queries = {k: v.replace("?", "%s") for k, v in six.iteritems(self._queries)}

    def _ensure_schema_exists(self):
        # N.B. On AWS RDS, information_schema.schemata always returns zero rows
        r = self._fetchone("select exists(SELECT 1 FROM pg_namespace WHERE nspname = %s)", [self.url.schema])
        if r[0]:
            return
        raise HGVSDataNotAvailableError(
            "specified schema ({}) does not exist (url={})".format(self.url.schema, self.url)
        )

    @contextlib.contextmanager
    def _get_cursor(self, n_retries=1):
        """Returns a context manager for obtained from a single or pooled
        connection, and sets the PostgreSQL search_path to the schema
        specified in the connection URL.

        Although *connections* are threadsafe, *cursors* are bound to
        connections and are *not* threadsafe. Do not share cursors
        across threads.

        Use this funciton like this::

            with hdp._get_cursor() as cur:
                # your code

        Do not call this function outside a contextmanager.

        """

        n_tries_rem = n_retries + 1
        while n_tries_rem > 0:
            try:

                conn = self._pool.getconn() if self.pooling else self._conn

                # autocommit=True obviates closing explicitly
                conn.autocommit = True

                cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
                if self.pooling:
                    # this might be a new connection, in which case we
                    # need to set the search path
                    if conn not in self._conns_seen:
                        self._set_search_path(cur)
                        self._conns_seen.add(conn)

                yield cur

                # contextmanager executes these when context exits
                cur.close()
                if self.pooling:
                    self._pool.putconn(conn)

                break

            except psycopg2.OperationalError:

                _logger.warning("Lost connection to {url}; attempting reconnect".format(url=self.url))
                if self.pooling:
                    self._pool.putconn(conn)
                    _logger.warning("Put away pool connection from {url}".format(url=self.url))
                else:
                    self._connect()
                    _logger.warning("Reconnected to {url}".format(url=self.url))

            n_tries_rem -= 1

        else:

            # N.B. Probably never reached
            raise HGVSError("Permanently lost connection to {url} ({n} retries)".format(url=self.url, n=n_retries))

    def _set_search_path(self, cur):
        cur.execute("set search_path = {self.url.schema},public;".format(self=self))

class ParseResult(urlparse.ParseResult):
    """Subclass of url.ParseResult that adds database and schema methods,
    and provides stringification.

    """

    def __new__(cls, pr):
        return super(ParseResult, cls).__new__(cls, *pr)

    @property
    def database(self):
        path_elems = self.path.split("/")
        return path_elems[1] if len(path_elems) > 1 else None

    @property
    def schema(self):
        path_elems = self.path.split("/")
        return path_elems[2] if len(path_elems) > 2 else None

    def __str__(self):
        return self.geturl()

def _parse_url(db_url):
    """parse database connection urls into components

    UTA database connection URLs follow that of SQLAlchemy, except
    that a schema may be optionally specified after the database. The
    skeleton format is:

       driver://user:pass@host/database/schema

    >>> params = _parse_url("driver://user:pass@host:9876/database/schema")

    >>> params.scheme
    u'driver'

    >>> params.hostname
    u'host'

    >>> params.username
    u'user'

    >>> params.password
    u'pass'

    >>> params.database
    u'database'

    >>> params.schema
    u'schema'

    """

    return ParseResult(urlparse.urlparse(db_url))

if __name__ == "__main__":
    import doctest

    doctest.testmod()

# <LICENSE>
# Copyright 2018 HGVS Contributors (https://github.com/biocommons/hgvs)
#
# Licensed 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.
# </LICENSE>


text:
title:  "Daily Rituals"
author: "Wojciech Adam Koszek"
description: >
  This is a book worth reading for those of us who'd like to start
  developing creative habits. What sucked a bit is the lack of essence --
  the summary. You'll listen through it, but you'll need to summarise it
  yourself.
address: "Menlo Park, CA"
klayout: book
tags:
- books
categories: books
read:	2015-10-03
ads:
-
spellcheck-allow:
-
---

redpajama_set_name: RedPajamaGithub


text:
<?php
// Check for empty fields
require_once ('mail/class.phpmailer.php');

$mail = new PHPMailer;

if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

/*$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
*/

$mail->addAddress('raghvendratolia@gmail.com');
$mail->email_subject = "Website Contact Form:  $name";
$mail->email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$mail->headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$mail->headers .= "Reply-To: $email_address";

return $mail->Send();

/*// Create the email and send the message
$to = 'raghvendratolia@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to , $email_subject, $email_body, $headers);
return true;*/

?>


text:
'use strict';

angular.module('momusApp.directives').
    directive('buttonLoader', function ($timeout) {
        return {
            restrict: 'A',
            template: '
 ',
            transclude: true,
            scope: {
                buttonLoader: '=',
                ngDisabled: '='
            },
            link: function (scope, elm, attrs) {
                scope.showingOriginal = true;

                // Default values
                var loadingText = typeof attrs.loadingText !== 'undefined' ? attrs.loadingText : "Lagrer";
                var completedText = typeof attrs.completedText !== 'undefined' ? attrs.completedText : "Lagret";
                var showIcons = !attrs.noIcons;

                var spinner = '';
                var check = '';
                var hasBeenDisabled;

                if (showIcons) {
                    spinner = ' ';
                    check = ' ';
                }

                scope.$watch('buttonLoader', function (isLoading) {
                    if (isLoading) {
                        showLoading();
                    } else {
                        if (hasBeenDisabled) {
                            hasBeenDisabled = false;
                            showCompleted();

                            $timeout(function () {
                                showOriginal();
                            }, 1500);
                        }
                    }
                });

                function showLoading() {
                    scope.showingOriginal = false;
                    scope.customText = spinner + loadingText;

                    elm.attr('disabled', true);
                    hasBeenDisabled = true;
                }

                function showCompleted() {
                    scope.showingOriginal = false;
                    scope.customText = check + completedText;

                    elm.addClass("btn-success");
                }

                function showOriginal() {
                    scope.showingOriginal = true;
                    elm.removeClass("btn-success");

                    if (scope.ngDisabled) { // if it has a ngDisabled attribute, set disabled to that value
                        elm.attr('disabled', scope.ngDisabled);
                    } else { // if not, it's not longer disabled
                        elm.attr('disabled', false);
                    }
                }
            }
        };
    });


text:
import { getMetaData, getUser, } from 'dummy/utils/bugsnag';
import { module, test } from 'qunit';

module('Unit | Utility | bugsnag');

test('getMetaData()', function(assert) {
  const result = getMetaData();
  const expected = {
    account: {
      name: 'Bugsnag',
      plan: 'premium',
      beta_access: true
    },
  };
  assert.deepEqual(
    result,
    expected,
    'should return what\'s defined in the the app\'s util'
  );
});

test('getUser()', function(assert) {
  const result = getUser();
  const expected = {
    id: 123,
    name: 'Dummy User',
    email: 'dummy@example.com'
  };
  assert.deepEqual(
    result,
    expected,
    'should return what\'s defined in the the app\'s util'
  );
});


text:
package org.apache.camel.builder.endpoint.dsl;

import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;

/**
 * Produce or consume Apache Avro RPC services.
 *
 * Generated by camel build tools - do NOT edit this file!
 */
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface AvroEndpointBuilderFactory {

    /**
     * Builder for endpoint consumers for the Avro RPC component.
     */
    public interface AvroEndpointConsumerBuilder
            extends
                EndpointConsumerBuilder {
        default AdvancedAvroEndpointConsumerBuilder advanced() {
            return (AdvancedAvroEndpointConsumerBuilder) this;
        }
        /**
         * Avro protocol to use.
         *
         * The option is a: org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointConsumerBuilder protocol(Object protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use.
         *
         * The option will be converted to a
         * org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointConsumerBuilder protocol(String protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use defined by the FQN class name.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointConsumerBuilder protocolClassName(
                String protocolClassName) {
            doSetProperty("protocolClassName", protocolClassName);
            return this;
        }
        /**
         * Avro protocol location.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointConsumerBuilder protocolLocation(
                String protocolLocation) {
            doSetProperty("protocolLocation", protocolLocation);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointConsumerBuilder reflectionProtocol(
                boolean reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointConsumerBuilder reflectionProtocol(
                String reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointConsumerBuilder singleParameter(
                boolean singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointConsumerBuilder singleParameter(
                String singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * Authority to use (username and password).
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointConsumerBuilder uriAuthority(String uriAuthority) {
            doSetProperty("uriAuthority", uriAuthority);
            return this;
        }
        /**
         * Allows for bridging the consumer to the Camel routing Error Handler,
         * which mean any exceptions occurred while the consumer is trying to
         * pickup incoming messages, or the likes, will now be processed as a
         * message and handled by the routing Error Handler. By default the
         * consumer will use the org.apache.camel.spi.ExceptionHandler to deal
         * with exceptions, that will be logged at WARN or ERROR level and
         * ignored.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: consumer
         */
        default AvroEndpointConsumerBuilder bridgeErrorHandler(
                boolean bridgeErrorHandler) {
            doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
            return this;
        }
        /**
         * Allows for bridging the consumer to the Camel routing Error Handler,
         * which mean any exceptions occurred while the consumer is trying to
         * pickup incoming messages, or the likes, will now be processed as a
         * message and handled by the routing Error Handler. By default the
         * consumer will use the org.apache.camel.spi.ExceptionHandler to deal
         * with exceptions, that will be logged at WARN or ERROR level and
         * ignored.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: consumer
         */
        default AvroEndpointConsumerBuilder bridgeErrorHandler(
                String bridgeErrorHandler) {
            doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
            return this;
        }
    }

    /**
     * Advanced builder for endpoint consumers for the Avro RPC component.
     */
    public interface AdvancedAvroEndpointConsumerBuilder
            extends
                EndpointConsumerBuilder {
        default AvroEndpointConsumerBuilder basic() {
            return (AvroEndpointConsumerBuilder) this;
        }
        /**
         * To let the consumer use a custom ExceptionHandler. Notice if the
         * option bridgeErrorHandler is enabled then this option is not in use.
         * By default the consumer will deal with exceptions, that will be
         * logged at WARN or ERROR level and ignored.
         *
         * The option is a: org.apache.camel.spi.ExceptionHandler
         * type.
         *
         * Group: consumer (advanced)
         */
        default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
                ExceptionHandler exceptionHandler) {
            doSetProperty("exceptionHandler", exceptionHandler);
            return this;
        }
        /**
         * To let the consumer use a custom ExceptionHandler. Notice if the
         * option bridgeErrorHandler is enabled then this option is not in use.
         * By default the consumer will deal with exceptions, that will be
         * logged at WARN or ERROR level and ignored.
         *
         * The option will be converted to a
         * org.apache.camel.spi.ExceptionHandler type.
         *
         * Group: consumer (advanced)
         */
        default AdvancedAvroEndpointConsumerBuilder exceptionHandler(
                String exceptionHandler) {
            doSetProperty("exceptionHandler", exceptionHandler);
            return this;
        }
        /**
         * Sets the exchange pattern when the consumer creates an exchange.
         *
         * The option is a: org.apache.camel.ExchangePattern type.
         *
         * Group: consumer (advanced)
         */
        default AdvancedAvroEndpointConsumerBuilder exchangePattern(
                ExchangePattern exchangePattern) {
            doSetProperty("exchangePattern", exchangePattern);
            return this;
        }
        /**
         * Sets the exchange pattern when the consumer creates an exchange.
         *
         * The option will be converted to a
         * org.apache.camel.ExchangePattern type.
         *
         * Group: consumer (advanced)
         */
        default AdvancedAvroEndpointConsumerBuilder exchangePattern(
                String exchangePattern) {
            doSetProperty("exchangePattern", exchangePattern);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointConsumerBuilder basicPropertyBinding(
                String basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointConsumerBuilder synchronous(
                boolean synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointConsumerBuilder synchronous(
                String synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
    }

    /**
     * Builder for endpoint producers for the Avro RPC component.
     */
    public interface AvroEndpointProducerBuilder
            extends
                EndpointProducerBuilder {
        default AdvancedAvroEndpointProducerBuilder advanced() {
            return (AdvancedAvroEndpointProducerBuilder) this;
        }
        /**
         * Avro protocol to use.
         *
         * The option is a: org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointProducerBuilder protocol(Object protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use.
         *
         * The option will be converted to a
         * org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointProducerBuilder protocol(String protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use defined by the FQN class name.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointProducerBuilder protocolClassName(
                String protocolClassName) {
            doSetProperty("protocolClassName", protocolClassName);
            return this;
        }
        /**
         * Avro protocol location.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointProducerBuilder protocolLocation(
                String protocolLocation) {
            doSetProperty("protocolLocation", protocolLocation);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointProducerBuilder reflectionProtocol(
                boolean reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointProducerBuilder reflectionProtocol(
                String reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointProducerBuilder singleParameter(
                boolean singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointProducerBuilder singleParameter(
                String singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * Authority to use (username and password).
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointProducerBuilder uriAuthority(String uriAuthority) {
            doSetProperty("uriAuthority", uriAuthority);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: producer
         */
        default AvroEndpointProducerBuilder lazyStartProducer(
                boolean lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: producer
         */
        default AvroEndpointProducerBuilder lazyStartProducer(
                String lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
    }

    /**
     * Advanced builder for endpoint producers for the Avro RPC component.
     */
    public interface AdvancedAvroEndpointProducerBuilder
            extends
                EndpointProducerBuilder {
        default AvroEndpointProducerBuilder basic() {
            return (AvroEndpointProducerBuilder) this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointProducerBuilder basicPropertyBinding(
                String basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointProducerBuilder synchronous(
                boolean synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointProducerBuilder synchronous(
                String synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
    }

    /**
     * Builder for endpoint for the Avro RPC component.
     */
    public interface AvroEndpointBuilder
            extends
                AvroEndpointConsumerBuilder,
                AvroEndpointProducerBuilder {
        default AdvancedAvroEndpointBuilder advanced() {
            return (AdvancedAvroEndpointBuilder) this;
        }
        /**
         * Avro protocol to use.
         *
         * The option is a: org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointBuilder protocol(Object protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use.
         *
         * The option will be converted to a
         * org.apache.avro.Protocol type.
         *
         * Group: common
         */
        default AvroEndpointBuilder protocol(String protocol) {
            doSetProperty("protocol", protocol);
            return this;
        }
        /**
         * Avro protocol to use defined by the FQN class name.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointBuilder protocolClassName(String protocolClassName) {
            doSetProperty("protocolClassName", protocolClassName);
            return this;
        }
        /**
         * Avro protocol location.
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointBuilder protocolLocation(String protocolLocation) {
            doSetProperty("protocolLocation", protocolLocation);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointBuilder reflectionProtocol(
                boolean reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If protocol object provided is reflection protocol. Should be used
         * only with protocol parameter because for protocolClassName protocol
         * type will be auto detected.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointBuilder reflectionProtocol(String reflectionProtocol) {
            doSetProperty("reflectionProtocol", reflectionProtocol);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointBuilder singleParameter(boolean singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * If true, consumer parameter won't be wrapped into array. Will fail if
         * protocol specifies more then 1 parameter for the message.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: common
         */
        default AvroEndpointBuilder singleParameter(String singleParameter) {
            doSetProperty("singleParameter", singleParameter);
            return this;
        }
        /**
         * Authority to use (username and password).
         *
         * The option is a: java.lang.String type.
         *
         * Group: common
         */
        default AvroEndpointBuilder uriAuthority(String uriAuthority) {
            doSetProperty("uriAuthority", uriAuthority);
            return this;
        }
    }

    /**
     * Advanced builder for endpoint for the Avro RPC component.
     */
    public interface AdvancedAvroEndpointBuilder
            extends
                AdvancedAvroEndpointConsumerBuilder,
                AdvancedAvroEndpointProducerBuilder {
        default AvroEndpointBuilder basic() {
            return (AvroEndpointBuilder) this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointBuilder basicPropertyBinding(
                String basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointBuilder synchronous(boolean synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedAvroEndpointBuilder synchronous(String synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
    }

    public interface AvroBuilders {
        /**
         * Avro RPC (camel-avro-rpc)
         * Produce or consume Apache Avro RPC services.
         *
         * Category: rpc
         * Since: 2.10
         * Maven coordinates: org.apache.camel:camel-avro-rpc
         *
         * Syntax: avro:transport:host:port/messageName
         *
         * Path parameter: transport (required)
         * Transport to use, can be either http or netty
         * There are 2 enums and the value can be one of: http, netty
         *
         * Path parameter: port (required)
         * Port number to use
         *
         * Path parameter: host (required)
         * Hostname to use
         *
         * Path parameter: messageName
         * The name of the message to send.
         *
         * @param path transport:host:port/messageName
         */
        default AvroEndpointBuilder avro(String path) {
            return AvroEndpointBuilderFactory.endpointBuilder("avro", path);
        }
        /**
         * Avro RPC (camel-avro-rpc)
         * Produce or consume Apache Avro RPC services.
         *
         * Category: rpc
         * Since: 2.10
         * Maven coordinates: org.apache.camel:camel-avro-rpc
         *
         * Syntax: avro:transport:host:port/messageName
         *
         * Path parameter: transport (required)
         * Transport to use, can be either http or netty
         * There are 2 enums and the value can be one of: http, netty
         *
         * Path parameter: port (required)
         * Port number to use
         *
         * Path parameter: host (required)
         * Hostname to use
         *
         * Path parameter: messageName
         * The name of the message to send.
         *
         * @param componentName to use a custom component name for the endpoint
         * instead of the default name
         * @param path transport:host:port/messageName
         */
        default AvroEndpointBuilder avro(String componentName, String path) {
            return AvroEndpointBuilderFactory.endpointBuilder(componentName, path);
        }
    }
    static AvroEndpointBuilder endpointBuilder(String componentName, String path) {
        class AvroEndpointBuilderImpl extends AbstractEndpointBuilder implements AvroEndpointBuilder, AdvancedAvroEndpointBuilder {
            public AvroEndpointBuilderImpl(String path) {
                super(componentName, path);
            }
        }
        return new AvroEndpointBuilderImpl(path);
    }
}


text:
//
//  ShowImageBrowser.h
//  YHCategory
//
//  Created by 郭月辉 on 2016/11/15.
//  Copyright © 2016年 Theshy. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ShowImageBrowser : NSObject

/**
 *  点击图像放大查看
 */
+ (void)showImage:(UIImageView *)avatarImageView;
@end


text:
package com.facebook.buck.features.project.intellij.lang.android;

import com.facebook.buck.core.description.arg.CommonDescriptionArg;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.features.project.intellij.BaseIjModuleRule;
import com.facebook.buck.features.project.intellij.ModuleBuildContext;
import com.facebook.buck.features.project.intellij.model.IjModuleFactoryResolver;
import com.facebook.buck.features.project.intellij.model.IjProjectConfig;
import com.facebook.buck.io.filesystem.ProjectFilesystem;

public abstract class AndroidModuleRule<T extends CommonDescriptionArg>
    extends BaseIjModuleRule<T> {

  private final AndroidProjectType androidProjectType;

  protected AndroidModuleRule(
      ProjectFilesystem projectFilesystem,
      IjModuleFactoryResolver moduleFactoryResolver,
      IjProjectConfig projectConfig,
      AndroidProjectType androidProjectType) {
    super(projectFilesystem, moduleFactoryResolver, projectConfig);
    this.androidProjectType = androidProjectType;
  }

  @Override
  public void apply(TargetNode<T> target, ModuleBuildContext context) {
    context
        .getOrCreateAndroidFacetBuilder()
        .setAndroidProjectType(androidProjectType)
        .setAutogenerateSources(projectConfig.isAutogenerateAndroidFacetSourcesEnabled());
  }
}


text:
#pragma once
#include <aws/lookoutequipment/LookoutEquipment_EXPORTS.h>
#include <aws/lookoutequipment/LookoutEquipmentRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace LookoutEquipment
{
namespace Model
{

  /**
   */
  class AWS_LOOKOUTEQUIPMENT_API DeleteInferenceSchedulerRequest : public LookoutEquipmentRequest
  {
  public:
    DeleteInferenceSchedulerRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteInferenceScheduler"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline const Aws::String& GetInferenceSchedulerName() const{ return m_inferenceSchedulerName; }

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline bool InferenceSchedulerNameHasBeenSet() const { return m_inferenceSchedulerNameHasBeenSet; }

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline void SetInferenceSchedulerName(const Aws::String& value) { m_inferenceSchedulerNameHasBeenSet = true; m_inferenceSchedulerName = value; }

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline void SetInferenceSchedulerName(Aws::String&& value) { m_inferenceSchedulerNameHasBeenSet = true; m_inferenceSchedulerName = std::move(value); }

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline void SetInferenceSchedulerName(const char* value) { m_inferenceSchedulerNameHasBeenSet = true; m_inferenceSchedulerName.assign(value); }

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline DeleteInferenceSchedulerRequest& WithInferenceSchedulerName(const Aws::String& value) { SetInferenceSchedulerName(value); return *this;}

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline DeleteInferenceSchedulerRequest& WithInferenceSchedulerName(Aws::String&& value) { SetInferenceSchedulerName(std::move(value)); return *this;}

    /**
     *
The name of the inference scheduler to be deleted.

     */
    inline DeleteInferenceSchedulerRequest& WithInferenceSchedulerName(const char* value) { SetInferenceSchedulerName(value); return *this;}

  private:

    Aws::String m_inferenceSchedulerName;
    bool m_inferenceSchedulerNameHasBeenSet = false;
  };

} // namespace Model
} // namespace LookoutEquipment
} // namespace Aws


text:
{-# LANGUAGE NamedWildcards #-}
module InstantiatedNamedWildcardsInConstraints where

foo :: (Enum _a, _) => _a -> (String, b)
foo x = (show (succ x), x)


text:
dep 'postgres' do
  requires 'postgres commandline'

  met? { '/Applications/Postgres.app'.p.exists? }
  meet {
    log_shell "Install Postgres", "mv ~/Applications/Postgres.app /Applications/Postgres.app"
  }
end

dep 'postgres.app' do
  version_number = '9.4.1.0'
  source "https://github.com/PostgresApp/PostgresApp/releases/download/#{version_number}/Postgres-#{version_number}.zip"

  provides 'Postgres.app'
  version version_number
end

dep 'postgres commandline' do
  main_version = '9.4'
  requires 'postgres.app'

  init_string = "export PATH=/Applications/Postgres.app/Contents/Versions/#{main_version}/bin/:$PATH"

  met? {
    shell("cat ~/.bash_profile").include?(init_string)
  }
  meet {
    shell "echo '# Add postgres commandline tools to bash' >> ~/.bash_profile"
    log_shell "Add init to .bash_profile", "echo '#{init_string}' >> ~/.bash_profile"
  }
end


text:
<?php
namespace Aws\S3;

use GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;

/**
 * Extracts a region, bucket, key, and and if a URI is in path-style
 */
class S3UriParser
{
    private $pattern = '/^(.+\\.)?s3[.-]([A-Za-z0-9-]+)\\./';

    private static $defaultResult = [
        'path_style' => true,
        'bucket'     => null,
        'key'        => null,
        'region'     => null
    ];

    /**
     * Parses a URL into an associative array of Amazon S3 data including:
     *
     * - bucket: The Amazon S3 bucket (null if none)
     * - key: The Amazon S3 key (null if none)
     * - path_style: Set to true if using path style, or false if not
     * - region: Set to a string if a non-class endpoint is used or null.
     *
     * @param string|UriInterface $uri
     *
     * @return array
     * @throws \InvalidArgumentException
     */
    public function parse($uri)
    {
        $url = Psr7\uri_for($uri);
        if (!$url->getHost()) {
            throw new \InvalidArgumentException('No hostname found in URI: '
                . $uri);
        }

        if (!preg_match($this->pattern, $url->getHost(), $matches)) {
            return $this->parseCustomEndpoint($url);
        }

        // Parse the URI based on the matched format (path / virtual)
        $result = empty($matches[1])
            ? $this->parsePathStyle($url)
            : $this->parseVirtualHosted($url, $matches);

        // Add the region if one was found and not the classic endpoint
        $result['region'] = $matches[2] == 'amazonaws' ? null : $matches[2];

        return $result;
    }

    private function parseCustomEndpoint(UriInterface $url)
    {
        $result = $result = self::$defaultResult;
        $path = ltrim($url->getPath(), '/ ');
        $segments = explode('/', $path, 2);

        if (isset($segments[0])) {
            $result['bucket'] = $segments[0];
            if (isset($segments[1])) {
                $result['key'] = $segments[1];
            }
        }

        return $result;
    }

    private function parsePathStyle(UriInterface $url)
    {
        $result = self::$defaultResult;

        if ($url->getPath() != '/') {
            $path = ltrim($url->getPath(), '/');
            if ($path) {
                $pathPos = strpos($path, '/');
                if ($pathPos === false) {
                    // https://s3.amazonaws.com/bucket
                    $result['bucket'] = $path;
                } elseif ($pathPos == strlen($path) - 1) {
                    // https://s3.amazonaws.com/bucket/
                    $result['bucket'] = substr($path, 0, -1);
                } else {
                    // https://s3.amazonaws.com/bucket/key
                    $result['bucket'] = substr($path, 0, $pathPos);
                    $result['key'] = substr($path, $pathPos + 1) ?: null;
                }
            }
        }

        return $result;
    }

    private function parseVirtualHosted(UriInterface $url, array $matches)
    {
        $result = self::$defaultResult;
        $result['path_style'] = false;
        // Remove trailing "." from the prefix to get the bucket
        $result['bucket'] = substr($matches[1], 0, -1);
        $path = $url->getPath();
        // Check if a key was present, and if so, removing the leading "/"
        $result['key'] = !$path || $path == '/' ? null : substr($path, 1);

        return $result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Utils;

namespace DotVVM.Framework.Controls
{
    /// <summary>
    /// Declares a resource that will be rendered in the <see cref="BodyResourceLinks" /> control later.
    /// </summary>
    [ControlMarkupOptions(AllowContent = false)]
    public class RequiredResource : DotvvmControl
    {

        /// <summary>
        /// Gets or sets the name of the resource.
        /// </summary>
        [MarkupOptions(Required = true, AllowBinding = false)]
        public string? Name
        {
            get { return (string?)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }
        public static readonly DotvvmProperty NameProperty =
            DotvvmProperty.Register<string?, RequiredResource>(c => c.Name);

        public RequiredResource() { }
        public RequiredResource(string name)
        {
            this.Name = name;
        }

        internal protected override void OnPreRender(IDotvvmRequestContext context)
        {
            context.ResourceManager.AddRequiredResource(Name.NotNull("RequiredResource.Name must be set"));
            base.OnPreRender(context);
        }
    }
}


text:
#ifndef ZMF_IZMFINSTANCEACCESS_H
#define ZMF_IZMFINSTANCEACCESS_H

#include <atomic>
#include <future>
#include <list>
#include <memory>
#include <map>
#include "IConfigurationProvider.hpp"
#include "PeerRegistry.hpp"
#include "ModuleHandle.hpp"
#include "MessageType.hpp"
#include "ZmfMessage.hpp"
#include "ModuleUniqueId.hpp"
#include "ZmfInReply.hpp"

namespace zmf {

    /**
     * @details Interface to access a ZMF instance from a module
     * @author Jonas Grunert
     * @date created on 6/25/15.
     */
    class IZmfInstanceAccess {

    public:

        /**
         * Subscription handle representing a specific subscription.
         * Can be used to unsubscribe from a subscription
         */
        class SubscriptionHandle {
        public:
            /**
             * Interface offering possibility to unsubscribe from a subscription
             */
            class ISubscriptionHandler {
            public:
                /**
                 * Unsubscribes from the given handle
                 * @param handle Handle to unsubscribe
                 */
                virtual void unsubscribe(SubscriptionHandle* handle) = 0;

                /// Returns a new, instance unique subscription ID
                virtual uint32_t getSubId() = 0;
            };

            SubscriptionHandle(ISubscriptionHandler* unsubscribeHandler, zmf::data::MessageType topic,
                               std::function<void(const zmf::data::ZmfMessage&,
                                                  const zmf::data::ModuleUniqueId& sender)> callback) :
                    SubId(unsubscribeHandler->getSubId()),
                    unsubscribeHandler_(unsubscribeHandler), subTopic(topic),
                    callback_(callback) { }

            /**
             * Unsubscribe from this subscription
             * @throws Exception
             */
            void unsubscribe() {
                unsubscribeHandler_->unsubscribe(this);
            }

            /**
             * @return Topic of this subscription
             */
            inline const zmf::data::MessageType& getTopic() { return subTopic; }

            /**
             * @return Subscription handler callback
             */
            inline std::function<void(const zmf::data::ZmfMessage& msg,
                                      const zmf::data::ModuleUniqueId& sender)>& getCallback() { return callback_; }

            const uint32_t SubId;
        private:
            ISubscriptionHandler* unsubscribeHandler_;
            const zmf::data::MessageType subTopic;
            std::function<void(const zmf::data::ZmfMessage& msg, const zmf::data::ModuleUniqueId& sender)> callback_;
        };

        /**
         * Returns the configuration provider interface which allows to access configuration values
         * @return Interface to configuration provider
         */
        virtual const std::shared_ptr<zmf::config::IConfigurationProvider>& getConfigurationProvider() = 0;

        /**
         * @return The public interface of the PeerRegistry which offers information about all known peers
         */
        virtual const std::shared_ptr<zmf::discovery::PeerRegistry>& getPeerRegistry() = 0;

        /**
         * Sends a request to a given node and returns a future_ to await the response.
         */
        virtual zmf::data::ZmfInReply sendRequest(const zmf::data::ModuleUniqueId& target,
                                                  const zmf::data::ZmfMessage& msg) = 0;

        /**
         * Starts a subscription to the given topic. Received subscription events will be sent to the given handler callback.
         */
        virtual IZmfInstanceAccess::SubscriptionHandle subscribe(const zmf::data::MessageType& topic,
                                                                 std::function<void(const zmf::data::ZmfMessage& msg,
                                                                                const zmf::data::ModuleUniqueId& sender)> handler) = 0;

        /**
         * Publishes an event to the messaging message bus.
         */
        virtual void publish(const zmf::data::ZmfMessage& msg) = 0;

        /**
         * Called when the additional state of a module was changed.
         * Will not trigger automatically trigger a state broadcast.
         */
        virtual void onModuleAdditionalStateChanged(std::vector<uint8_t> additionalState) = 0;

        /**
         * Triggers a state broadcast for the module of this instance.
         */
        virtual void forceStateBroadcast() = 0;

        /**
         * Requests to initiate disabling of the module managed by this ZMF core
         */
        virtual void requestDisableModule() = 0;

        /**
         * Requests to initiate stopping this ZMF core and its module
         */
        virtual void requestStopInstance() = 0;

        /**
         * Requests the remote instance to be enabled. Will wait for the given timeout (ms) and return true only if a reply was
         * received for the request and if the received reply was positive
         */
        virtual bool requestEnableRemoteInstance(zmf::data::ModuleUniqueId, long timeout) = 0;

        /**
         * Requests the remote instance to be disabled. Will wait for the given timeout (ms) and return true only if a reply was
         * received for the request and if the received reply was positive
         */
        virtual bool requestDisableRemoteInstance(zmf::data::ModuleUniqueId, long timeout) = 0;

        /**
         * Requests the remote instance to stop. Will wait for the given timeout (ms) and return true only if a reply was
         * received for the request and if the received reply was positive
         */
        virtual bool requestStopRemoteInstance(zmf::data::ModuleUniqueId, long timeout) = 0;
    };

}

#endif //ZMF_IZMFINSTANCEACCESS_H


text:
const path = require('path');
//get os type then return path of respective platform library
const gifwebp=function() {
    if (process.platform === 'darwin') {

        return path.join(__dirname, "../", "/bin/libwebp_osx/bin/gif2webp");//return osx library path
    }else if (process.platform === 'linux') {

        return path.join(__dirname, "../", "/bin/libwebp_linux/bin/gif2webp");//return linux library path

    }else if (process.platform === 'win32') {

        if (process.arch === 'x64') {
            return path.join(__dirname, "../", "\\bin\\libwebp_win64\\bin\\gif2webp.exe");//return windows 64bit library path
        } else {
            console.log('Unsupported platform:', process.platform, process.arch);//show unsupported platform message
        }

    } else {
        console.log('Unsupported platform:', process.platform, process.arch);//show unsupported platform message
    }
};
module.exports = gifwebp


text:
class Ppn

  def self.parse
    objects = []

    (1..4).each do |index|
      Semester.find_or_create_by(number: index)
    end
    (1..2).each do |index|
      TeachingUnit.find_or_create_by(number: index)
    end

    # teaching_subject
    subjects = []
    doc.css('.element').each do |element|
      label = element.css('.name').first.content.to_s
      teaching_unit_number = element.css('.uevalue').first.content.to_i
      teaching_unit = TeachingUnit.where(number: teaching_unit_number).first
      TeachingSubject.find_or_create_by(label: label, teaching_unit_id: teaching_unit.id)
    end

    # teaching_category
    categories = []
    doc.css('.element .cat').each do |category|
      label = category.content.to_s
      TeachingCategory.find_or_create_by(label: label)
    end

    # Training modules
    doc.css('.element').each do |m|
      code = m.css('.id').first.content
      teaching_module = TeachingModule.find_or_create_by(code: code)
      teaching_module.label = m.css('.name').first.content
      teaching_module.semester_id = m.css('.semvalue').first.content.to_i
      teaching_unit_number = m.css('.uevalue').first.content.to_i
      teaching_unit = TeachingUnit.where(number: teaching_unit_number).first
      teaching_module.teaching_unit = TeachingUnit.where(number: teaching_unit_number).first
      teaching_subject_label = m.css('.name').first.content
      teaching_module.teaching_subject = TeachingSubject.where(label: teaching_subject_label, teaching_unit_id: teaching_unit.id).first
      teaching_category_label = m.css('.cat').first.content
      teaching_module.teaching_category = TeachingCategory.where(label: teaching_category_label).first
      teaching_module.coefficient = m.css('.coefvalue').first.content.to_i
      id = m.css('@href').first.content
      full_data = doc.css(id).first
      full_data.css('h3').each do |f|
        title = f.content
        nodes = []
        current = f.next_element
        while
          nodes.push current
          current = current.next_element
          break if current.nil? or current.name == 'h3'
        end
        case title
          when 'Objectifs du module'
            nodes.collect(&:content).each do |objective_label|
              Objective.find_or_create_by(label: objective_label, teaching_module_id: teaching_module.id)
            end
          when 'Contenus'
            teaching_module.content = nodes.collect(&:content).join(' ')
          when 'Modalités de mise en œuvre'
            teaching_module.how_to = nodes.collect(&:content).join(' ')
          when 'Prolongements possibles'
            teaching_module.what_next = nodes.collect(&:content).join(' ')
          when 'Compétences visées'
            competencies = []
            if nodes.count == 1
              competency = nodes.first.content
              competency.gsub!('Être capable de ', '')
              competency.gsub!('Être capable d\'', '')
              competencies << competency
            else
              ul = nodes.pop
              ul.css('li').each do |li|
                competency_label = li.content
                Competency.find_or_create_by(label: competency_label, teaching_module_id: teaching_module.id)
              end
            end
          when 'Mots-clés'
            list = nodes.collect(&:content).join(',')
            list.gsub!("\r\n", ' ')
            list.gsub!("\n", ' ')
            list.gsub!("\r", ' ')
            list.gsub!("
", ' ')
            list.gsub!(" ; ", ',')
            list.gsub!('…', ',')
            list.gsub!('.', ',')
            list.gsub!('                                    ', '')
            list.gsub!(',,', ',')
            list.gsub!(', ', ',')
            list.gsub!('—', ',')
            list.gsub!(', ', ',')
            list.downcase!
            keywords = list.split(',')
            keywords.each do |keyword|
              unless keyword.empty?
                Keyword.find_or_create_by(label: keyword, teaching_module_id: teaching_module.id)
              end
            end
          end
      end
      teaching_module.hours = full_data.css('.total').first.content.to_i
      teaching_module.hours_cm = full_data.css('.cm').first.content.to_i
      teaching_module.hours_td = full_data.css('.td').first.content.to_i
      teaching_module.hours_tp = full_data.css('.tp').first.content.to_i
      teaching_module.save
      objects << teaching_module
    end
    objects
  end

  def self.doc
    # TODO load html from app/public/ppn.html
    # It was in a constant, which was quite ugly
    # The code below is untested
    ppn = 'app/public/ppn.html'
    html = File.open(ppn) { |f| Nokogiri::HTML(f) }
    html
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/Theme.AppCompat.CompactMenu"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <ExpandableListView
        android:id="@+id/example_expandableListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>


text:
package org.metafacture.metamorph.maps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.metafacture.metamorph.api.helpers.AbstractReadOnlyMap;

/**
 * A map which resolves its keys by doing a REST request and returning the
 * response as value.
 *
 * @author Markus Michael Geipel
 * @author Philipp v. Böselager
 */
public final class RestMap extends AbstractReadOnlyMap<String, String> {

    private static final Pattern VAR_PATTERN = Pattern.compile("${key}", Pattern.LITERAL);
    private String charsetName = "UTF-8";
    private String url;

    public RestMap() {
    }

    public RestMap(String url) {
        this.url = url;
    }

    @Override
    public String get(final Object key) {
        final Matcher matcher = VAR_PATTERN.matcher(url);
        try {
            String urlString = matcher.replaceAll(key.toString());
            return readFromUrl(urlString);
        } catch (IOException | URISyntaxException e) {
            // There was no data result for the given URL
            return null;
        }
    }

    private String readFromUrl(final String url) throws IOException, URISyntaxException {
        InputStream inputStream = new URL(new URI(url.replace(" ", "%20")).toASCIIString()).openConnection()
                .getInputStream();
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, Charset.forName(charsetName)));
            StringBuilder stringBuffer = new StringBuilder();
            int value;
            while ((value = reader.read()) != -1) {
                stringBuffer.append((char) value);
            }
            return stringBuffer.toString();
        } finally {
            inputStream.close();
        }
    }

    public void setUrl(final String url) {
        this.url = url;
    }

    public void setCharsetName(String name) {
        charsetName = name;
    }

}


text: throw Error('mu/drivers/tee does not exist, you want http://npm.im/mu-tee')


text:
<!---
FrozenIsBool True
-->

##Example

We can build a random array


text:
#ifndef OPENALPR_PLATEMASK_H
#define	OPENALPR_PLATEMASK_H

#include BLIK_OPENCV_U_opencv2__imgproc__imgproc_hpp //original-code:"opencv2/imgproc/imgproc.hpp"
#include BLIK_OPENALPR_U_pipeline_data_h //original-code:"pipeline_data.h"
#include "textcontours.h"

namespace alpr
{

  class PlateMask {
  public:
    PlateMask(PipelineData* pipeline_data);
    virtual ~PlateMask();

    bool hasPlateMask;

    cv::Mat getMask();

    void findOuterBoxMask(std::vector<TextContours > contours);

  private:

    PipelineData* pipeline_data;
    cv::Mat plateMask;

  };

}
#endif	/* OPENALPR_PLATEMASK_H */


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>All Classes</title>
<meta name="date" content="2013-04-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

ApiKeys

FileSystem

MtGox

TradeInterface

UsageExample


text:
This is the Math::Segment class.

Represents a line segment.

## Initializer

```
$segment = Segment($pt1: Point, $pt2: Point)
```

Creates a line segment given two endpoints.

* __pt1__: Point - An endpoint.

* __pt2__: Point - Another endpoint.

## Methods

### length

```
$segment.length
```

Computed property. Length of the line segment.

### endpoints

```
$segment.endpoints
```

Computed property. A list of endpoints.

### midpoint

```
$segment.midpoint
```

Computed property. Midpoint of the line segment.

End of the Math::Segment class.

This file was generated automatically by the Ferret compiler from
Segment.frt.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="ImageTextButtonStyle" format="reference"/>

    <declare-styleable name="ImageTextButtonStyle">
        <attr name="topIcon" format="reference" />
        <attr name="rightIcon" format="reference"/>
    </declare-styleable>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/match_match"
    android:background="@color/bg_root_black"
    android:orientation="vertical" >

    <LinearLayout style="@style/title_top_ll" >

        <Button
            android:id="@+id/btn_back"
            android:layout_width="@dimen/size_icon_normal"
            android:layout_height="@dimen/size_icon_normal"
            android:background="@drawable/btn_back_selector" />

        <TextView
            style="@style/title_top_tv"
            android:text="@string/common_number_query" />
    </LinearLayout>

    <ExpandableListView
        android:id="@+id/elv_number"
        style="@style/match_match"
        android:layout_margin="@dimen/size_normal"
        android:background="@color/bg_black"
        android:divider="@color/divider"
        android:dividerHeight="@dimen/size_divider"
        android:cacheColorHint="@android:color/transparent"
        android:listSelector="@drawable/bg_item_common_selector" >
    </ExpandableListView>

</LinearLayout>


text:
using System;

namespace FubarDev.FtpServer
{
    /// <summary>
    /// The interface that must be implemented by the FTP server.
    /// </summary>
    public interface IFtpServer : IPausableFtpService
    {
        /// <summary>
        /// This event is raised when the connection is ready to be configured.
        /// </summary>
        [Obsolete("Register a service of type IFtpConnectionConfigurator instead.")]
        event EventHandler<ConnectionEventArgs>? ConfigureConnection;

        /// <summary>
        /// This event is raised when the listener was started.
        /// </summary>
        event EventHandler<ListenerStartedEventArgs>? ListenerStarted;

        /// <summary>
        /// Gets the public IP address (required for <c>PASV</c> and <c>EPSV</c>).
        /// </summary>
        string? ServerAddress { get; }

        /// <summary>
        /// Gets the port on which the FTP server is listening for incoming connections.
        /// </summary>
        /// <remarks>
        /// This value is only final after the <see cref="ListenerStarted"/> event was raised.
        /// </remarks>
        int Port { get; }

        /// <summary>
        /// Gets the max allows active connections.
        /// </summary>
        /// <remarks>
        /// This will cause connections to be refused if count is exceeded.
        /// 0 (default) means no control over connection count.
        /// </remarks>
        int MaxActiveConnections { get; }

        /// <summary>
        /// Gets a value indicating whether server ready to receive incoming connections.
        /// </summary>
        bool Ready { get; }

        /// <summary>
        /// Gets the FTP server statistics.
        /// </summary>
        IFtpServerStatistics Statistics { get; }

        /// <summary>
        /// Starts the FTP server in the background.
        /// </summary>
        [Obsolete("User IFtpServerHost.StartAsync instead.")]
        void Start();

        /// <summary>
        /// Stops the FTP server.
        /// </summary>
        /// <remarks>
        /// The FTP server cannot be started again after it was stopped.
        /// </remarks>
        [Obsolete("User IFtpServerHost.StopAsync instead.")]
        void Stop();
    }
}


text:
Heaven
======

[![Build
Status](https://travis-ci.org/TailorDev/heaven.svg?branch=tailordev)](https://travis-ci.org/TailorDev/heaven)

Heaven is an API that integrates with GitHub's [Deployment API][1]. It receives
[deployment events][2] from GitHub and pushes code to our servers. This is a
fork of [atmos/heaven](https://github.com/atmos/heaven) that is tweaked for
[TailorDev](http://tailordev.fr) needs.

Documentation
-------------

* [Overview](/doc/overview.md)
* [Installation](/doc/installation.md)
* [Deployment Providers](/doc/providers.md)
* [Deployment Notifications](/doc/notifications.md)
* [Environment Locking](/doc/locking.md)

Launch on Heroku
----------------

[![Launch on
Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

[1]: http://developer.github.com/v3/repos/deployments/
[2]: https://developer.github.com/v3/repos/deployments/#create-a-deployment


text:
package com.eliteams.quick4j.core.entity;

/**
 * ServiceException : 封装业务层发生的异常
 *
 * @author StarZou
 * @since 2014-09-27 18:09
 */
public class ServiceException extends UserException {

	private static final long serialVersionUID = 8554025843930995042L;

}


text:
// JScript File
$(function () {
    var selectedArray = [];
    var numeroTaxa = $(".classTaxa").length - 1;
    var o = $($(".classTaxa").clone()[0]);
    o.removeAttr("style");

    var fnTipoTaxa = function (selectTaxa) {

        calculaPacoteLocacao();

        var drop = selectTaxa.attr("id").replace("cboTaxaTipo_", "");
        selectedArray[drop] = selectTaxa.val();

        //Percorre os dropdowns
        $(".classTaxaTipo").find("select").each(function () {

            //Não percorrer o dropdown default
            if ($(this).attr("id") != "cboTaxaTipo_Default") {
                var selectValue = $(this).val();

                //Percorre as opçoes do select
                $(this).find("option").each(function (i) {

                    if ($(this).val() != 0 && $(this).val() != selectValue && ($.inArray($(this).val(), selectedArray) != -1))
                        $(this).prop("disabled", true);
                    else
                        $(this).prop("disabled", false);

                    //Se for laudêmio, ocultar a periodicidade
                    if (selectValue == 3)
                        $(this).parent().parent().next().hide();
                    else
                        $(this).parent().parent().next().show();
                });
            }
        });
    }

    //Adicionar uma taxa
    $("#btnAddTaxa").click(function () {

        if ($(".classTaxa").length - 1 == $("#hdMaxTaxas").val())
            bootbox.alert("Você pode adicionar somente uma taxa de cada tipo.", function () { });
        else {
            a = o.clone();

            $(a).find("select,input").each(function () {
                $(this).attr("id", $(this).attr("id") + "_" + numeroTaxa);

                $(this).attr("name", $(this).attr("name").replace("_Default", "") + "_" + numeroTaxa);
            });

            $(a).find("[class=classTaxaValor]").maskMoney();

            numeroTaxa++;

            $(".addTaxa").before(a);

            $(a).find("a[class=lnkExcluirTaxa]").bind("click", function () {
                ExcluirTaxa($(this)); return (false);
                numeroTaxa = numeroTaxa - 1;
            });

            //Adiciona evento change
            $(a).find("select[class=classTaxaTipo]").change(function () {
                fnTipoTaxa($(this));
            }).change();

            //Adiciona evento calculaPacoteLocacao
            $(a).find("select[name*='cboTaxaPeriodicidade_']").change(function () {
                calculaPacoteLocacao();
            });
            $(a).find("input[name*='txTaxa_']").bind('keyup', calculaPacoteLocacao);

            $("#hdTotalTaxas").val($(".classTaxa").length - 1);
        }

        return (false);
    });

    //Adicionar evento excluir para os elementos que já existem
    $(".lnkExcluirTaxa").click(function () { ExcluirTaxa($(this)); return (false); });

    //Adicionar evento change para os elementos que já existem
    $(".classTaxaTipo").find("select").change(function () { fnTipoTaxa($(this)); }).change();

    //Adicionar evento calculaPacoteLocacao para os elementos que já existem
    $("select[name*='cboTaxaPeriodicidade_']").change(calculaPacoteLocacao);
    $("input[name*='txTaxa_']").bind('keyup', calculaPacoteLocacao);

    //Excluir uma taxa
    function ExcluirTaxa(objLnkExcluir) {
        bootbox.confirm({
            message: "Tem certeza que deseja excluir essa taxa?",
            callback: function (result) {
                if (result) {
                    var drop = objLnkExcluir.parent().parent().find("select").attr("id").replace("cboTaxaTipo_", "");

                    objLnkExcluir.parent().parent().find("select").parent().remove();
                    objLnkExcluir.parent().parent().find("input[name*='txTaxa_']").parent().remove();

                    selectedArray[drop] = null;
                    objLnkExcluir.parent().parent().hide();
                    $("#hdTotalTaxas").val($(".classTaxa").length - 1);
                    calculaPacoteLocacao();
                }
            }
        });
    }

    //Popula array com valores de dropdowns já existentes
    $(".classTaxaTipo").find("select").each(function () {

        //Não percorrer o dropdown default
        if ($(this).attr("id") != "cboTaxaTipo_Default") {
            var drop = $(this).attr("id").replace("cboTaxaTipo_", "");
            selectedArray[drop] = $(this).val();
        }
    });

    //Caso seja um imóvel novo ou que não possua nenhuma taxa, adicionar uma vazia
    if (numeroTaxa < 1) { $("#btnAddTaxa").trigger("click"); }

    //Dispara um change inicial
    $(".classTaxaTipo").find("select").eq(1).change();

    $("#hdTotalTaxas").val($(".classTaxa").length - 1);
});


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

namespace StatMaster.Data
{
    class SettingsData : BaseData
    {

        public Settings settings;

        public SettingsData()
        {
            dataVersionIdx = 1;
        }

        protected override Dictionary<string, object> getDict(string handle)
        {
            Dictionary<string, object> dict = base.getDict(handle);

            dict.Add("devMode", settings.devMode);

            dict.Add("updateGameData", settings.updateGameData);
            dict.Add("updateParkData", settings.updateParkData);
            dict.Add("updateParkSessionData", settings.updateParkSessionData);

            dict.Add("updateProgressionData", settings.updateProgressionData);
            dict.Add("progressionDataUpdateInterval", settings.progressionDataUpdateInterval);

            dict.Add("updatePeopleData", settings.updatePeopleData);
            dict.Add("updateAttractionsData", settings.updateAttractionsData);
            dict.Add("updateShopsnData", settings.updateShopsData);

            dict.Add("updateAutoSaveData", settings.updateAutoSaveData);
            dict.Add("ignoreQuickSaveFileNames", settings.ignoreQuickSaveFileNames);
            dict.Add("ignoreAutoSaveFileNames", settings.ignoreAutoSaveFileNames);

            return dict;
        }

        protected override bool setObjByKey(string handle, string key, object obj)
        {
            bool success = base.setObjByKey(handle, key, obj);

            switch (key)
            {
                case "devMode":
                    settings.devMode = Convert.ToBoolean(obj);
                    break;
                case "updateGameData":
                    settings.updateGameData = Convert.ToBoolean(obj);
                    break;
                case "updateParkData":
                    settings.updateParkData = Convert.ToBoolean(obj);
                    break;
                case "updateParkSessionData":
                    settings.updateParkSessionData = Convert.ToBoolean(obj);
                    break;
                case "updateProgressionData":
                    settings.updateProgressionData = Convert.ToBoolean(obj);
                    break;
                case "progressionDataUpdateInterval":
                    settings.progressionDataUpdateInterval = Convert.ToUInt32(obj);
                    break;
                case "updatePeopleData":
                    settings.updatePeopleData = Convert.ToBoolean(obj);
                    break;
                case "updateAttractionsData":
                    settings.updateAttractionsData = Convert.ToBoolean(obj);
                    break;
                case "updateShopsData":
                    settings.updateShopsData = Convert.ToBoolean(obj);
                    break;
                case "updateAutoSaveData":
                    settings.updateAutoSaveData = Convert.ToBoolean(obj);
                    break;
                case "ignoreQuickSaveFileNames":
                    settings.ignoreQuickSaveFileNames = Convert.ToBoolean(obj);
                    break;
                case "ignoreAutoSaveFileNames":
                    settings.ignoreAutoSaveFileNames = Convert.ToBoolean(obj);
                    break;
            }

            return true;
        }
    }
}