def Func(arg_0, arg_1='', **arg_2: arg_3):
        """Get a list of top clans by war

        location_id: Optional[str] = ''
            A location ID or '' (global)
            See https://github.com/RoyaleAPI/cr-api-data/blob/master/json/regions.json
            for a list of acceptable location IDs
        \*\*keys: Optional[list] = None
            Filter which keys should be included in the
            response
        \*\*exclude: Optional[list] = None
            Filter which keys should be excluded from the
            response
        \*\*max: Optional[int] = None
            Limit the number of items returned in the response
        \*\*page: Optional[int] = None
            Works with max, the zero-based page of the
            items
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_4 = arg_0.api.TOP + '/war/' + str(arg_1)
        return arg_0._get_model(arg_4, PartialClan, **arg_2)


def Func(arg_0, **arg_1: arg_2):
        """Get a list of most queried players

        \*\*keys: Optional[list] = None
            Filter which keys should be included in the
            response
        \*\*exclude: Optional[list] = None
            Filter which keys should be excluded from the
            response
        \*\*max: Optional[int] = None
            Limit the number of items returned in the response
        \*\*page: Optional[int] = None
            Works with max, the zero-based page of the
            items
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_3 = arg_0.api.POPULAR + '/players'
        return arg_0._get_model(arg_3, PartialPlayerClan, **arg_1)


def Func(arg_0, **arg_1: arg_2):
        """Get a list of most queried tournaments

        \*\*keys: Optional[list] = None
            Filter which keys should be included in the
            response
        \*\*exclude: Optional[list] = None
            Filter which keys should be excluded from the
            response
        \*\*max: Optional[int] = None
            Limit the number of items returned in the response
        \*\*page: Optional[int] = None
            Works with max, the zero-based page of the
            items
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_3 = arg_0.api.POPULAR + '/tournament'
        return arg_0._get_model(arg_3, PartialTournament, **arg_1)


def Func(arg_0, **arg_1: arg_2):
        """Get a list of queried tournaments

        \*\*keys: Optional[list] = None
            Filter which keys should be included in the
            response
        \*\*exclude: Optional[list] = None
            Filter which keys should be excluded from the
            response
        \*\*max: Optional[int] = None
            Limit the number of items returned in the response
        \*\*page: Optional[int] = None
            Works with max, the zero-based page of the
            items
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_3 = arg_0.api.TOURNAMENT + '/known'
        return arg_0._get_model(arg_3, PartialTournament, **arg_1)


def Func(arg_0, arg_1: arg_2, arg_3=None):
        """Get information about a player

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_4 = arg_0.api.PLAYER + '/' + arg_1
        return arg_0._get_model(arg_4, FullPlayer, arg_3=arg_3)


def Func(arg_0, arg_1: arg_2, arg_3: arg_4=None):
        """Get inforamtion about a clan

        Parameters
        ----------
        tag: str
            A valid tournament tag. Minimum length: 3
            Valid characters: 0289PYLQGRJCUV
        timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_5 = arg_0.api.CLAN + '/' + arg_1
        return arg_0._get_model(arg_5, FullClan, arg_3=arg_3)


def Func(arg_0, **arg_1: arg_2):
        """Search for a clan. At least one
        of the filters must be present

        Parameters
        ----------
        name: Optional[str]
            The name of a clan
            (has to be at least 3 characters long)
        locationId: Optional[int]
            A location ID
        minMembers: Optional[int]
            The minimum member count
            of a clan
        maxMembers: Optional[int]
            The maximum member count
            of a clan
        minScore: Optional[int]
            The minimum trophy score of
            a clan
        \*\*limit: Optional[int] = None
            Limit the number of items returned in the response
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_3 = arg_0.api.CLAN
        return arg_0._get_model(arg_3, PartialClan, **arg_1)


def Func(arg_0, arg_1: arg_2):
        """Get the arena image URL

        Parameters
        ---------
        obj: official_api.models.BaseAttrDict
            An object that has the arena ID in ``.arena.id``
            Can be ``Profile`` for example.

        Returns None or str
        """
        arg_3 = arg_1.arena.id
        for arg_4 in arg_0.constants.arenas:
            if arg_4.id == arg_3:
                return 'https://royaleapi.github.io/cr-api-assets/arenas/arena{}.png'.format(arg_4.arena_id)


def Func(arg_0, arg_1: arg_2):
        """Form a deck link

        Parameters
        ---------
        deck: official_api.models.BaseAttrDict
            An object is a deck. Can be retrieved from ``Player.current_deck``

        Returns str
        """
        arg_3 = 'https://link.clashroyale.com/deck/en?deck='

        for arg_4 in arg_1:
            arg_5 = arg_0.get_card_info(arg_4.name)
            arg_3 += '{0.id};'.format(arg_5)

        return arg_3


def Func(arg_0, Func, arg_2, arg_3, arg_4):
    """Export gene panels to .bed like format.

        Specify any number of panels on the command line
    """
    LOG.info("Running scout export panel")
    arg_5 = arg_0.obj['adapter']
    # Save all chromosomes found in the collection if panels
    arg_6 = set()

    if not Func:
        LOG.warning("Please provide at least one gene panel")
        arg_0.abort()

    LOG.info("Exporting panels: {}".format(', '.join(Func)))
    if arg_3:
        if arg_4:
            arg_4 = [arg_4]
        arg_7 = export_panels(
            arg_5=arg_5,
            panels=Func,
            versions=arg_4,
            arg_2=arg_2,
        )
    else:
        arg_7 = export_gene_panels(
            arg_5=arg_5,
            panels=Func,
            arg_4=arg_4,
            )
    for arg_8 in arg_7:
        click.echo(arg_8)


def Func(arg_0, arg_1):
    """
    Given a weekday and a date, will increment the date until it's
    weekday matches that of the given weekday, then that date is returned.
    """
    while arg_0 != arg_1.weekday():
        arg_1 += timedelta(days=1)
    return arg_1


def Func(arg_0, arg_1=None):
        """
        Add 'num' to the day and count that day until we reach end_Func, or
        until we're outside of the current month, counting the days
        as we go along.
        """
        if arg_1 is None:
            arg_1 = arg_0.day

        try:
            arg_2 = date(arg_0.year, arg_0.month, arg_1)
        except ValueError:  # out of range day
            return arg_0.count

        if arg_0.count_first and arg_2 <= arg_0.end_Func:
            arg_0.count_it(arg_2.day)

        arg_2 += timedelta(days=arg_0.num)

        if arg_0.end_on is not None:
            while arg_2.month == arg_0.month and \
                    arg_2 <= arg_0.end_Func and \
                    arg_2.day <= arg_0.end_on:
                arg_0.count_it(arg_2.day)
                arg_2 += timedelta(days=arg_0.num)
        else:
            while arg_2.month == arg_0.month and arg_2 <= arg_0.end_Func:
                arg_0.count_it(arg_2.day)
                arg_2 += timedelta(days=arg_0.num)


def Func(arg_0, arg_1, arg_2):
        """
        Starts from 'start' day and counts backwards until 'end' day.
        'start' should be >= 'end'. If it's equal to, does nothing.
        If a day falls outside of end_repeat, it won't be counted.
        """
        arg_3 = arg_1
        arg_4 = arg_1 - arg_2
        try:
            if date(arg_0.year, arg_0.month, arg_3) <= arg_0.end_repeat:
                arg_0.count_it(arg_3)
        # a value error likely means the event runs past the end of the month,
        # like an event that ends on the 31st, but the month doesn't have that
        # many days. Ignore it b/c the dates won't be added to calendar anyway
        except ValueError:
            pass
        for arg_5 in xrange(arg_4):
            arg_3 -= 1
            try:
                if date(arg_0.year, arg_0.month, arg_3) <= arg_0.end_repeat:
                    arg_0.count_it(arg_3)
            except ValueError:
                pass


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
    """Export causative variants for a collaborator

    Args:
        adapter(MongoAdapter)
        collaborator(str)
        document_id(str): Search for a specific variant
        case_id(str): Search causative variants for a case

    Yields:
        variant_obj(scout.Models.Variant): Variants marked as causative ordered by position.
    """

    # Store the variants in a list for sorting
    arg_4 = []
    if arg_2:
        yield arg_0.variant(arg_2)
        return

    arg_5 = arg_0.get_causatives(
        institute_id=arg_1,
        arg_3=arg_3
        )
    ##TODO add check so that same variant is not included more than once
    for arg_2 in arg_5:

        arg_6 = arg_0.variant(arg_2)
        arg_7 = arg_6['chromosome']
        # Convert chromosome to integer for sorting
        arg_8 = CHROMOSOME_INTEGERS.get(arg_7)
        if not arg_8:
            LOG.info("Unknown chromosome %s", arg_7)
            continue

        # Add chromosome and position to prepare for sorting
        arg_4.append((arg_8, arg_6['position'], arg_6))

    # Sort varants based on position
    arg_4.sort(key=lambda x: (x[0], x[1]))

    for arg_9 in arg_4:
        arg_6 = arg_9[2]
        yield arg_6


def Func(arg_0, arg_1):
    """Export mitochondrial variants for a case to create a MT excel report

    Args:
        variants(list): all MT variants for a case, sorted by position
        sample_id(str) : the id of a sample within the case

    Returns:
        document_lines(list): list of lines to include in the document
    """
    arg_2 = []
    for arg_3 in arg_0:
        arg_4 = []
        arg_5 = arg_3.get('position')
        arg_6 = '>'.join([arg_3.get('reference'),arg_3.get('alternative')])
        arg_4.append(arg_5)
        arg_4.append(arg_6)
        arg_4.append(str(arg_5)+arg_6)
        arg_7 = []
        arg_8 = []
        for arg_9 in arg_3.get('genes'):
            arg_7.append(arg_9.get('hgnc_symbol',''))
            for arg_10 in arg_9.get('transcripts'):
                if arg_10.get('is_canonical') and arg_10.get('protein_sequence_name'):
                    arg_8.append(urllib.parse.unquote(arg_10.get('protein_sequence_name')))
        arg_4.append(','.join(arg_8))
        arg_4.append(','.join(arg_7))
        arg_11 = ''
        arg_12 = ''
        for arg_13 in arg_3['samples']:
            if arg_13.get('sample_id') == arg_1:
                arg_11 = arg_13['allele_depths'][0]
                arg_12 = arg_13['allele_depths'][1]
        arg_4.append(arg_11)
        arg_4.append(arg_12)
        arg_2.append(arg_4)
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """
    Update a Func in the database
    """
    arg_6 = arg_0.obj['adapter']

    arg_7 = arg_6.Func(arg_1)

    if not arg_7:
        LOG.warning("User %s could not be found", arg_1)
        arg_0.abort()

    arg_8 = set(arg_7.get('roles',[]))
    if arg_2:
        if not arg_2 in arg_7['roles']:
            arg_8 = set(arg_7['roles'])
            arg_8.add(arg_2)
            LOG.info("Adding role %s to Func", arg_2)
        else:
            LOG.warning("User already have role %s", arg_2)

    if arg_4:
        try:
            arg_8.remove('admin')
            LOG.info("Removing admin rights from Func %s", arg_1)
        except KeyError as err:
            LOG.info("User %s does not have admin rights", arg_1)

    arg_7['roles'] = list(arg_8)

    arg_9 = set(arg_7.get('institutes',[]))
    for arg_10 in arg_3:
        arg_11 = arg_6.institute(arg_10)
        if not arg_11:
            LOG.warning("Institute %s could not be found", arg_10)
        else:
            arg_9.add(arg_10)
            LOG.info("Adding institute %s to Func", arg_10)

    for arg_10 in arg_5:
        try:
            arg_9.remove(arg_10)
            LOG.info("Removing institute %s from Func", arg_10)
        except KeyError as err:
            LOG.info("User does not have access to institute %s", arg_10)

    arg_7['institutes'] = list(arg_9)

    arg_12 = arg_6.update_Func(arg_7)


def Func(arg_0, arg_1):
    """Display a list of STR variants."""
    arg_2 = int(request.args.get('page', 1))
    arg_3 = request.args.get('variant_type', 'clinical')

    arg_4 = StrFiltersForm(request.args)

    arg_5, arg_6 = institute_and_case(store, arg_0, arg_1)

    arg_7 = arg_4.data
    arg_7['variant_type'] = arg_3

    arg_8 = store.variants(arg_6['_id'], category='str',
        arg_7=arg_7)
    arg_9 = controllers.Func(store, arg_5, arg_6,
        arg_8, arg_2)
    return dict(institute=arg_5, case=arg_6,
        arg_3 = arg_3, arg_4=arg_4, arg_2=arg_2, **arg_9)


def Func(arg_0, arg_1, arg_2):
    """Display a specific STR variant."""
    arg_3 = controllers.Func(store, arg_0, arg_1, arg_2)
    return arg_3


def Func(arg_0, arg_1):
    """Show cancer variants overview."""
    arg_2 = controllers.Func(store, request.args, arg_0, arg_1)
    return arg_2


def Func(arg_0, arg_1, arg_2):
    """ACMG classification form."""
    if request.method == 'GET':
        arg_3 = controllers.Func(store, arg_0, arg_1, arg_2)
        return arg_3
    else:
        arg_4 = []
        arg_5 = request.form.getlist('criteria')
        for arg_6 in arg_5:
            arg_4.append(dict(
                arg_6=arg_6,
                comment=request.form.get("comment-{}".format(arg_6)),
                links=[request.form.get("link-{}".format(arg_6))],
            ))
        arg_7 = controllers.Func_post(store, arg_0, arg_1, arg_2,
                                             current_user.email, arg_4)
        flash("classified as: {}".format(arg_7), 'info')
        return redirect(url_for('.variant', arg_0=arg_0, arg_1=arg_1,
                                arg_2=arg_2))


def Func():
    """Calculate an ACMG classification from submitted criteria."""
    arg_0 = request.args.getlist('criterion')
    arg_1 = get_Func(arg_0)
    return jsonify(dict(arg_1=arg_1))


def Func(arg_0, arg_1):
    """Parse gene panel file and fill in HGNC symbols for filter."""
    arg_2 = arg_5.symbol_file.data

    if arg_2.filename == '':
        flash('No selected file', 'warning')
        return redirect(request.referrer)

    try:
        arg_3 = io.StringIO(arg_2.stream.read().decode('utf-8'), newline=None)
    except UnicodeDecodeError as error:
        flash("Only text files are supported!", 'warning')
        return redirect(request.referrer)

    arg_4 = request.args.get('category')

    if(arg_4 == 'sv'):
        arg_5 = SvFiltersForm(request.args)
    else:
        arg_5 = FiltersForm(request.args)

    arg_6 = set(arg_5.hgnc_symbols.data)
    arg_7 = controllers.Func(store, arg_0, arg_1, arg_3)
    arg_6.update(arg_7)
    arg_5.hgnc_symbols.data = ','.join(arg_6)
    # reset gene panels
    arg_5.gene_panels.data = ''
    # HTTP redirect code 307 asks that the browser preserves the method of request (POST).
    if(arg_4 == 'sv'):
        return redirect(url_for('.sv_variants', arg_0=arg_0, arg_1=arg_1,
                            **arg_5.data), code=307)
    else:
        return redirect(url_for('.variants', arg_0=arg_0, arg_1=arg_1,
                            **arg_5.data), code=307)


def Func():
    """Download all verified variants for user's cases"""
    arg_0 = store.user(current_user.email)
    arg_1 = arg_0.get('institutes')
    arg_2 = os.path.join(variants_bp.static_folder, 'verified_folder')
    os.makedirs(arg_2, exist_ok=True)

    arg_3 = controllers.verified_excel_file(store, arg_1, arg_2)
    if arg_3:
        arg_4 = datetime.datetime.now().strftime('%Y-%m-%d')
        # zip the files on the fly and serve the archive to the user
        arg_5 = io.BytesIO()
        with zipfile.ZipFile(arg_5, mode='w') as z:
            for arg_6 in pathlib.Path(arg_2).iterdir():
                zipfile.ZipFile
                z.write(arg_6, os.path.basename(arg_6))
        arg_5.seek(0)

        # remove temp folder with excel files in it
        shutil.rmtree(arg_2)

        return send_file(
            arg_5,
            mimetype='application/zip',
            as_attachment=True,
            attachment_filename='_'.join(['scout', 'verified_variants', arg_4])+'.zip'
        )
    else:
        flash("No verified variants could be exported for user's institutes", 'warning')
        return redirect(request.referrer)


def Func(arg_0):
    """Return a dictionary with hgnc symbols as keys

    Value of the dictionaries are information about the hgnc ids for a symbol.
    If the symbol is primary for a gene then 'true_id' will exist.
    A list of hgnc ids that the symbol points to is in ids.

    Args:
        hgnc_genes(dict): a dictionary with hgnc_id as key and gene info as value

    Returns:
        alias_genes(dict):
            {
                'hgnc_symbol':{
                    'true_id': int,
                    'ids': list(int)
                    }
            }
    """
    arg_1 = {}
    for arg_2 in arg_0:
        arg_3 = arg_0[arg_2]
        # This is the primary symbol:
        arg_4 = arg_3['hgnc_symbol']

        for arg_5 in arg_3['previous_symbols']:
            arg_6 = None
            if arg_5 == arg_4:
                arg_6 = arg_2
            if arg_5 in arg_1:
                arg_1[arg_5.upper()]['ids'].add(arg_2)
                if arg_6:
                    arg_1[arg_5.upper()]['true_id'] = arg_2
            else:
                arg_1[arg_5.upper()] = {
                    'true': arg_6,
                    'ids': set([arg_2])
                }

    return arg_1


def Func(arg_0, arg_1, arg_2):
    """Add information of incomplete penetrance"""
    LOG.info("Add incomplete penetrance info")
    for arg_3 in get_incomplete_penetrance_genes(arg_2):
        for arg_4 in get_correct_ids(arg_3, arg_1):
            arg_0[arg_4]['incomplete_penetrance'] = True


def Func(arg_0, arg_1, arg_2, arg_3,
               arg_4, arg_5):
    """Gather information from different sources and return a gene dict

    Extract information collected from a number of sources and combine them
    into a gene dict with HGNC symbols as keys.

    hgnc_id works as the primary symbol and it is from this source we gather
    as much information as possible (hgnc_complete_set.txt)

    Coordinates are gathered from ensemble and the entries are linked from hgnc
    to ensembl via ENSGID.

    From exac the gene intolerance scores are collected, genes are linked to hgnc
    via hgnc symbol. This is a unstable symbol since they often change.

        Args:
            ensembl_lines(iterable(str)): Strings with ensembl gene information
            hgnc_lines(iterable(str)): Strings with hgnc gene information
            exac_lines(iterable(str)): Strings with exac PLi score info
            mim2gene_lines(iterable(str))
            genemap_lines(iterable(str))
            hpo_lines(iterable(str)): Strings with hpo gene information

        Yields:
            gene(dict): A dictionary with gene information
    """
    arg_6 = {}
    LOG.info("Linking genes")
    # HGNC genes are the main source, these define the gene dataset to use
    # Try to use as much information as possible from hgnc
    for arg_7 in parse_hgnc_genes(arg_1):
        arg_8 = arg_7['hgnc_id']
        arg_6[arg_8] = arg_7

    add_ensembl_info(arg_6, arg_0)

    arg_9 = genes_by_alias(arg_6)

    add_exac_info(arg_6, arg_9, arg_2)

    add_omim_info(arg_6, arg_9, arg_4, arg_3)

    add_incomplete_penetrance(arg_6, arg_9, arg_5)

    return arg_6


def Func(arg_0, arg_1):
    """Get the cytoband coordinate for a position

    Args:
        chrom(str)
        pos(int)

    Returns:
        coordinate(str)
    """
    arg_2 = ""

    if arg_0 in CYTOBANDS:
        for arg_3 in CYTOBANDS[arg_0][arg_1]:
            arg_2 = arg_3.data

    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=None):
    """Get the subcategory for a VCF variant

    The sub categories are:
        'snv', 'indel', 'del', 'ins', 'dup', 'bnd', 'inv'

    Args:
        alt_len(int)
        ref_len(int)
        category(str)
        svtype(str)

    Returns:
        subcategory(str)
    """
    arg_4 = ''

    if arg_2 in ('snv', 'indel', 'cancer'):
        if arg_1 == arg_0:
            arg_4 = 'snv'
        else:
            arg_4 = 'indel'
    elif arg_2 == 'sv':
        arg_4 = arg_3

    return arg_4


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None):
    """Return the end coordinate for a variant

    Args:
        pos(int)
        alt(str)
        category(str)
        snvend(str)
        svend(int)
        svlen(int)

    Returns:
        end(int)
    """
    # If nothing is known we set end to be same as start
    arg_6 = arg_0
    # If variant is snv or indel we know that cyvcf2 can handle end pos
    if arg_2 in ('snv', 'indel', 'cancer'):
        arg_6 = arg_3

    # With SVs we have to be a bit more careful
    elif arg_2 == 'sv':
        # The END field from INFO usually works fine
        arg_6 = arg_4

        # For some cases like insertions the callers set end to same as pos
        # In those cases we can hope that there is a svlen...
        if arg_4 == arg_0:
            if arg_5:
                arg_6 = arg_0 + arg_5
        # If variant is 'BND' they have ':' in alt field
        # Information about other end is in the alt field
        if ':' in arg_1:
            arg_7 = BND_ALT_PATTERN.match(arg_1)
            if arg_7:
                arg_6 = int(arg_7.group(2))

    return arg_6


def Func(arg_0, arg_1):
    """Find out the coordinates for a variant

    Args:
        variant(cyvcf2.Variant)

    Returns:
        coordinates(dict): A dictionary on the form:
        {
            'position':<int>,
            'end':<int>,
            'end_chrom':<str>,
            'length':<int>,
            'sub_category':<str>,
            'mate_id':<str>,
            'cytoband_start':<str>,
            'cytoband_end':<str>,
        }
    """
    arg_2 = arg_0.REF

    if arg_0.ALT:
        arg_3 = arg_0.ALT[0]
    if arg_1=="str" and not arg_0.ALT:
        arg_3 = '.'

    arg_4 = CHR_PATTERN.match(arg_0.CHROM)
    arg_5 = arg_4.group(2)

    arg_6 = arg_0.INFO.get('SVTYPE')
    if arg_6:
        arg_6 = arg_6.lower()

    arg_7 = arg_0.INFO.get('MATEID')

    arg_8 = arg_0.INFO.get('SVLEN')

    arg_9 = arg_0.INFO.get('END')
    arg_10 = int(arg_0.end)

    arg_11 = int(arg_0.POS)

    arg_12 = len(arg_2)
    arg_13 = len(arg_3)

    arg_14 = get_sub_category(arg_13, arg_12, arg_1, arg_6)
    arg_15 = get_end(arg_11, arg_3, arg_1, arg_10, arg_9)

    arg_16 = get_length(arg_13, arg_12, arg_1, arg_11, arg_15, arg_6, arg_8)
    arg_17 = arg_5

    if arg_14 == 'bnd':
        if ':' in arg_3:
            arg_18 = BND_ALT_PATTERN.match(arg_3)
            # BND will often be translocations between different chromosomes
            if arg_18:
                arg_19 = arg_18.group(1)
                arg_18 = CHR_PATTERN.match(arg_19)
                arg_17 = arg_18.group(2)

    arg_20 = get_cytoband_coordinates(arg_5, arg_11)
    arg_21 = get_cytoband_coordinates(arg_17, arg_15)

    arg_22 = {
        'position': arg_11,
        'end': arg_15,
        'length': arg_16,
        'sub_category': arg_14,
        'mate_id': arg_7,
        'cytoband_start': arg_20,
        'cytoband_end': arg_21,
        'end_chrom': arg_17,
    }

    return arg_22


def Func():
    """Show all Func for a case."""
    if request.method == 'POST':
        # update an existing panel
        arg_0 = request.files['csv_file']
        arg_1 = arg_0.stream.read()
        arg_2 = None
        try:
            if b'\n' in arg_1:
                arg_2 = arg_1.decode('utf-8', 'ignore').split('\n')
            else:
                arg_2 = arg_1.decode('windows-1252').split('\r')
        except Exception as err:
            flash('Something went wrong while parsing the panel CSV file! ({})'.format(err), 'danger')
            return redirect(request.referrer)

        arg_3 = request.form.get('new_panel_name')
        if arg_3: #create a new panel
            arg_4 = controllers.new_panel(
                store=store,
                institute_id=request.form['institute'],
                panel_name=arg_3,
                display_name=request.form['display_name'],
                csv_lines=arg_2,
            )
            if arg_4 is None:
                flash('Something went wrong and the panel list was not updated!','warning')
                return redirect(request.referrer)
            else:
                flash("new gene panel added, {}!".format(arg_3),'success')
            return redirect(url_for('Func.panel', panel_id=arg_4))

        else: # modify an existing panel
            arg_5 = request.form['modify_option']
            arg_6= controllers.update_panel(
                                   store=store,
                                   panel_name=request.form['panel_name'],
                                   csv_lines=arg_2,
                                   option=arg_5
             )
            if arg_6 is None:
                return abort(404, "gene panel not found: {}".format(request.form['panel_name']))
            else:
                return redirect(url_for('Func.panel', panel_id=arg_6['_id']))

    arg_7 = list(user_institutes(store, current_user))
    arg_8 = [arg_10
                   for institute in arg_7
                   for arg_10 in
                   store.gene_Func(institute_id=institute['_id']).distinct('panel_name')]

    arg_9 = {}
    for arg_10 in arg_8:
        arg_9[arg_10]=store.gene_Func(panel_id=arg_10)

    arg_11 = []
    for arg_12 in arg_7:
         arg_13 = store.latest_Func(arg_12['_id'])
         arg_11.append((arg_12, arg_13))

    return dict(arg_11=arg_11, arg_8=arg_8,
                arg_9=arg_9, arg_7=arg_7)


def Func(arg_0, arg_1, arg_2,
                    arg_3):
    """Add delivery report to an existing case."""

    arg_4 = arg_0.obj['adapter']

    try:
        load_Func(arg_4=arg_4, arg_1=arg_1,
                             arg_2=arg_2, arg_3=arg_3)
        LOG.info("saved report to case!")
    except Exception as e:
        LOG.error(e)
        arg_0.abort()


def Func(arg_0, arg_1 = None, arg_2 = None):
    """Retrieves a list of HPO terms from scout database

    Args:
        store (obj): an adapter to the scout database
        query (str): the term to search in the database
        limit (str): the number of desired results

    Returns:
        hpo_phenotypes (dict): the complete list of HPO objects stored in scout

    """
    arg_3 = {}
    if arg_2:
        arg_2=int(arg_2)

    arg_3['phenotypes'] = list(arg_0.Func(text=arg_1, arg_2=arg_2))
    return arg_3


def Func(arg_0):
    """Show all objects in the Func collection"""
    LOG.info("Running scout view users")
    arg_1 = arg_0.obj['adapter']

    ## TODO add a User interface to the adapter
    for arg_2 in arg_1.Func_collection.find():
        click.echo(arg_2['_id'])


def Func(arg_0, arg_1):
    """Parse information about a Func."""
    arg_2 = {'builds': {'37': None, '38': None}, 'symbol': None, 'description': None, 'ensembl_id': None, 'record': None}

    for arg_3 in arg_2['builds']:
        arg_4 = arg_0.hgnc_Func(arg_1, arg_3=arg_3)
        if arg_4:

            arg_4['position'] = "{this[chromosome]}:{this[start]}-{this[end]}".format(this=arg_4)
            arg_2['aliases'] = arg_4['aliases']
            arg_2['hgnc_id'] = arg_4['hgnc_id']
            arg_2['description'] = arg_4['description']
            arg_2['builds'][arg_3] = arg_4
            arg_2['symbol'] = arg_4['hgnc_symbol']
            arg_2['description'] = arg_4['description']
            arg_2['entrez_id'] = arg_4.get('entrez_id')
            arg_2['pli_score'] = arg_4.get('pli_score')

            add_Func_links(arg_4, int(arg_3))

            arg_2['omim_id'] = arg_4.get('omim_id')
            arg_2['incomplete_penetrance'] = arg_4.get('incomplete_penetrance',False)
            arg_2['inheritance_models'] = arg_4.get('inheritance_models',[])
            for arg_5 in arg_4['transcripts']:
                arg_5['position'] = ("{this[chrom]}:{this[start]}-{this[end]}"
                                          .format(this=arg_5))
                add_tx_links(arg_5, arg_3)

            for arg_6 in arg_4.get('phenotypes',[]):
                arg_6['omim_link'] = omim(arg_6.get('mim_number'))

            if not arg_2['record']:
                arg_2['record'] = arg_4

    # If none of the Funcs where found
    if not any(arg_2.values()):
        raise ValueError

    return arg_2


def Func(arg_0, arg_1):
    """Fetch matching genes and convert to JSON."""
    arg_2 = arg_0.hgnc_genes(arg_1, search=True)
    arg_3 = [{'name': "{} | {} ({})".format(gene['hgnc_id'], gene['hgnc_symbol'],
                                                 ', '.join(gene['aliases'])),
                   'id': gene['hgnc_id']} for gene in arg_2]
    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3):
    """Show all Func in the database"""
    LOG.info("Running scout view Func")
    arg_4 = arg_0.obj['adapter']

    if not arg_3:
        click.echo("Chromosome\tstart\tend\ttranscript_id\thgnc_id\trefseq\tis_primary")
    for arg_5 in arg_4.Func(arg_1=arg_1, arg_2=arg_2):
        if arg_3:
            pp(arg_5)
            continue
        click.echo("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}".format(
            arg_5['chrom'],
            arg_5['start'],
            arg_5['end'],
            arg_5['ensembl_transcript_id'],
            arg_5['hgnc_id'],
            arg_5.get('refseq_id', ''),
            arg_5.get('is_primary') or '',
        ))


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Returns the events that occur on the given day.
    Works by getting all occurrences for the month, then drilling
    down to only those occurring on the given day.
    """
    # Get a dict with all of the events for the month
    arg_4 = CountHandler(arg_0, arg_1, arg_2).get_count()
    arg_5 = [x[1] for x in arg_4[arg_3]]  # list of pks for events on given day
    # List enables sorting.
    # See the comments in EventMonthView in views.py for more info
    arg_6 = list(Event.objects.filter(pk__in=arg_5).order_by(
        'start_date').prefetch_related('cancellations'))
    arg_6.sort(key=lambda x: x.l_start_date.hour)
    return arg_6


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=1, arg_5=50):
    """Pre-process list of SV variants."""
    arg_6 = (arg_5 * max(arg_4 - 1, 0))
    arg_7 = True if arg_3.count() > (arg_6 + arg_5) else False

    arg_8 = arg_2.get('genome_build', '37')
    if arg_8 not in ['37','38']:
        arg_8 = '37'

    return {
        'variants': (parse_variant(arg_0, arg_1, arg_2, arg_9, arg_8=arg_8) for arg_9 in
                     arg_3.skip(arg_6).limit(arg_5)),
        'more_variants': arg_7,
    }


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=1, arg_5=50):
    """Pre-process list of STR variants."""
    # Nothing unique to STRs on this level. Inheritance?
    return variants(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5)


def Func(arg_0):
    """Returns a header for the CSV file with the filtered variants to be exported.

        Args:
            case_obj(scout.models.Case)

        Returns:
            header: includes the fields defined in scout.constants.variants_export EXPORT_HEADER
                    + AD_reference, AD_alternate, GT_quality for each sample analysed for a case
    """
    arg_1 = []
    arg_1 = arg_1 + EXPORT_HEADER
    # Add fields specific for case samples
    for arg_2 in arg_0['individuals']:
        arg_3 = str(arg_2['display_name'])
        arg_1.append('AD_reference_'+arg_3) # Add AD reference field for a sample
        arg_1.append('AD_alternate_'+arg_3) # Add AD alternate field for a sample
        arg_1.append('GT_quality_'+arg_3) # Add Genotype quality field for a sample
    return arg_1


def Func(arg_0):
    """Get variant information"""
    arg_1 = {'canonical_transcripts': []}
    for arg_2 in arg_0:
        if not arg_2.get('canonical_transcripts'):
            arg_3 = arg_2['transcripts'][0]
            arg_4 = arg_3['transcript_id']
            arg_5 = arg_3.get('exon', '-')
            arg_6 = arg_3.get('coding_sequence_name', '-')
        else:
            arg_4 = arg_2['canonical_transcripts']
            arg_5 = arg_2.get('exon', '-')
            arg_6 = arg_2.get('hgvs_identifier', '-')

        if len(arg_6) > 20:
            arg_6 = arg_6[:20] + '...'

        if len(arg_0) == 1:
            arg_7 = ':'.join([arg_4,arg_5,arg_6])
        else:
            arg_8 = arg_2.get('hgnc_symbol') or str(arg_2['hgnc_id'])
            arg_7 = ':'.join([arg_8, arg_4,arg_5,arg_6])
        arg_1['canonical_transcripts'].append(arg_7)

    return arg_1


def Func(arg_0):
    """Get sift predictions from genes."""
    arg_1 = {
        'sift_predictions': [],
        'polyphen_predictions': [],
        'region_annotations': [],
        'functional_annotations': []
    }
    for arg_2 in arg_0:
        for arg_3 in arg_1:
            arg_4 = arg_3[:-1]
            if len(arg_0) == 1:
                arg_5 = arg_2.get(arg_4, '-')
            else:
                arg_6 = arg_2.get('hgnc_symbol') or str(arg_2['hgnc_id'])
                arg_5 = ':'.join([arg_6, arg_2.get(arg_4, '-')])
            arg_1[arg_3].append(arg_5)

    return arg_1


def Func(arg_0, arg_1, arg_2):
    """Pre-process case for the variant view.

    Adds information about files from case obj to variant

    Args:
        store(scout.adapter.MongoAdapter)
        case_obj(scout.models.Case)
        variant_obj(scout.models.Variant)
    """
    arg_1['bam_files'] = []
    arg_1['mt_bams'] = []
    arg_1['bai_files'] = []
    arg_1['mt_bais'] = []
    arg_1['sample_names'] = []
    for arg_3 in arg_1['individuals']:
        arg_4 = arg_3.get('bam_file')
        arg_5 = arg_3.get('mt_bam')
        arg_1['sample_names'].append(arg_3.get('display_name'))
        if arg_4 and os.path.exists(arg_4):
            arg_1['bam_files'].append(arg_3['bam_file'])
            arg_1['bai_files'].append(find_bai_file(arg_3['bam_file']))
        if arg_5 and os.path.exists(arg_5):
            arg_1['mt_bams'].append(arg_3['mt_bam'])
            arg_1['mt_bais'].append(find_bai_file(arg_3['mt_bam']))

        else:
            LOG.debug("%s: no bam file found", arg_3['individual_id'])

    try:
        arg_6 = arg_2.get('genes', [])
        if len(arg_6) == 1:
            arg_7 = arg_0.hgnc_gene(arg_2['genes'][0]['hgnc_id'])
            if arg_7:
                arg_8 = arg_0.get_region_vcf(arg_1, gene_obj=arg_7)
                arg_1['region_vcf_file'] = arg_8
            else:
                arg_1['region_vcf_file'] = None
        elif len(arg_6) > 1:
            arg_9 = arg_2['genes'][0]['common']['chromosome']
            arg_10 = min(gene['common']['start'] for gene in arg_2['genes'])
            arg_11 = max(gene['common']['end'] for gene in arg_2['genes'])
            # Create a reduced VCF with variants in the region
            arg_8 = arg_0.get_region_vcf(arg_1, arg_9=arg_9, arg_10=arg_10, arg_11=arg_11)
            arg_1['region_vcf_file'] = arg_8
    except (SyntaxError, Exception):
        LOG.warning("skip VCF region for alignment view")


def Func(arg_0, arg_1, arg_2, arg_3):
    """Query Func for a variant."""
    arg_4 = ("{this[chromosome]}_{this[position]}_{this[reference]}_"
                    "{this[alternative]}".format(this=arg_3))
    arg_5 = arg_1.get_variant({'_id': arg_4}) or {}
    arg_5['total'] = arg_1.case_count()

    arg_5['cases'] = []
    arg_6 = arg_3['institute']
    for arg_7 in arg_5.get('families', []):
        if arg_7 != arg_3['case_id'] and arg_7.startswith(arg_6):
            arg_8 = arg_0.variant(arg_3['variant_id'], arg_7=arg_7)
            arg_9 = arg_0.case(arg_7)
            arg_5['cases'].append(dict(case=arg_9, variant=arg_8))

    return arg_5


def Func(arg_0, arg_1=None):
    """Parse variant genes."""
    arg_1 = arg_1 or 37

    if arg_0.get('common'):
        add_gene_links(arg_0, arg_1)
        arg_2 = []
        for arg_3 in arg_0['transcripts']:
            parse_transcript(arg_0, arg_3, arg_1)

            # select refseq transcripts as "primary"
            if not arg_3.get('refseq_id'):
                continue

            arg_2.append(arg_3)

        arg_0['primary_transcripts'] = (arg_2 if arg_2 else [])


def Func(arg_0, arg_1=None):
    """Generate amino acid change as a string."""
    if arg_0.get('exon'):
        arg_2, arg_3 = 'exon', arg_0['exon']
    elif arg_0.get('intron'):
        arg_2, arg_3 = 'intron', arg_0['intron']
    else:
        # variant between genes
        arg_2, arg_3 = 'intergenic', '0'

    arg_4 = arg_3.rpartition('/')[0]
    arg_5 = "{}:{}{}:{}:{}".format(
        arg_0.get('refseq_id', ''),
        arg_2,
        arg_4,
        arg_0.get('coding_sequence_name', 'NA'),
        arg_0.get('protein_sequence_name', 'NA'),
    )
    if arg_1:
        arg_5 = "{}:".format(arg_1) + arg_5
    return arg_5


def Func(arg_0):
    """Calculate end position for a variant."""
    arg_1 = len(arg_0['alternative'])
    arg_2 = max(len(arg_0['reference']), arg_1)
    return arg_0['position'] + (arg_2 - 1)


def Func(arg_0):
    """Returns a judgement on the overall Func of the variant.

    Combines multiple metrics into a single call.
    """
    arg_1 = max(arg_0.get('thousand_genomes_Func') or 0,
                                arg_0.get('exac_Func') or 0)
    if arg_1 > .05:
        return 'common'
    elif arg_1 > .01:
        return 'uncommon'
    else:
        return 'rare'


def Func(arg_0):
    """Compose link to COSMIC Database.

    Args:
        variant_obj(scout.models.Variant)

    Returns:
        url_template(str): Link to COSMIIC database if cosmic id is present
    """

    arg_1 = arg_0.get('cosmic_ids')

    if not arg_1:
        return None
    else:
        arg_2 = arg_1[0]
        arg_3 = ("https://cancer.sanger.ac.uk/cosmic/mutation/overview?id={}")

    return arg_3.format(arg_2)


def Func(arg_0, arg_1=None):
    """Compose link to Beacon Network."""
    arg_1 = arg_1 or 37
    arg_2 = ("https://beacon-network.org/#/search?pos={this[position]}&"
                    "chrom={this[chromosome]}&allele={this[alternative]}&"
                    "ref={this[reference]}&rs=GRCh37")
    # beacon does not support build 38 at the moment
    # if build == '38':
    #     url_template = ("https://beacon-network.org/#/search?pos={this[position]}&"
    #                     "chrom={this[chromosome]}&allele={this[alternative]}&"
    #                     "ref={this[reference]}&rs=GRCh38")

    return arg_2.format(this=arg_0)


def Func(arg_0, arg_1=None):
    """Compose link to UCSC."""
    arg_1 = arg_1 or 37
    arg_2 = ("http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg19&"
                        "position=chr{this[chromosome]}:{this[position]}"
                        "-{this[position]}&dgv=pack&knownGene=pack&omimGene=pack")
    if arg_1 == 38:
        arg_2 = ("http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg20&"
                        "position=chr{this[chromosome]}:{this[position]}"
                        "-{this[position]}&dgv=pack&knownGene=pack&omimGene=pack")

    return arg_2.format(this=arg_0)


def Func(arg_0):
    """Translate SPIDEX annotation to human readable string."""
    if arg_0.get('spidex') is None:
        return 'not_reported'
    elif abs(arg_0['spidex']) < SPIDEX_HUMAN['low']['pos'][1]:
        return 'low'
    elif abs(arg_0['spidex']) < SPIDEX_HUMAN['medium']['pos'][1]:
        return 'medium'
    else:
        return 'high'


def Func(arg_0, arg_1, arg_2, arg_3):
    """Fetch data related to cancer variants for a case."""
    arg_4, arg_5 = institute_and_case(arg_0, arg_2, arg_3)
    arg_6 = CancerFiltersForm(arg_1)
    arg_7 = arg_0.variants(arg_5['_id'], category='cancer', query=arg_6.data).limit(50)
    arg_8 = dict(
        institute=arg_4,
        case=arg_5,
        variants=(parse_variant(arg_0, arg_4, arg_5, variant, update=True) for
                  variant in arg_7),
        arg_6=arg_6,
        variant_type=arg_1.get('variant_type', 'clinical'),
    )
    return arg_8


def Func(arg_0, arg_1, arg_2, arg_3):
    """Gather the required data for creating the clinvar submission form

        Args:
            store(scout.adapter.MongoAdapter)
            institute_id(str): Institute ID
            case_name(str): case ID
            variant_id(str): variant._id

        Returns:
            a dictionary with all the required data (case and variant level) to pre-fill in fields in the clinvar submission form

    """

    arg_4, arg_5 = institute_and_case(arg_0, arg_1, arg_2)
    arg_6 = [arg_0.variant(arg_3) or arg_3 for arg_3 in
                  arg_5.get('suspects', [])]
    arg_7 = arg_0.variant(arg_3)
    return dict(
        today = str(date.today()),
        institute=arg_4,
        case=arg_5,
        variant=arg_7,
        pinned_vars=arg_6
    )


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Collects all variants from the clinvar submission collection with a specific submission_id

        Args:
            store(scout.adapter.MongoAdapter)
            institute_id(str): Institute ID
            case_name(str): case ID
            variant_id(str): variant._id
            submission_id(str): clinvar submission id, i.e. SUB76578

        Returns:
            A dictionary with all the data to display the clinvar_update.html template page
    """

    arg_5, arg_6 = institute_and_case(arg_0, arg_1, arg_2)
    arg_7 = [arg_0.variant(arg_3) or arg_3 for arg_3 in
                  arg_6.get('suspects', [])]
    arg_8 = arg_0.variant(arg_3)
    arg_9 = arg_0.clinvars(arg_4=arg_4)
    return dict(
        today = str(date.today()),
        institute=arg_5,
        case=arg_6,
        variant=arg_8,
        pinned_vars=arg_7,
        clinvars = arg_9
    )


def Func(arg_0, arg_1, arg_2, arg_3):
    """Collect data relevant for rendering ACMG classification form."""
    arg_4, arg_5 = institute_and_case(arg_0, arg_1, arg_2)
    arg_6 = arg_0.variant(arg_3)
    return dict(institute=arg_4, case=arg_5, variant=arg_6,
                CRITERIA=ACMG_CRITERIA, ACMG_OPTIONS=ACMG_OPTIONS)


def Func(arg_0, arg_1):
    """Fetch and fill-in Func object."""
    arg_1['institute'] = arg_0.institute(arg_1['institute_id'])
    arg_1['case'] = arg_0.case(arg_1['case_id'])
    arg_1['variant'] = arg_0.variant(arg_1['variant_specific'])
    arg_1['criteria'] = {criterion['term']: criterion for criterion in
                                  arg_1['criteria']}
    arg_1['classification'] = ACMG_COMPLETE_MAP[arg_1['classification']]
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
    """Parse out HGNC symbols from a stream."""
    arg_4, arg_5 = institute_and_case(arg_0, arg_1, arg_2)
    arg_6 = [line.strip().split('\t')[0] for line in arg_3 if
                   line and not line.startswith('#')]
    # check if supplied gene symbols exist
    arg_7 = []
    for arg_8 in arg_6:
        if arg_0.hgnc_genes(arg_8).count() == 0:
            flash("HGNC symbol not found: {}".format(arg_8), 'warning')
        else:
            arg_7.append(arg_8)
    return arg_7


def Func(arg_0, arg_1, arg_2, arg_3):
    """Get the clnsig information

    Args:
        acc(str): The clnsig accession number, raw from vcf
        sig(str): The clnsig significance score, raw from vcf
        revstat(str): The clnsig revstat, raw from vcf
        transcripts(iterable(dict))

    Returns:
        clnsig_accsessions(list): A list with clnsig accessions
    """
    arg_4 = []

    if arg_0:
    # New format of clinvar allways have integers as accession numbers
        try:
            arg_0 = int(arg_0)
        except ValueError:
            pass
        # There are sometimes different separators so we need to check which
        # one to use
        if isinstance(arg_0, int):
            arg_5 = []
            if arg_2:
                arg_5 = [rev.lstrip('_') for rev in arg_2.split(',')]

            arg_6 = []
            if arg_1:
                for arg_7 in arg_1.split('/'):
                    arg_8 = arg_7.split('_')
                    arg_6.append(' '.join(arg_8[:2]))

            for arg_9 in arg_6:
                arg_4.append({
                    'value': arg_9,
                    'accession': int(arg_0),
                    'revstat': ', '.join(arg_5),
                })
        else:
            # There are sometimes different separators so we need to check which
            # one to use
            arg_10 = arg_0.split('|')
            arg_6 = arg_1.split('|')
            arg_5 = arg_2.split('|')
            for arg_11, arg_12, arg_13 in zip(arg_10, arg_6, arg_5):
                arg_14 = arg_11.split(',')
                arg_15 = arg_12.split(',')
                arg_16 = arg_13.split(',')
                for arg_17, arg_7, arg_2 in zip(arg_14, arg_15, arg_16):
                    arg_4.append({
                        'value': int(arg_7),
                        'accession': arg_17,
                        'revstat': arg_2,
                    })

    elif arg_3:
        arg_18 = set()
        for arg_19 in arg_3:
            for arg_20 in arg_19.get('clinsig', []):
                arg_18.add(arg_20)
        for arg_20 in arg_18:
            arg_4.append({'value': arg_20})

    return arg_4


def Func(arg_0, arg_1, arg_2):
    """Get a list with compounds objects for this variant.

        Arguments:
            compound_info(str): A Variant dictionary
            case_id (str): unique family id
            variant_type(str): 'research' or 'clinical'

        Returns:
            compounds(list(dict)): A list of compounds
    """
    # We need the case to construct the correct id
    arg_3 = []
    if arg_0:
        for arg_4 in arg_0.split(','):
            arg_5 = arg_4.split(':')
            # This is the family id
            if arg_5[0] == arg_1:
                for arg_6 in arg_5[1].split('|'):
                    arg_7 = arg_6.split('>')
                    arg_8 = {}
                    arg_9 = arg_7[0]
                    arg_8['variant'] = generate_md5_key(arg_9.split('_') +
                                                               [arg_2, arg_1])

                    try:
                        arg_10 = float(arg_7[1])
                    except (TypeError, IndexError):
                        arg_10 = 0.0

                    arg_8['score'] = arg_10
                    arg_8['display_name'] = arg_9

                    arg_3.append(arg_8)

    return arg_3


def Func(arg_0):
    """Build a Individual object

        Args:
            ind (dict): A dictionary with individual information

        Returns:
            ind_obj (dict): A Individual object

        dict(
            individual_id = str, # required
            display_name = str,
            sex = str,
            phenotype = int,
            father = str, # Individual id of father
            mother = str, # Individual id of mother
            capture_kits = list, # List of names of capture kits
            bam_file = str, # Path to bam file
            vcf2cytosure = str, # Path to CGH file
            analysis_type = str, # choices=ANALYSIS_TYPES
        )

    """

    try:
        arg_1 = dict(
            individual_id=arg_0['individual_id']
        )
        log.info("Building Individual with id:{0}".format(arg_0['individual_id']))
    except KeyError as err:
        raise PedigreeError("Individual is missing individual_id")

    arg_1['display_name'] = arg_0.get('display_name', arg_1['individual_id'])

    arg_2 = arg_0.get('sex', 'unknown')
    # Convert sex to .ped
    try:
        # Check if sex is coded as an integer
        int(arg_2)
        arg_1['sex'] = str(arg_2)
    except ValueError as err:
        try:
            # Sex are numbers in the database
            arg_1['sex'] = REV_SEX_MAP[arg_2]
        except KeyError as err:
            raise(PedigreeError("Unknown sex: %s" % arg_2))

    arg_3 = arg_0.get('phenotype', 'unknown')
    # Make the phenotype integers
    try:
        arg_4 = REV_PHENOTYPE_MAP[arg_3]
        if arg_4 == -9:
            arg_4 = 0
        arg_1['phenotype'] = arg_4
    except KeyError as err:
        raise(PedigreeError("Unknown phenotype: %s" % arg_3))

    arg_1['father'] = arg_0.get('father')
    arg_1['mother'] = arg_0.get('mother')
    arg_1['capture_kits'] = arg_0.get('capture_kits', [])
    arg_1['bam_file'] = arg_0.get('bam_file')
    arg_1['mt_bam'] = arg_0.get('mt_bam')
    arg_1['vcf2cytosure'] = arg_0.get('vcf2cytosure')
    arg_1['confirmed_sex'] = arg_0.get('confirmed_sex')
    arg_1['confirmed_parent'] = arg_0.get('confirmed_parent')
    arg_1['predicted_ancestry'] = arg_0.get('predicted_ancestry')

    # Check if the analysis type is ok
    # Can be anyone of ('wgs', 'wes', 'mixed', 'unknown')
    arg_5 = arg_0.get('analysis_type', 'unknown')
    if not arg_5 in ANALYSIS_TYPES:
        raise PedigreeError("Analysis type %s not allowed", arg_5)
    arg_1['analysis_type'] = arg_5

    if 'tmb' in arg_0:
        arg_1['tmb'] = arg_0['tmb']

    if 'msi' in arg_0:
        arg_1['msi'] = arg_0['msi']

    if 'tumor_purity' in arg_0:
        arg_1['tumor_purity'] = arg_0['tumor_purity']

    if 'tumor_type' in arg_0:
        arg_1['tumor_type'] = arg_0['tumor_type']

    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6,
             arg_7, arg_8, arg_9, arg_10, arg_11, arg_12, arg_13, arg_14,
             arg_15, arg_16):
    """Upload Func to a case

        Note that the files has to be linked with the case,
        if they are not use 'scout update case'.
    """
    LOG.info("Running scout load Func")
    arg_17 = arg_0.obj['adapter']

    if arg_2:
        arg_1 = "{0}-{1}".format(arg_2, arg_1)
    else:
        arg_2 = arg_1.split('-')[0]
    arg_18 = arg_17.case(arg_1=arg_1)
    if arg_18 is None:
        LOG.info("No matching case found")
        arg_0.abort()

    arg_19 = [
        {'category': 'cancer', 'variant_type': 'clinical', 'upload': arg_4},
        {'category': 'cancer', 'variant_type': 'research', 'upload': arg_5},
        {'category': 'sv', 'variant_type': 'clinical', 'upload': arg_6},
        {'category': 'sv', 'variant_type': 'research', 'upload': arg_7},
        {'category': 'snv', 'variant_type': 'clinical', 'upload': arg_8},
        {'category': 'snv', 'variant_type': 'research', 'upload': arg_9},
        {'category': 'str', 'variant_type': 'clinical', 'upload': arg_10},
    ]

    arg_20 = None
    if (arg_14 or arg_15):
        if arg_14:
            arg_20 = arg_17.hgnc_gene(arg_14)
        if arg_15:
            for arg_21 in arg_17.gene_by_alias(arg_15):
                arg_20 = arg_21
        if not arg_20:
            LOG.warning("The gene could not be found")
            arg_0.abort()

    arg_22 = 0
    for arg_23 in arg_19:
        arg_24 = arg_23['variant_type']
        arg_25 = arg_23['category']

        if arg_23['upload']:
            arg_22 += 1
            if arg_24 == 'research':
                if not (arg_3 or arg_18['research_requested']):
                    LOG.warn("research not requested, use '--force'")
                    arg_0.abort()

            LOG.info("Delete {0} {1} Func for case {2}".format(
                         arg_24, arg_25, arg_1))
            arg_17.delete_Func(arg_1=arg_18['_id'],
                                    arg_24=arg_24,
                                    arg_25=arg_25)

            LOG.info("Load {0} {1} Func for case {2}".format(
                         arg_24, arg_25, arg_1))

            try:
                arg_17.load_Func(
                    arg_18=arg_18,
                    arg_24=arg_24,
                    arg_25=arg_25,
                    rank_threshold=arg_16,
                    arg_11=arg_11,
                    arg_12=arg_12,
                    arg_13=arg_13,
                    arg_20=arg_20
                )
            except Exception as e:
                LOG.warning(e)
                arg_0.abort()
    if arg_22 == 0:
        LOG.info("No files where specified to upload Func from")


def Func(arg_0, arg_1):
    """Return a variant."""
    arg_2, arg_3 = institute_and_Func(store, arg_0, arg_1)
    if arg_3 is None:
        return abort(404)
    return Response(json_util.dumps(arg_3), mimetype='application/json')


def Func(arg_0):
    """Return a opened file"""

    if arg_0.endswith('.gz'):
        arg_1 = getreader('utf-8')(gzip.open(arg_0, 'r'), errors='replace')
    else:
        arg_1 = open(arg_0, 'r', encoding='utf-8')

    return arg_1


def Func(arg_0):
    """Get the net of any 'next' and 'prev' querystrings."""
    try:
        arg_1, arg_2 = map(
            int, (arg_0.GET.get('cal_next', 0), arg_0.GET.get('cal_prev', 0))
        )
        arg_3 = arg_1 - arg_2
    except Exception:
        arg_3 = 0
    return arg_3


def Func(arg_0):
    """Returns what the next and prev querystrings should be."""
    if arg_0 == 0:
        arg_1 = arg_2 = 1
    elif arg_0 > 0:
        arg_1 = arg_0 + 1
        arg_2 = -(arg_0 - 1)
    else:
        arg_1 = arg_0 + 1
        arg_2 = abs(arg_0) + 1
    return arg_1, arg_2


def Func(arg_0, arg_1, arg_2, arg_3=False):
    """
    Make sure any event day we send back for weekday repeating
    events is not a weekend.
    """
    arg_4 = date(arg_0, arg_1, arg_2)
    while arg_4.weekday() in (5, 6):
        if arg_3:
            arg_4 -= timedelta(days=1)
        else:
            arg_4 += timedelta(days=1)
    return arg_4.year, arg_4.month, arg_4.day


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None,
                    arg_4=None, arg_5=None, arg_6=None, arg_7=None,
                    arg_8=None, arg_9=None, arg_10=None, arg_11=None):
    """Parse all data necessary for loading a case into scout

    This can be done either by providing a VCF file and other information
    on the command line. Or all the information can be specified in a config file.
    Please see Scout documentation for further instructions.

    Args:
        config(dict): A yaml formatted config file
        ped(iterable(str)): A ped formatted family file
        owner(str): The institute that owns a case
        vcf_snv(str): Path to a vcf file
        vcf_str(str): Path to a VCF file
        vcf_sv(str): Path to a vcf file
        vcf_cancer(str): Path to a vcf file
        peddy_ped(str): Path to a peddy ped
        multiqc(str): Path to dir with multiqc information

    Returns:
        config_data(dict): Holds all the necessary information for loading
                           Scout
    """
    arg_12 = copy.deepcopy(arg_0) or {}
    # Default the analysis date to now if not specified in load config
    if 'analysis_date' not in arg_12:
        arg_12['analysis_date'] = datetime.datetime.now()

    # If the family information is in a ped file we nned to parse that
    if arg_1:
        arg_13, arg_14 = parse_ped(arg_1)
        arg_12['family'] = arg_13
        arg_12['samples'] = arg_14

    # Each case has to have a owner. If not provided in config file it needs to be given as a
    # argument
    if 'owner' not in arg_12:
        if not arg_2:
            raise SyntaxError("Case has no owner")
        else:
            arg_12['owner'] = arg_2

    if 'gene_panels' in arg_12:
        # handle whitespace in gene panel names
        arg_12['gene_panels'] = [panel.strip() for panel in
                                      arg_12['gene_panels']]
        arg_12['default_gene_panels'] = [panel.strip() for panel in
                                              arg_12['default_gene_panels']]

    ##################### Add information from peddy if existing #####################
    arg_12['peddy_ped'] = arg_7 or arg_12.get('peddy_ped')
    arg_12['peddy_sex_check'] = arg_8 or arg_12.get('peddy_sex')
    arg_12['peddy_ped_check'] = arg_9 or arg_12.get('peddy_check')

    # This will add information from peddy to the individuals
    add_peddy_information(arg_12)

    ##################### Add multiqc information #####################
    arg_12['multiqc'] = arg_11 or arg_12.get('multiqc')

    arg_12['vcf_snv'] = arg_3 if arg_3 else arg_12.get('vcf_snv')
    arg_12['vcf_sv'] = arg_4 if arg_4 else arg_12.get('vcf_sv')
    arg_12['vcf_str'] = arg_6 if arg_6 else arg_12.get('vcf_str')
    log.debug("Config vcf_str set to {0}".format(arg_12['vcf_str']))

    arg_12['vcf_cancer'] = arg_5 if arg_5 else arg_12.get('vcf_cancer')

    arg_12['delivery_report'] = arg_10 if arg_10 else arg_12.get('delivery_report')

    arg_12['rank_model_version'] = arg_12.get('rank_model_version')
    arg_12['rank_score_threshold'] = arg_12.get('rank_score_threshold', 0)

    arg_12['track'] = arg_12.get('track', 'rare')
    if arg_12['vcf_cancer']:
        arg_12['track'] = 'cancer'

    return arg_12


def Func(arg_0):
    """Add information from peddy outfiles to the individuals"""
    arg_1 = {}
    arg_2 = {}
    arg_3 = {}
    arg_4 = []

    if arg_0.get('peddy_ped'):
        arg_5 = open(arg_0['peddy_ped'], 'r')
        for arg_6 in parse_peddy_ped(arg_5):
            arg_1[arg_6['sample_id']] = arg_6

    if arg_0.get('peddy_ped_check'):
        arg_5 = open(arg_0['peddy_ped_check'], 'r')
        for arg_7 in parse_peddy_ped_check(arg_5):
            arg_2[(arg_7['sample_a'], arg_7['sample_b'])] = arg_7

    if arg_0.get('peddy_sex_check'):
        arg_5 = open(arg_0['peddy_sex_check'], 'r')
        for arg_6 in parse_peddy_sex_check(arg_5):
            arg_3[arg_6['sample_id']] = arg_6

    if not arg_1:
        return

    arg_8 = {}
    for arg_9 in arg_0['samples']:
        arg_10 = arg_9['sample_id']
        arg_8[arg_10] = arg_9

    for arg_10 in arg_8:
        arg_9 = arg_8[arg_10]
        # Check if peddy has inferred the ancestry
        if arg_10 in arg_1:
            arg_9['predicted_ancestry'] = arg_1[arg_10].get('ancestry-prediction', 'UNKNOWN')
        # Check if peddy has inferred the sex
        if arg_10 in arg_3:
            if arg_3[arg_10]['error']:
                arg_9['confirmed_sex'] = False
            else:
                arg_9['confirmed_sex'] = True

        # Check if peddy har confirmed parental relations
        for arg_11 in ['mother', 'father']:
            # If we are looking at individual with parents
            if arg_9[arg_11] != '0':
                # Check if the child/parent pair is in peddy data
                for arg_12 in arg_2:
                    if (arg_10 in arg_12 and arg_9[arg_11] in arg_12):
                        # If there is a parent error we mark that
                        if arg_2[arg_12]['parent_error']:
                            arg_8[arg_9[arg_11]]['confirmed_parent'] = False
                        else:
                            # Else if parent confirmation has not been done
                            if 'confirmed_parent' not in arg_8[arg_9[arg_11]]:
                                # Set confirmatio to True
                                arg_8[arg_9[arg_11]]['confirmed_parent'] = True


def Func(arg_0):
    """Parse the individual information

        Reformat sample information to proper individuals

        Args:
            samples(list(dict))

        Returns:
            individuals(list(dict))
    """
    arg_1 = []
    if len(arg_0) == 0:
        raise PedigreeError("No samples could be found")

    arg_2 = set()
    for arg_3 in arg_0:
        arg_4 = parse_individual(arg_3)
        arg_1.append(arg_4)
        arg_2.add(arg_4['individual_id'])

    # Check if relations are correct
    for arg_4 in arg_1:
        arg_5 = arg_4['father']
        if (arg_5 and arg_5 != '0'):
            if arg_5 not in arg_2:
                raise PedigreeError('father %s does not exist in family' % arg_5)
        arg_6 = arg_4['mother']
        if (arg_6 and arg_6 != '0'):
            if arg_6 not in arg_2:
                raise PedigreeError('mother %s does not exist in family' % arg_6)

    return arg_1


def Func(arg_0, arg_1='ped'):
    """Parse out minimal family information from a PED file.

    Args:
        ped_stream(iterable(str))
        family_type(str): Format of the pedigree information

    Returns:
        family_id(str), samples(list[dict])
    """
    arg_2 = FamilyParser(arg_0, arg_1=arg_1)

    if len(arg_2.families) != 1:
        raise PedigreeError("Only one case per ped file is allowed")

    arg_3 = list(arg_2.families.keys())[0]
    arg_4 = arg_2.families[arg_3]

    arg_5 = [{
        'sample_id': ind_id,
        'father': individual.father,
        'mother': individual.mother,
        # Convert sex to human readable
        'sex': SEX_MAP[individual.sex],
        'phenotype': PHENOTYPE_MAP[int(individual.phenotype)],
    } for ind_id, individual in arg_4.individuals.items()]

    return arg_3, arg_5


def Func(arg_0, arg_1, arg_2, arg_3,
                     arg_4, arg_5, arg_6, arg_7):
    """Build a evaluation object ready to be inserted to database

    Args:
        variant_specific(str): md5 string for the specific variant
        variant_id(str): md5 string for the common variant
        user_id(str)
        user_name(str)
        institute_id(str)
        case_id(str)
        classification(str): The ACMG classification
        criteria(list(dict)): A list of dictionaries with ACMG criterias

    Returns:
        evaluation_obj(dict): Correctly formatted evaluation object

    """
    arg_7 = arg_7 or []
    arg_8 = dict(
        arg_0 = arg_0,
        arg_1 = arg_1,
        arg_4 = arg_4,
        arg_5 = arg_5,
        arg_6 = arg_6,
        arg_2 = arg_2,
        arg_3 = arg_3,
        created_at = datetime.datetime.now(),
    )
    arg_9 = []
    for arg_10 in arg_7:
        arg_11 = {}
        # This allways has to exist
        # We might want to check if the term is valid here...
        arg_11['term'] = arg_10['term']
        if 'comment' in arg_10:
            arg_11['comment'] = arg_10['comment']
        if 'links' in arg_10:
            arg_11['links'] = arg_10['links']
        arg_9.append(arg_11)

    arg_8['criteria'] = arg_9

    return arg_8


def Func(arg_0, arg_1, arg_2, arg_3=None):
    """Export all mitochondrial variants for each sample of a case
       and write them to an excel file

        Args:
            adapter(MongoAdapter)
            case_id(str)
            test(bool): True if the function is called for testing purposes
            outpath(str): path to output file

        Returns:
            written_files(int): number of written or simulated files
    """
    LOG.info('exporting mitochondrial variants for case "{}"'.format(arg_1))

    arg_4 = arg_0.obj['adapter']
    arg_5 = {'chrom':'MT'}

    arg_6 = arg_4.case(arg_1=arg_1)

    if not arg_6:
        LOG.warning('Could not find a scout case with id "{}". No report was created.'.format(arg_1))
        arg_0.abort()

    arg_7 = arg_6.get('individuals')
    arg_8 = list(arg_4.variants(arg_1=arg_1, arg_5=arg_5, nr_of_variants= -1, sort_key='position'))
    if not arg_8:
        LOG.warning('There are no MT variants associated to case {} in database!'.format(arg_1))
        arg_0.abort()

    arg_9 = datetime.datetime.now().strftime('%Y-%m-%d')

    # set up outfolder
    if not arg_3:
        arg_3 = str(os.getcwd())

    # get document lines for each of the cases's individuals
    # Write excel document for each sample in case
    arg_10 = 0

    for arg_11 in arg_7:
        arg_12 = arg_11['individual_id']
        arg_13 = export_mt_variants(variants=arg_8, arg_12=arg_12)

        # set up document name
        arg_14 = '.'.join([arg_6['display_name'], arg_12, arg_9]) + '.xlsx'
        arg_15 = Workbook(os.path.join(arg_3,arg_14))
        arg_16 = arg_15.add_worksheet()

        if arg_2 and arg_13 and arg_15:
            arg_10 +=1
            continue

        # Write the column header
        arg_17 = 0
        for arg_18,arg_19 in enumerate(MT_EXPORT_HEADER):
            arg_16.write(arg_17,arg_18,arg_19)

        # Write variant lines, after header (start at line 1)
        for arg_17, arg_20 in enumerate(arg_13,1): # each line becomes a row in the document
            for arg_18, arg_19 in enumerate(arg_20): # each field in line becomes a cell
                arg_16.write(arg_17,arg_18,arg_19)
        arg_15.close()

        if os.path.exists(os.path.join(arg_3,arg_14)):
            arg_10 += 1

    if arg_2:
        LOG.info("Number of excel files that can be written to folder {0}: {1}".format(arg_3, arg_10))
    else:
        LOG.info("Number of excel files written to folder {0}: {1}".format(arg_3, arg_10))
    return arg_10


def Func(arg_0, arg_1):
    """Check if criterias for Likely Benign are fullfilled

    The following are descriptions of Likely Benign clasification from ACMG paper:

    Likely Benign
      (i) 1 Strong (BS1–BS4) and 1 supporting (BP1– BP7) OR
      (ii) ≥2 Supporting (BP1–BP7)

    Args:
        bs_terms(list(str)): Terms that indicate strong evidence for benign variant
        bp_terms(list(str)): Terms that indicate supporting evidence for benign variant

    Returns:
        bool: if classification indicates Benign level
    """
    if arg_0:
        # Likely Benign (i)
        if arg_1:
            return True
    # Likely Benign (ii)
    if len(arg_1) >= 2:
        return True

    return False


def Func(arg_0, arg_1, arg_2=None):
        """Add extra information about genes from gene panels

        Args:
            variant_obj(dict): A variant from the database
            gene_panels(list(dict)): List of panels from database
        """
        arg_2 = arg_2 or []

        # Add a variable that checks if there are any refseq transcripts
        arg_1['has_refseq'] = False

        # We need to check if there are any additional information in the gene panels

        # extra_info will hold information from gene panels
        # Collect all extra info from the panels in a dictionary with hgnc_id as keys
        arg_3 = {}
        for arg_4 in arg_2:
            for arg_5 in arg_4['genes']:
                arg_6 = arg_5['hgnc_id']
                if arg_6 not in arg_3:
                    arg_3[arg_6] = []

                arg_3[arg_6].append(arg_5)

        # Loop over the genes in the variant object to add information
        # from hgnc_genes and panel genes to the variant object
        for arg_7 in arg_1.get('genes', []):
            arg_6 = arg_7['hgnc_id']
            # Get the hgnc_gene
            arg_8 = arg_0.hgnc_gene(arg_6)

            if not arg_8:
                continue

            # Create a dictionary with transcripts information
            # Use ensembl transcript id as keys
            arg_9 = {}
            # Add transcript information from the hgnc gene
            for arg_10 in arg_8.get('transcripts', []):
                arg_11 = arg_10['ensembl_transcript_id']
                arg_9[arg_11] = arg_10

            # Add the transcripts to the gene object
            arg_8['transcripts_dict'] = arg_9

            if arg_8.get('incomplete_penetrance'):
                arg_7['omim_penetrance'] = True

            ############# PANEL SPECIFIC INFORMATION #############
            # Panels can have extra information about genes and transcripts
            arg_12 = arg_3.get(arg_6, [])

            # Manually annotated disease associated transcripts
            arg_13 = set()
            # We need to strip the version to compare against others
            arg_14 = set()
            arg_15 = False
            arg_16 = False
            arg_17 = set()

            # We need to loop since there can be information from multiple panels
            for arg_5 in arg_12:
                # Check if there are manually annotated disease transcripts
                for arg_18 in arg_5.get('disease_associated_transcripts', []):
                    # We remove the version of transcript at this stage
                    arg_19 = re.sub(r'\.[0-9]', '', arg_18)
                    arg_14.add(arg_19)
                    arg_13.add(arg_18)

                if arg_5.get('reduced_penetrance'):
                    arg_15 = True

                if arg_5.get('mosaicism'):
                    arg_16 = True

                arg_17.update(arg_5.get('inheritance_models', []))

            arg_7['disease_associated_transcripts'] = list(arg_13)
            arg_7['manual_penetrance'] = arg_15
            arg_7['mosaicism'] = arg_16
            arg_7['manual_inheritance'] = list(arg_17)

            # Now add the information from hgnc and panels
            # to the transcripts on the variant

            # First loop over the variants transcripts
            for arg_10 in arg_7.get('transcripts', []):
                arg_11 = arg_10['transcript_id']
                if not arg_11 in arg_9:
                    continue

                # This is the common information about the transcript
                arg_20 = arg_9[arg_11]

                # Check in the common information if it is a primary transcript
                if arg_20.get('is_primary'):
                    arg_10['is_primary'] = True
                # If the transcript has a ref seq identifier we add that
                # to the variants transcript
                if not arg_20.get('refseq_id'):
                    continue

                arg_21 = arg_20['refseq_id']
                arg_10['refseq_id'] = arg_21
                arg_1['has_refseq'] = True
                # Check if the refseq id are disease associated
                if arg_21 in arg_14:
                    arg_10['is_disease_associated'] = True

                # Since a ensemble transcript can have multiple refseq identifiers we add all of
                # those
                arg_10['refseq_identifiers'] = arg_20.get('refseq_identifiers',[])

            arg_7['common'] = arg_8
            # Add the associated disease terms
            arg_7['disease_terms'] = arg_0.disease_terms(arg_6)

        return arg_1


def Func(arg_0, arg_1=None, arg_2=None):
        """Return all variants with sanger information

        Args:
            institute_id(str)
            case_id(str)

        Returns:
            res(pymongo.Cursor): A Cursor with all variants with sanger activity
        """
        arg_3 = {'validation': {'$exists': True}}
        if arg_1:
            arg_3['institute_id'] = arg_1
        if arg_2:
            arg_3['case_id'] = arg_2

        return arg_0.variant_collection.find(arg_3)


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Returns the specified Func.

           Arguments:
               document_id : A md5 key that represents the Func or "Func_id"
               gene_panels(List[GenePanel])
               case_id (str): case id (will search with "Func_id")

           Returns:
               Func_object(Variant): A odm Func object
        """
        arg_4 = {}
        if arg_3:
            # search for a Func in a case
            arg_4['case_id'] = arg_3
            arg_4['Func_id'] = arg_1
        else:
            # search with a unique id
            arg_4['_id'] = arg_1

        arg_5 = arg_0.Func_collection.find_one(arg_4)
        if arg_5:
            arg_5 = arg_0.add_gene_info(arg_5, arg_2)
            if arg_5['chromosome'] in ['X', 'Y']:
                ## TODO add the build here
                arg_5['is_par'] = is_par(arg_5['chromosome'],
                                               arg_5['position'])
        return arg_5


def Func(arg_0, arg_1):
        """Return all Func variants for a given institute

        Args:
            institute_id(str): institute id

        Returns:
            res(list): a list with validated variants
        """
        arg_2 = {
            'verb' : 'validate',
            'institute' : arg_1,
        }
        arg_3 = []
        arg_4 = arg_0.event_collection.find(arg_2)
        for arg_5 in list(arg_4):
            arg_6 = arg_5['case']
            arg_7 = arg_0.variant(arg_6=arg_6, document_id=arg_5['variant_id'])
            arg_8 = arg_0.case(arg_6=arg_6)
            if not arg_8 or not arg_7:
                continue # Take into account that stuff might have been removed from database
            arg_7['case_obj'] = {
                'display_name' : arg_8['display_name'],
                'individuals' : arg_8['individuals']
            }
            arg_3.append(arg_7)

        return arg_3


def Func(arg_0, arg_1=None, arg_2=None):
        """Check if there are any variants that are previously marked causative

            Loop through all variants that are marked 'causative' for an
            institute and check if any of the variants are present in the
            current case.

            Args:
                case_obj (dict): A Case object
                institute_obj (dict): check across the whole institute

            Returns:
                causatives(iterable(Variant))
        """
        arg_3 = arg_1['owner'] if arg_1 else arg_2['_id']
        arg_4 = arg_0.get_causatives(arg_3)
        if len(arg_4) == 0:
            return []

        if arg_1:
            # exclude variants that are marked causative in "case_obj"
            arg_5 = set(arg_1.get('causatives', []))
            arg_4 = list(
                set(arg_4).difference(arg_5)
            )

        # convert from unique ids to general "variant_id"
        arg_6 = arg_0.variant_collection.find(
            {'_id': {'$in': arg_4}},
            {'variant_id': 1}
        )
        arg_7 = [item['variant_id'] for item in arg_6]

        arg_8 = {'variant_id': {'$in': arg_7}}
        if arg_1:
            arg_8['case_id'] = arg_1['_id']
        else:
            arg_8['institute'] = arg_2['_id']
        return arg_0.variant_collection.find(arg_8)


def Func(arg_0, arg_1, arg_2):
        """Find the same variant in other cases marked causative.

        Args:
            case_obj(dict)
            variant_obj(dict)

        Yields:
            other_variant(dict)
        """
        # variant id without "*_[variant_type]"
        arg_3 = arg_2['display_name'].rsplit('_', 1)[0]

        arg_4 = arg_0.get_causatives(arg_2['institute'])
        for arg_5 in arg_4:
            arg_6 = arg_0.variant(arg_5)
            if not arg_6:
                continue
            arg_7 = arg_6['case_id'] != arg_1['_id']
            arg_8 = arg_6['display_name'].startswith(arg_3)
            if arg_7 and arg_8:
                yield arg_6


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Delete variants of one type for a case

            This is used when a case is reanalyzed

            Args:
                case_id(str): The case id
                variant_type(str): 'research' or 'clinical'
                category(str): 'snv', 'sv' or 'cancer'
        """
        arg_3 = arg_3 or ''
        LOG.info("Deleting old {0} {1} variants for case {2}".format(
                    arg_2, arg_3, arg_1))
        arg_4 = {'case_id': arg_1, 'variant_type': arg_2}
        if arg_3:
            arg_4['category'] = arg_3
        arg_5 = arg_0.variant_collection.delete_many(arg_4)
        LOG.info("{0} variants deleted".format(arg_5.deleted_count))


def Func(arg_0, arg_1):
        """Return Func variants.

        Look at the genes that a variant overlaps to.
        Then return all variants that overlap these genes.

        If variant_obj is sv it will return the Func snvs and oposite
        There is a problem when SVs are huge since there are to many Func variants.

        Args:
            variant_obj(dict)

        Returns:
            variants(iterable(dict))
        """
        #This is the category of the variants that we want to collect
        arg_2 = 'snv' if arg_1['category'] == 'sv' else 'sv'

        arg_3 = {
            '$and': [
                {'case_id': arg_1['case_id']},
                {'category': arg_2},
                {'hgnc_ids' : { '$in' : arg_1['hgnc_ids']}}
            ]
        }

        arg_4 = [('rank_score', pymongo.DESCENDING)]
        # We collect the 30 most severe Func variants
        arg_5 = arg_0.variant_collection.find(arg_3).sort(arg_4).limit(30)

        return arg_5


def Func(arg_0, arg_1):
        """Returns variants that has been evaluated

        Return all variants, snvs/indels and svs from case case_id
        which have a entry for 'acmg_classification', 'manual_rank', 'dismiss_variant'
        or if they are commented.

        Args:
            case_id(str)

        Returns:
            variants(iterable(Variant))
        """
        # Get all variants that have been evaluated in some way for a case
        arg_2 = {
            '$and': [
                {'case_id': arg_1},
                {
                    '$or': [
                        {'acmg_classification': {'$exists': True}},
                        {'manual_rank': {'$exists': True}},
                        {'dismiss_variant': {'$exists': True}},
                    ]
                }
            ],
        }

        # Collect the result in a dictionary
        arg_3 = {}
        for arg_4 in arg_0.variant_collection.find(arg_2):
            arg_3[arg_4['variant_id']] = arg_0.add_gene_info(arg_4)

        # Collect all variant comments from the case
        arg_5 = {
            '$and': [
                {'case': arg_1},
                {'category': 'variant'},
                {'verb': 'comment'},
            ]
        }

        # Get all variantids for commented variants
        arg_6 = {event['variant_id'] for event in arg_0.event_collection.find(arg_5)}

        # Get the variant objects for commented variants, if they exist
        for arg_7 in arg_6:
            # Skip if we already added the variant
            if arg_7 in arg_3:
                continue
            # Get the variant with variant_id (not _id!)
            arg_8 = arg_0.variant(arg_7, arg_1=arg_1)

            # There could be cases with comments that refers to non existing variants
            # if a case has been reanalysed
            if not arg_8:
                continue

            arg_8['is_commented'] = True
            arg_3[arg_7] = arg_8

        # Return a list with the variant objects
        return arg_3.values()


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None,
                       arg_5=None, arg_6='clinical', arg_7='snv',
                       arg_8=None):
        """Produce a reduced vcf with variants from the specified coordinates
           This is used for the alignment viewer.

        Args:
            case_obj(dict): A case from the scout database
            variant_type(str): 'clinical' or 'research'. Default: 'clinical'
            category(str): 'snv' or 'sv'. Default: 'snv'
            rank_threshold(float): Only load variants above this score. Default: 5
            chrom(str): Load variants from a certain chromosome
            start(int): Specify the start position
            end(int): Specify the end position
            gene_obj(dict): A gene object from the database

        Returns:
            file_name(str): Path to the temporary file
        """
        arg_8 = arg_8 or -100

        arg_9 = None
        if arg_6 == 'clinical':
            if arg_7 == 'snv':
                arg_9 = arg_1['vcf_files'].get('vcf_snv')
            elif arg_7 == 'sv':
                arg_9 = arg_1['vcf_files'].get('vcf_sv')
            elif arg_7 == 'str':
                arg_9 = arg_1['vcf_files'].get('vcf_str')
        elif arg_6 == 'research':
            if arg_7 == 'snv':
                arg_9 = arg_1['vcf_files'].get('vcf_snv_research')
            elif arg_7 == 'sv':
                arg_9 = arg_1['vcf_files'].get('vcf_sv_research')

        if not arg_9:
            raise SyntaxError("Vcf file does not seem to exist")

        arg_10 = VCF(arg_9)
        arg_11 = ""

        if arg_5:
            arg_2 = arg_5['chromosome']
            arg_3 = arg_5['start']
            arg_4 = arg_5['end']

        if arg_2:
            if (arg_3 and arg_4):
                arg_11 = "{0}:{1}-{2}".format(arg_2, arg_3, arg_4)
            else:
                arg_11 = "{0}".format(arg_2)

        else:
            arg_8 = arg_8 or 5

        with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
            arg_12 = str(pathlib.Path(temp.name))
            for arg_13 in arg_10.raw_header.split('\n'):
                if len(arg_13) > 3:
                    temp.write(arg_13 + '\n')
            for arg_14 in arg_10(arg_11):
                temp.write(str(arg_14))

        return arg_12


def Func(arg_0, arg_1, arg_2, arg_3 = 'snv'):
        """Given a list of variants get variant objects found in a specific patient

        Args:
            variants(list): a list of variant ids
            sample_name(str): a sample display name
            category(str): 'snv', 'sv' ..

        Returns:
            result(iterable(Variant))
        """
        LOG.info('Retrieving variants for subject : {0}'.format(arg_2))
        arg_4 = re.compile('1|2') # a non wild-type allele is called at least once in this sample

        arg_5 = {
            '$and': [
                {'_id' : { '$in' : arg_1}},
                {'category' : arg_3},
                {'samples': {
                    '$elemMatch': { 'display_name' : arg_2, 'genotype_call': { '$regex' : arg_4 } }
                }}
            ]
        }

        arg_6 = arg_0.variant_collection.find(arg_5)
        return arg_6


def Func(arg_0, arg_1):
    """Determine which fields to include in csv header by checking a list of submission objects

        Args:
            submission_objs(list): a list of objects (variants or casedata) to include in a csv file
            csv_type(str) : 'variant_data' or 'case_data'

        Returns:
            custom_header(dict): A dictionary with the fields required in the csv header. Keys and values are specified in CLINVAR_HEADER and CASEDATA_HEADER

    """

    arg_2 = {} # header containing all available fields
    arg_3 = {}   # header reflecting the real data included in the submission objects
    if arg_1 == 'variant_data' :
        arg_2 = CLINVAR_HEADER
    else:
        arg_2 = CASEDATA_HEADER

    for arg_4, arg_5 in arg_2.items(): # loop over the info fields provided in each submission object
        for arg_6 in arg_0: # loop over the submission objects
            for arg_7, arg_8 in arg_6.items(): # loop over the keys and values of the clinvar objects

                if not arg_4 in arg_3 and arg_4 == arg_7: # add to custom header if missing and specified in submission object
                    arg_3[arg_4] = arg_5

    return arg_3


def Func(arg_0, arg_1=None, arg_2='37', arg_3=None):
    """Load all the transcripts

    Transcript information is from ensembl.

    Args:
        adapter(MongoAdapter)
        transcripts_lines(iterable): iterable with ensembl transcript lines
        build(str)
        ensembl_genes(dict): Map from ensembl_id -> HgncGene

    Returns:
        transcript_objs(list): A list with all transcript objects
    """
    # Fetch all genes with ensemblid as keys
    arg_3 = arg_3 or arg_0.ensembl_genes(arg_2)

    if arg_1 is None:
        arg_1 = fetch_ensembl_transcripts(arg_2=arg_2)

    # Map with all transcripts enstid -> parsed transcript
    arg_4 = parse_transcripts(arg_1)
    for arg_5 in list(arg_4):
        arg_6 = arg_4[arg_5]
        # Get the ens gene id
        arg_7 = arg_6['ensembl_gene_id']

        # Fetch the internal gene object to find out the correct hgnc id
        arg_8 = arg_3.get(arg_7)
        # If the gene is non existing in scout we skip the transcript
        if not arg_8:
            arg_4.pop(arg_5)
            LOG.debug("Gene %s does not exist in build %s", arg_7, arg_2)
            continue

        # Add the correct hgnc id
        arg_6['hgnc_id'] = arg_8['hgnc_id']
        # Primary transcript information is collected from HGNC
        arg_6['primary_transcripts'] = set(arg_8.get('primary_transcripts', []))

    arg_9 = 0
    arg_10 = 0
    arg_11 = len(arg_4)

    arg_12 = []

    with progressbar(arg_4.values(), label="Building transcripts", length=arg_11) as bar:
        for arg_13 in bar:

            #################### Get the correct refseq identifier ####################
            # We need to decide one refseq identifier for each transcript, if there are any to
            # choose from. The algorithm is as follows:
            # If there is ONE mrna this is choosen
            # If there are several mrna the one that is in 'primary_transcripts' is choosen
            # Else one is choosen at random
            # The same follows for the other categories where nc_rna has precedense over mrna_predicted
            # We will store all refseq identifiers in a "refseq_identifiers" list as well
            arg_13['is_primary'] = False
            arg_14 = arg_13['primary_transcripts']
            arg_15 = None
            arg_16 = []
            for arg_17 in TRANSCRIPT_CATEGORIES:
                arg_18 = arg_13[arg_17]
                if not arg_18:
                    continue

                for arg_19 in arg_18:
                    # Add all refseq identifiers to refseq_identifiers
                    arg_16.append(arg_19)
                    arg_9 += 1

                    if arg_19 in arg_14:
                        arg_15 = arg_19
                        arg_13['is_primary'] = True
                        arg_10 += 1

                    if not arg_15:
                        arg_15 = arg_19

            if arg_15:
                arg_13['refseq_id'] = arg_15
            if arg_16:
                arg_13['refseq_identifiers'] = arg_16

            ####################  ####################  ####################
            # Build the transcript object
            arg_20 = build_transcript(arg_13, arg_2)
            arg_12.append(arg_20)

    # Load all transcripts
    LOG.info("Loading transcripts...")
    if len(arg_12) > 0:
        arg_0.load_transcript_bulk(arg_12)

    LOG.info('Number of transcripts in build %s: %s', arg_2, arg_11)
    LOG.info('Number of transcripts with refseq identifier: %s', arg_9)
    LOG.info('Number of primary transcripts: %s', arg_10)

    return arg_12


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9, arg_10):
    """Add a gene Func to the database."""

    arg_11 = arg_0.obj['adapter']
    arg_7 = arg_7 or 'cust000'

    if arg_8:
        arg_9 = arg_9 or arg_0.obj.get('omim_api_key')
        if not arg_9:
            LOG.warning("Please provide a omim api key to load the omim gene Func")
            arg_0.abort()
        #Check if OMIM-AUTO exists
        if arg_11.gene_Func(arg_6='OMIM-AUTO'):
            LOG.warning("OMIM-AUTO already exists in database")
            LOG.info("To create a new version use scout update omim")
            return

        # Here we know that there is no Func loaded
        try:
            arg_11.load_omim_Func(arg_9, arg_7=arg_7)
        except Exception as err:
            LOG.error(err)
            arg_0.abort()

    if arg_10:
        # try:
        load_Func_app(arg_11, arg_6, arg_7=arg_7)
        # except Exception as err:
        #     LOG.warning(err)
        #     context.abort()

    if (arg_8 or arg_10):
        return

    if arg_1 is None:
        LOG.info("Please provide a Func")
        return
    try:
        load_Func(arg_1, arg_11, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7)
    except Exception as err:
        LOG.warning(err)
        arg_0.abort()


def Func(arg_0, arg_1, arg_2):
    """Delete a version of a gene Func or all versions of a gene Func"""
    LOG.info("Running scout delete Func")
    arg_3 = arg_0.obj['adapter']

    arg_4 = arg_3.gene_Funcs(arg_1=arg_1, arg_2=arg_2)
    if arg_4.count() == 0:
        LOG.info("No Funcs found")

    for arg_5 in arg_4:
        arg_3.delete_Func(arg_5)


def Func(arg_0):
    """Delete all Funces in the database"""
    LOG.info("Running scout delete Func")
    arg_1 = arg_0.obj['adapter']

    for arg_2 in arg_1.db.collection_names():
        arg_1.db[arg_2].drop_Funces()
    LOG.info("All Funces deleted")


def Func(arg_0, arg_1):
    """Delete a Func from the database"""
    LOG.info("Running scout delete Func")
    arg_2 = arg_0.obj['adapter']
    arg_3 = arg_2.Func(arg_1)
    if not arg_3:
        LOG.warning("User {0} could not be found in database".format(arg_1))
    else:
        arg_2.delete_Func(arg_1)


def Func(arg_0, arg_1):
    """Delete all Func in the database"""
    LOG.info("Running scout delete Func")
    arg_2 = arg_0.obj['adapter']

    arg_2.drop_Func(arg_1)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Delete a case and it's variants from the database"""
    arg_4 = arg_0.obj['adapter']
    if not (arg_2 or arg_3):
        click.echo("Please specify what case to delete")
        arg_0.abort()

    if arg_3:
        if not arg_1:
            click.echo("Please specify the owner of the case that should be "
                       "deleted with flag '-i/--institute'.")
            arg_0.abort()
        arg_2 = "{0}-{1}".format(arg_1, arg_3)

    LOG.info("Running deleting case {0}".format(arg_2))
    Func = arg_4.delete_case(
        arg_2=arg_2,
        institute_id=arg_1,
        arg_3=arg_3
    )

    if Func.deleted_count == 1:
        arg_4.delete_variants(arg_2=arg_2, variant_type='clinical')
        arg_4.delete_variants(arg_2=arg_2, variant_type='research')
    else:
        LOG.warning("Case does not exist in database")
        arg_0.abort()


def Func(arg_0, arg_1, arg_2, arg_3):
    """Show all individuals from all cases in the database"""
    LOG.info("Running scout view individuals")
    arg_4 = arg_0.obj['adapter']
    Func = []

    if arg_3:
        arg_6 = arg_4.case(arg_3=arg_3)
        if arg_6:
            arg_7 = [arg_6]
        else:
            LOG.info("Could not find case %s", arg_3)
            return
    else:
        arg_7 = [case_obj for case_obj in
                 arg_4.cases(
                     collaborator=arg_1,
                     has_causatives=arg_2)]
        if len(arg_7) == 0:
            LOG.info("Could not find cases that match criteria")
            return
        Func = (arg_8 for case_obj in arg_7 for arg_8 in case_obj['individuals'])

    click.echo("#case_id\tind_id\tdisplay_name\tsex\tphenotype\tmother\tfather")

    for arg_6 in arg_7:
        for arg_8 in arg_6['individuals']:
            arg_9 = [
                arg_6['_id'], arg_8['individual_id'],
                arg_8['display_name'], SEX_MAP[int(arg_8['sex'])],
                PHENOTYPE_MAP[arg_8['phenotype']], arg_8['mother'],
                arg_8['father']
            ]
            click.echo('\t'.join(arg_9))


def Func(arg_0, arg_1):
    """Parse a list of matchmaker matches objects and returns
       a readable list of matches to display in matchmaker matches view.

    Args:
        patient_id(str): id of a mme patient
        match_objs(list): list of match objs returned by MME server for the patient
                # match_objs looks like this:
                    [
                        {
                            'node' : { id : node_id , label: node_label},
                            'patients' : [
                                { 'patient': {patient1_data} },
                                { 'patient': {patient2_data} },
                                ..
                            ]
                        },
                        ..
                    ]

    Returns:
        parsed_matches(list): a list of parsed match objects

    """
    LOG.info('Parsing MatchMaker matches for patient {}'.format(arg_0))
    arg_2 = []

    for arg_3 in arg_1:

        # convert match date from millisecond to readable date
        arg_4 = arg_3['created']['$date']
        arg_5 = datetime.datetime.fromtimestamp(arg_4/1000.0)
        arg_6 = 'external'
        arg_7 = []

        arg_8 = {
            'match_oid' : arg_3['_id']['$oid'],# save match object ID
            'match_date' : arg_5
        }

        # if patient was used as query patient:
        if arg_3['data']['patient']['id'] == arg_0:
            arg_9 = arg_3['results'] # List of matching patients
            for arg_10 in arg_9:
                if arg_3['match_type'] == 'internal':
                    arg_6 = 'internal'

                for arg_11 in arg_10['patients']:
                    arg_12 = {
                        'patient_id' : arg_11['patient']['id'],
                        'score' : arg_11['score'],
                        'patient' : arg_11['patient'],
                        'node' : arg_10['node']
                    }
                    arg_7.append(arg_12)

        else: # else if patient was returned as a match result for another patient
            arg_13 = arg_3['data']['patient']
            arg_14 = arg_13['contact'].get('institution')
            if arg_14 and 'Scout software user' in arg_14:
                arg_6 = 'internal'

            # loop over match results to capture score for matching
            arg_15 = None
            for arg_16 in arg_3['results']:
                for arg_11 in arg_16['patients']:
                    LOG.info('Looping in else, patient:{}'.format(arg_11['patient']['id']))
                    if arg_11['patient']['id'] == arg_0:

                        arg_15 = arg_11['score']
                        arg_12 = {
                            'patient_id' : arg_13['id'],
                            'score' : arg_15,
                            'patient' : arg_13,
                            'node' : arg_16['node']
                        }
                        arg_7.append(arg_12)

        arg_8['match_type'] = arg_6
        arg_8['patients'] = arg_7
        arg_2.append(arg_8)

    # sort results by descending score
    arg_2 = sorted(arg_2, key=lambda k: k['match_date'], reverse=True)
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """Display Func from the database"""
    LOG.info("Running scout view institutes")
    arg_6 = arg_0.obj['adapter']

    arg_7 = []
    if arg_3:
        arg_8 = arg_6.case(arg_3=arg_3)
        if arg_8:
            arg_7.append(arg_8)

    else:
        arg_7 = arg_6.Func(collaborator=arg_1, name_query=arg_2)
        arg_7 = [arg_8 for arg_8 in arg_7]

    if not arg_7:
        LOG.info("No Func could be found")
        return

    arg_9 = ['case_id', 'display_name', 'institute']

    if arg_5:
        LOG.info("Only show Func with more than %s variants", arg_5)
        arg_4 = True

    if arg_4:
        LOG.info("Displaying number of variants for each case")
        arg_9.append('clinical')
        arg_9.append('research')

    click.echo("#"+'\t'.join(arg_9))
    for arg_10 in arg_7:
        arg_11 = "{:<12}\t{:<12}\t{:<12}"
        arg_12 = [arg_10['_id'],arg_10['display_name'],arg_10['owner']]
        if arg_4:
            arg_11 += "\t{:<12}\t{:<12}"
            arg_13 = 0
            arg_14 = 0
            arg_15 = arg_6.variant_collection.find({'case_id':arg_10['_id']})
            arg_16 = 0
            for arg_16, arg_17 in enumerate(arg_15, 1):
                if arg_17['variant_type'] == 'clinical':
                    arg_13 += 1
                else:
                    arg_14 += 1
            arg_12.extend([arg_13, arg_14])

            if arg_5 and arg_16 < arg_5:
                LOG.debug("Case %s had to few variants, skipping", arg_10['_id'])
                continue

        click.echo(arg_11.format(*arg_12))


def Func(arg_0):
    """Returns the currently active user as an object."""
    arg_1 = store.user(arg_0)
    arg_2 = LoginUser(arg_1) if arg_1 else None
    return arg_2


def Func():
    """Login a user if they have access."""
    # store potential next param URL in the session
    if 'next' in request.args:
        arg_0['next_url'] = request.args['next']

    if current_app.config.get('GOOGLE'):
        arg_1 = url_for('.authorized', _external=True)
        return google.authorize(callback=arg_1)

    arg_2 = request.args.get('email')
    arg_3 = store.user(arg_2)

    if arg_3 is None:
        flash("email not whitelisted: {}".format(arg_2), 'warning')
        return redirect(url_for('public.index'))

    return perform_Func(arg_3)


def Func(arg_0, arg_1, arg_2=None,
                    arg_3=None, arg_4=None):
    """Build a institute object

    Args:
        internal_id(str)
        display_name(str)
        sanger_recipients(list(str)): List with email addresses

    Returns:
        institute_obj(scout.models.Institute)

    """

    LOG.info("Building institute %s with display name %s", arg_0,arg_1)

    arg_5 = Institute(
        arg_0=arg_0,
        arg_1=arg_1,
        arg_2=arg_2,
        arg_3 = arg_3,
        arg_4 = arg_4
    )

    for arg_6 in list(arg_5):
        if arg_5[arg_6] is None:
            arg_5.pop(arg_6)

    return arg_5


def Func(arg_0, arg_1):
        """Delete a event

            Arguments:
                event_id (str): The database key for the event
        """
        LOG.info("Deleting event{0}".format(arg_1))
        if not isinstance(arg_1, ObjectId):
            arg_1 = ObjectId(arg_1)
        arg_0.event_collection.delete_one({'_id': arg_1})
        LOG.debug("Event {0} deleted".format(arg_1))