def Func(arg_0, arg_1):
        """Add the correct hgnc id to a set of genes with hgnc symbols

        Args:
            genes(list(dict)): A set of genes with hgnc symbols only

        """
        arg_2 = arg_0.genes_by_alias()

        for arg_3 in arg_1:
            arg_4 = arg_2.get(arg_3['hgnc_symbol'])
            if not arg_4:
                LOG.warning("Gene %s does not exist in scout", arg_3['hgnc_symbol'])
                continue
            arg_3['hgnc_id'] = arg_4['true']
            if not arg_4['true']:
                if len(arg_4['ids']) > 1:
                    LOG.warning("Gene %s has ambiguous value, please choose one hgnc id in result", arg_3['hgnc_symbol'])
                arg_3['hgnc_id'] = ','.join([str(hgnc_id) for hgnc_id in arg_4['ids']])


def Func(arg_0, arg_1='37', arg_2=None):
        """Return a dictionary with chromosomes as keys and interval trees as values

        Each interval represents a coding region of overlapping genes.

        Args:
            build(str): The genome build
            genes(iterable(scout.models.HgncGene)):

        Returns:
            intervals(dict): A dictionary with chromosomes as keys and overlapping genomic intervals as values
        """
        arg_3 = {}
        if not arg_2:
            arg_2 = arg_0.all_genes(arg_1=arg_1)
        LOG.info("Building interval trees...")
        for arg_4,arg_5 in enumerate(arg_2):
            arg_6 = arg_5['chromosome']
            arg_7 = max((arg_5['start'] - 5000), 1)
            arg_8 = arg_5['end'] + 5000

            # If this is the first time a chromosome is seen we create a new
            # interval tree with current interval
            if arg_6 not in arg_3:
                arg_3[arg_6] = intervaltree.IntervalTree()
                arg_3[arg_6].addi(arg_7, arg_8, arg_4)
                continue

            arg_9 = arg_3[arg_6].search(arg_7, arg_8)

            # If the interval did not overlap any other intervals we insert it and continue
            if not arg_9:
                arg_3[arg_6].addi(arg_7, arg_8, arg_4)
                continue

            # Loop over the overlapping intervals
            for arg_10 in arg_9:
                # Update the positions to new max and mins
                if arg_10.begin < arg_7:
                    arg_7 = arg_10.begin

                if arg_10.end > arg_8:
                    arg_8 = arg_10.end

                # Delete the old interval
                arg_3[arg_6].remove(arg_10)

            # Add the new interval consisting och the overlapping ones
            arg_3[arg_6].addi(arg_7, arg_8, arg_4)

        return arg_3


def Func(arg_0, arg_1, arg_2):
    """
    Update the automate generated Func gene panel in the database.
    """
    LOG.info("Running scout update Func")
    arg_3 = arg_0.obj['adapter']

    arg_1 = arg_1 or arg_0.obj.get('Func_api_key')
    if not arg_1:
        LOG.warning("Please provide a Func api key to load the Func gene panel")
        arg_0.abort()

    arg_4 = arg_3.institute(arg_2)
    if not arg_4:
        LOG.info("Institute %s could not be found in database", arg_2)
        LOG.warning("Please specify an existing institute")
        arg_0.abort()

    try:
        arg_3.load_Func_panel(arg_1, arg_2=arg_2)
    except Exception as err:
        LOG.error(err)
        arg_0.abort()


def Func(arg_0, arg_1):
    """Show all MatchMaker matches for a given case"""
    # check that only authorized users can access MME patients matches
    arg_2 = store.user(current_user.email)
    if 'mme_submitter' not in arg_2['roles']:
        flash('unauthorized request', 'warning')
        return redirect(request.referrer)
    # Required params for getting matches from MME server:
    arg_3 = current_app.config.get('MME_URL')
    arg_4 = current_app.config.get('MME_TOKEN')
    if not arg_3 or not arg_4:
        flash('An error occurred reading matchmaker connection parameters. Please check config file!', 'danger')
        return redirect(request.referrer)
    arg_5, arg_6 = institute_and_case(store, arg_0, arg_1)
    arg_7 = controllers.mme_matches(arg_6, arg_5, arg_3, arg_4)
    if arg_7 and arg_7.get('server_errors'):
        flash('MatchMaker server returned error:{}'.format(arg_7['server_errors']), 'danger')
        return redirect(request.referrer)
    elif not arg_7:
        arg_7 = {
            'institute' : arg_5,
            'case' : arg_6
        }
    return arg_7


def Func(arg_0, arg_1, arg_2):
    """Starts an internal match or a match against one or all MME external nodes"""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)

    # check that only authorized users can run matches
    arg_5 = store.user(current_user.email)
    if 'mme_submitter' not in arg_5['roles']:
        flash('unauthorized request', 'warning')
        return redirect(request.referrer)

    # Required params for sending an add request to MME:
    arg_6 = current_app.config.get('MME_URL')
    arg_7 = current_app.config.get('MME_ACCEPTS')
    arg_8 = current_app.config.get('MME_TOKEN')
    arg_9 = current_app.mme_nodes

    if not arg_6 or not arg_8 or not arg_7:
        flash('An error occurred reading matchmaker connection parameters. Please check config file!', 'danger')
        return redirect(request.referrer)

    arg_10 = controllers.mme_match(arg_4, arg_2, arg_6, arg_8, arg_9, arg_7)
    arg_11 = 0
    for arg_10 in arg_10:
        arg_10['status_code'] == 200
        arg_11 +=1
    if arg_11:
        flash("Match request sent. Look for eventual matches in 'Matches' page.", 'info')
    else:
        flash('An error occurred while sending match request.', 'danger')

    return redirect(request.referrer)


def Func(arg_0, arg_1):
    """Visualize case report"""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    arg_4 = controllers.Func_content(store, arg_2, arg_3)
    return dict(institute=arg_2, case=arg_3, format='html', **arg_4)


def Func(arg_0, arg_1):
    """Add or remove a diagnosis for a case."""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    arg_4 = store.user(current_user.email)
    arg_5 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    arg_6 = 'phenotype' if 'phenotype' in request.form else 'gene'
    arg_7 = request.form['omim_id']
    arg_8 = True if request.args.get('remove') == 'yes' else False
    store.diagnose(arg_2, arg_3, arg_4, arg_5, arg_6=arg_6,
                   arg_7=arg_7, arg_8=arg_8)
    return redirect(request.referrer)


def Func(arg_0, arg_1, arg_2=None):
    """Handle Func."""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)
    arg_5 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    arg_6 = request.args.get('is_group') == 'yes'
    arg_7 = store.user(current_user.email)

    if arg_2:
        # DELETE a phenotype item/group from case
        store.remove_phenotype(arg_3, arg_4, arg_7, arg_5,
                               arg_2, arg_6=arg_6)
    else:
        try:
            # add a new phenotype item/group to the case
            arg_8 = request.form['hpo_term']
            if arg_8.startswith('HP:') or len(arg_8) == 7:
                arg_9 = arg_8.split(' | ', 1)[0]
                store.add_phenotype(arg_3, arg_4, arg_7, arg_5,
                                    arg_9=arg_9, arg_6=arg_6)
            else:
                # assume omim id
                store.add_phenotype(arg_3, arg_4, arg_7, arg_5,
                                    omim_term=arg_8)
        except ValueError:
            return abort(400, ("unable to add phenotype: {}".format(arg_8)))
    return redirect(arg_5)


def Func(arg_0, arg_1):
    """Perform actions on multiple phenotypes."""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    arg_4 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    arg_5 = request.form['action']
    arg_6 = request.form.getlist('hpo_id')
    arg_7 = store.user(current_user.email)

    if arg_5 == 'DELETE':
        for arg_8 in arg_6:
            # DELETE a phenotype from the list
            store.remove_phenotype(arg_2, arg_3, arg_7, arg_4, arg_8)
    elif arg_5 == 'PHENOMIZER':
        if len(arg_6) == 0:
            arg_6 = [term['phenotype_id'] for term in arg_3.get('phenotype_terms', [])]

        arg_9 = current_app.config['PHENOMIZER_USERNAME']
        arg_10 = current_app.config['PHENOMIZER_PASSWORD']
        arg_11 = controllers.hpo_diseases(arg_9, arg_10, arg_6)
        return render_template('cases/diseases.html', arg_11=arg_11,
                               institute=arg_2, case=arg_3)

    elif arg_5 == 'GENES':
        arg_12 = set()
        for arg_13 in request.form.getlist('genes'):
            # avoid empty lists
            if arg_13:
                arg_12.update(arg_14.split(' ', 1)[0] for arg_14 in
                                    arg_13.split('|'))
        store.update_dynamic_gene_list(arg_3, arg_12=arg_12)

    elif arg_5 == 'GENERATE':
        if len(arg_6) == 0:
            arg_6 = [term['phenotype_id'] for term in arg_3.get('phenotype_terms', [])]
        arg_15 = store.generate_hpo_gene_list(*arg_6)
        # determine how many HPO terms each gene must match
        arg_16 = int(request.form.get('min_match') or 1)
        arg_17 = [result[0] for result in arg_15 if result[1] >= arg_16]
        store.update_dynamic_gene_list(arg_3, arg_17=arg_17, phenotype_ids=arg_6)

    return redirect(arg_4)


def Func(arg_0, arg_1, arg_2=None):
    """Handle Func."""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)
    arg_5 = request.form.get('link')
    arg_6 = request.form.get('content')
    arg_7 = request.args.get('variant_id')
    arg_8 = store.user(current_user.email)

    if arg_2:
        # delete the event
        store.delete_event(arg_2)
    else:
        if arg_7:
            # create a variant comment
            arg_9 = store.variant(arg_7)
            arg_10 = request.form.get('level', 'specific')
            store.comment(arg_3, arg_4, arg_8, arg_5,
                          variant=arg_9, arg_6=arg_6, comment_level=arg_10)
        else:
            # create a case comment
            store.comment(arg_3, arg_4, arg_8, arg_5, arg_6=arg_6)

    return redirect(request.referrer)


def Func(arg_0, arg_1, arg_2=None):
    """Assign and unFunc a user from a case."""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)
    arg_5 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    if arg_2:
        arg_6 = store.user(arg_2)
    else:
        arg_6 = store.user(current_user.email)
    if request.form.get('action') == 'DELETE':
        store.unFunc(arg_3, arg_4, arg_6, arg_5)
    else:
        store.Func(arg_3, arg_4, arg_6, arg_5)
    return redirect(request.referrer)


def Func(arg_0, arg_1, arg_2):
    """Mark a variant as sanger validated."""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)
    arg_5 = store.variant(arg_2)
    arg_6 = store.user(current_user.email)
    arg_7 = request.form['type'] or None
    arg_8 = url_for('variants.variant', arg_0=arg_0, arg_1=arg_1,
                   arg_2=arg_2)
    store.validate(arg_3, arg_4, arg_6, arg_8, arg_5, arg_7)
    return redirect(request.referrer or arg_8)


def Func(arg_0, arg_1, arg_2):
    """Mark a variant as confirmed causative."""
    arg_3, arg_4 = institute_and_case(store, arg_0, arg_1)
    arg_5 = store.variant(arg_2)
    arg_6 = store.user(current_user.email)
    arg_7 = url_for('variants.variant', arg_0=arg_0, arg_1=arg_1,
                   arg_2=arg_2)
    if request.form['action'] == 'ADD':
        store.Func(arg_3, arg_4, arg_6, arg_7, arg_5)
    elif request.form['action'] == 'DELETE':
        store.unFunc(arg_3, arg_4, arg_6, arg_7, arg_5)

    # send the user back to the case that was marked as solved
    arg_8 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    return redirect(arg_8)


def Func(arg_0, arg_1):
    """Display delivery report."""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    if arg_3.get('delivery_report') is None:
        return abort(404)

    arg_4 = request.args.get('date')
    if arg_4:
        Func = None
        arg_6 = parse_date(arg_4)
        for arg_7 in arg_3['analyses']:
            if arg_7['date'] == arg_6:
                Func = arg_7['delivery_report']
        if Func is None:
            return abort(404)
    else:
        Func = arg_3['delivery_report']

    arg_8 = os.path.dirname(Func)
    arg_9 = os.path.basename(Func)
    return send_from_directory(arg_8, arg_9)


def Func(arg_0, arg_1):
    """Share a case with a different institute."""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    arg_4 = store.user(current_user.email)
    arg_5 = request.form['collaborator']
    arg_6 = 'revoke' in request.form
    arg_7 = url_for('.case', arg_0=arg_0, arg_1=arg_1)

    if arg_6:
        store.unFunc(arg_2, arg_3, arg_5, arg_4, arg_7)
    else:
        store.Func(arg_2, arg_3, arg_5, arg_4, arg_7)

    return redirect(request.referrer)


def Func(arg_0, arg_1):
    """Request a case to be Func."""
    arg_2 = current_app.config['MAIL_USERNAME']
    arg_3 = current_app.config['TICKET_SYSTEM_EMAIL']
    controllers.Func(store, mail, current_user, arg_0, arg_1, arg_2,
                      arg_3)
    return redirect(request.referrer)


def Func(arg_0, arg_1):
    """Open the Func list for a case."""
    arg_2, arg_3 = institute_and_case(store, arg_0, arg_1)
    arg_4 = store.user(current_user.email)
    arg_5 = url_for('.case', arg_0=arg_0, arg_1=arg_1)
    store.open_Func(arg_2, arg_3, arg_4, arg_5)
    return redirect(request.referrer)


def Func(arg_0, arg_1, arg_2):
    """Download vcf2cytosure file for individual."""

    (arg_3, Func) = controllers.vcf2cytosure(store,
        arg_0, arg_1, arg_2)

    arg_5 = os.path.abspath(os.path.dirname(Func))
    arg_6 = os.path.basename(Func)

    log.debug("Attempt to deliver file {0} from dir {1}".format(arg_6, arg_5))

    arg_7 = arg_3 + ".vcf2cytosure.cgh"

    return send_from_directory(arg_5, arg_6,
        arg_7=arg_7,
        as_attachment=True)


def Func(arg_0, arg_1):
    """Load Func report for the case."""
    arg_2 = controllers.Func(store, arg_0, arg_1)
    if arg_2['case'].get('Func') is None:
        return abort(404)
    arg_3 = os.path.abspath(os.path.dirname(arg_2['case']['Func']))
    arg_4 = os.path.basename(arg_2['case']['Func'])
    return send_from_directory(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2=100):
    """Preprocess case objects.

    Add the necessary information to display the 'Func' view

    Args:
        store(adapter.MongoAdapter)
        case_query(pymongo.Cursor)
        limit(int): Maximum number of Func to display

    Returns:
        data(dict): includes the Func, how many there are and the limit.
    """

    arg_3 = {status: [] for status in CASE_STATUSES}
    for arg_4 in arg_1.limit(arg_2):
        arg_5 = set(ind['analysis_type'] for ind in arg_4['individuals'])

        arg_4['analysis_types'] = list(arg_5)
        arg_4['assignees'] = [arg_0.user(user_email) for user_email in
                                 arg_4.get('assignees', [])]
        arg_3[arg_4['status']].append(arg_4)
        arg_4['is_rerun'] = len(arg_4.get('analyses', [])) > 0
        arg_4['clinvar_variants'] = arg_0.case_to_clinVars(arg_4['_id'])
        arg_4['display_track'] = TRACKS[arg_4.get('track', 'rare')]

    arg_6 = {
        'Func': [(status, arg_3[status]) for status in CASE_STATUSES],
        'found_Func': arg_1.count(),
        'limit': arg_2,
    }
    return arg_6


def Func(arg_0, arg_1, arg_2):
    """Gather contents to be visualized in a case report

    Args:
        store(adapter.MongoAdapter)
        institute_obj(models.Institute)
        case_obj(models.Case)

    Returns:
        data(dict)

    """
    arg_3 = {
        'causatives_detailed': 'causatives',
        'suspects_detailed': 'suspects',
        'classified_detailed': 'acmg_classification',
        'tagged_detailed': 'manual_rank',
        'dismissed_detailed': 'dismiss_variant',
        'commented_detailed': 'is_commented',
    }
    arg_4 = arg_2

    for arg_5 in arg_4['individuals']:
        try:
            arg_6 = int(arg_5.get('sex', 0))
        except ValueError as err:
            arg_6 = 0
        arg_5['sex_human'] = SEX_MAP[arg_6]
        arg_5['phenotype_human'] = PHENOTYPE_MAP.get(arg_5['phenotype'])

    # Add the case comments
    arg_4['comments'] = arg_0.events(arg_1, case=arg_2, comments=True)

    arg_4['manual_rank_options'] = MANUAL_RANK_OPTIONS
    arg_4['dismissed_options'] = DISMISS_VARIANT_OPTIONS
    arg_4['genetic_models'] = dict(GENETIC_MODELS)
    arg_4['report_created_at'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

    arg_7 = {}
    for arg_8 in arg_3:
        arg_7[arg_8] = []
    # We collect all causatives and suspected variants
    # These are handeled in separate since they are on case level
    for arg_9 in ['causatives', 'suspects']:
        #These include references to variants
        arg_8 = '_'.join([arg_9, 'detailed'])
        for arg_10 in arg_2.get(arg_9,[]):
            arg_11 = arg_0.variant(arg_10)
            if not arg_11:
                continue
            # If the variant exists we add it to the evaluated variants
            arg_7[arg_8].append(arg_11)

    ## get variants for this case that are either classified, commented, tagged or dismissed.
    for arg_12 in arg_0.evaluated_variants(case_id=arg_2['_id']):
        # Check which category it belongs to
        for arg_8 in arg_3:
            arg_13 = arg_3[arg_8]
            # When found we add it to the categpry
            # Eac variant can belong to multiple categories
            if arg_13 in arg_12:
                arg_7[arg_8].append(arg_12)

    for arg_9 in arg_7:
        arg_14 = []
        for arg_12 in arg_7[arg_9]:
        # We decorate the variant with some extra information
            if arg_12['category'] == 'snv':
                arg_15 = variant_decorator(
                        arg_0=arg_0,
                        arg_1=arg_1,
                        arg_2=arg_2,
                        variant_id=None,
                        arg_11=arg_12,
                        add_case=False,
                        add_other=False,
                        get_overlapping=False
                    )
            else:
                arg_15 = sv_variant(
                    arg_0=arg_0,
                    institute_id=arg_1['_id'],
                    case_name=arg_2['display_name'],
                    arg_11=arg_12,
                    add_case=False,
                    get_overlapping=False
                    )
            arg_14.append(arg_15['variant'])
        # Add the decorated variants to the case
        arg_4[arg_9] = arg_14

    return arg_4


def Func(arg_0, arg_1, arg_2):
    """Get all Clinvar submissions for a user and an institute"""
    arg_3 = list(arg_0.Func(arg_1, arg_2))
    return arg_3


def Func(arg_0, arg_1, arg_2):
    """Collect MT variants and format line of a MT variant report
    to be exported in excel format

    Args:
        store(adapter.MongoAdapter)
        case_obj(models.Case)
        temp_excel_dir(os.Path): folder where the temp excel files are written to

    Returns:
        written_files(int): the number of files written to temp_excel_dir

    """
    arg_3 = datetime.datetime.now().strftime('%Y-%m-%d')
    arg_4 = arg_1.get('individuals')

    arg_5 = {'chrom':'MT'}
    arg_6 = list(arg_0.variants(case_id=arg_1['_id'], arg_5=arg_5, nr_of_variants= -1, sort_key='position'))

    arg_7 = 0
    for arg_8 in arg_4:
        arg_9 = arg_8['individual_id']
        arg_10 = export_mt_variants(variants=arg_6, arg_9=arg_9)

        # set up document name
        arg_11 = '.'.join([arg_1['display_name'], arg_9, arg_3]) + '.xlsx'
        arg_12 = Workbook(os.path.join(arg_2,arg_11))
        arg_13 = arg_12.add_worksheet()

        # Write the column header
        arg_14 = 0
        for arg_15,arg_16 in enumerate(MT_EXPORT_HEADER):
            arg_13.write(arg_14,arg_15,arg_16)

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

        if os.path.exists(os.path.join(arg_2,arg_11)):
            arg_7 += 1

    return arg_7


def Func(arg_0, arg_1, arg_2, arg_3):
    """Func CGH file for inidividual."""
    arg_4, arg_5 = institute_and_case(arg_0, arg_1, arg_2)

    for arg_6 in arg_5['individuals']:
        if arg_6['individual_id'] == arg_3:
            arg_7 = arg_6

    return (arg_7['display_name'], arg_7['Func'])


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6,
    arg_7, arg_8, arg_9):
    """Add a patient to MatchMaker server

    Args:
        store(adapter.MongoAdapter)
        user_obj(dict) a scout user object (to be added as matchmaker contact)
        case_obj(dict) a scout case object
        add_gender(bool) if True case gender will be included in matchmaker
        add_features(bool) if True HPO features will be included in matchmaker
        add_disorders(bool) if True OMIM diagnoses will be included in matchmaker
        genes_only(bool) if True only genes and not variants will be shared
        mme_base_url(str) base url of the MME server
        mme_accepts(str) request content accepted by MME server
        mme_token(str) auth token of the MME server

    Returns:
        submitted_info(dict) info submitted to MatchMaker and its responses
    """

    if not arg_7 or not arg_8 or not arg_9:
        return 'Please check that Matchmaker connection parameters are valid'
    arg_10 = ''.join([arg_7, '/patient/add'])
    arg_11 = []   # this is the list of HPO terms
    arg_12 = []  # this is the list of OMIM diagnoses
    arg_13 = []

     # create contact dictionary
    arg_14 = {
        'name' : arg_1['name'],
        'href' : ''.join( ['mailto:',arg_1['email']] ),
        'institution' : 'Scout software user, Science For Life Laboratory, Stockholm, Sweden'
    }
    if arg_4: # create features dictionaries
        arg_11 = hpo_terms(arg_2)

    if arg_5: # create OMIM disorders dictionaries
        arg_12 = omim_terms(arg_2)

    # send a POST request and collect response for each affected individual in case
    arg_15 = []

    arg_16 = {
        'contact' : arg_14,
        'sex' : arg_3,
        'features' : arg_11,
        'disorders' : arg_12,
        'genes_only' : arg_6,
        'patient_id' : []
    }
    for arg_17 in arg_2.get('individuals'):
        if not arg_17['phenotype'] in  [2, 'affected']: # include only affected individuals
            continue

        arg_18 = {
            'contact' : arg_14,
            'id' : '.'.join([arg_2['_id'], arg_17.get('individual_id')]), # This is a required field form MME
            'label' : '.'.join([arg_2['display_name'], arg_17.get('display_name')]),
            'features' : arg_11,
            'disorders' : arg_12
        }
        if arg_3:
            if arg_17['sex'] == '1':
                arg_18['sex'] = 'MALE'
            else:
                arg_18['sex'] = 'FEMALE'

        if arg_2.get('suspects'):
            arg_13 = genomic_features(arg_0, arg_2, arg_17.get('display_name'), arg_6)
            arg_18['genomicFeatures'] = arg_13

        # send add request to server and capture response
        arg_19 = matchmaker_request(arg_10=arg_10, token=arg_9, method='POST', content_type=arg_8,
            accept='application/json', data={'patient':arg_18})

        arg_15.append({
                'patient': arg_18,
                'message': arg_19.get('message'),
                'status_code' : arg_19.get('status_code')
            })
    arg_16['server_responses'] = arg_15
    return arg_16


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None):
    """Initiate a MatchMaker match against either other Scout patients or external nodes

    Args:
        case_obj(dict): a scout case object already submitted to MME
        match_type(str): 'internal' or 'external'
        mme_base_url(str): base url of the MME server
        mme_token(str): auth token of the MME server
        mme_accepts(str): request content accepted by MME server (only for internal matches)

    Returns:
        matches(list): a list of eventual matches
    """
    arg_6 = []
    arg_7 = []
    arg_8 = None
    # list of patient dictionaries is required for internal matching
    arg_6 = arg_0['mme_submission']['patients']
    if arg_1=='internal':
        arg_8 = ''.join([arg_2,'/match'])
        for arg_9 in arg_6:
            arg_10 = matchmaker_request(arg_8=arg_8, token=arg_3, method='POST',
                content_type=arg_5, accept=arg_5, data={'patient':arg_9})
            arg_11 = {
                'server' : 'Local MatchMaker node',
                'patient_id' : arg_9['id'],
                'results' : arg_10.get('results'),
                'status_code' : arg_10.get('status_code'),
                'message' : arg_10.get('message') # None if request was successful
            }
            arg_7.append(arg_11)
    else: # external matching
        # external matching requires only patient ID
        arg_6 = [ arg_9['id'] for arg_9 in arg_6]
        arg_12 = [ arg_13['id'] for arg_13 in arg_4 ]
        if arg_1 in arg_12: # match is against a specific external node
            arg_12 = [arg_1]

        # Match every affected patient
        for arg_9 in arg_6:
            # Against every node
            for arg_13 in arg_12:
                arg_8 = ''.join([arg_2,'/match/external/', arg_9, '?node=', arg_13])
                arg_10 = matchmaker_request(arg_8=arg_8, token=arg_3, method='POST')
                arg_11 = {
                    'server' : arg_13,
                    'patient_id' : arg_9,
                    'results' : arg_10.get('results'),
                    'status_code' : arg_10.get('status_code'),
                    'message' : arg_10.get('message') # None if request was successful
                }
                arg_7.append(arg_11)
    return arg_7


def Func(arg_0, arg_1='snv'):
    """Parse how the different variant callers have performed

        Args:
            variant (cyvcf2.Variant): A variant object

        Returns:
            callers (dict): A dictionary on the format
            {'gatk': <filter>,'freebayes': <filter>,'samtools': <filter>}
    """
    arg_2 = CALLERS[arg_1]
    arg_3 = {arg_7['id']: None for arg_7 in arg_2}
    arg_4 = arg_0.INFO.get('set')
    if arg_4:
        arg_5 = arg_4.split('-')
        for arg_6 in arg_5:
            if arg_6 == 'FilteredInAll':
                for arg_7 in arg_3:
                    arg_3[arg_7] = 'Filtered'
            elif arg_6 == 'Intersection':
                for arg_7 in arg_3:
                    arg_3[arg_7] = 'Pass'
            elif 'filterIn' in arg_6:
                for arg_7 in arg_3:
                    if arg_7 in arg_6:
                        arg_3[arg_7] = 'Filtered'

            elif arg_6 in set(arg_3.keys()):
                arg_3[arg_6] = 'Pass'
    # The following is parsing of a custom made merge
    arg_8 = arg_0.INFO.get('FOUND_IN')
    if arg_8:
        for arg_5 in arg_8.split(','):
            arg_9 = arg_5.split('|')[0]
            arg_3[arg_9] = 'Pass'

    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=None):
    """Load a institute into the database

        Args:
            adapter(MongoAdapter)
            internal_id(str)
            display_name(str)
            sanger_recipients(list(email))
    """

    arg_4 = build_institute(
        arg_1=arg_1,
        arg_2=arg_2,
        arg_3=arg_3
    )
    log.info("Loading institute {0} with display name {1}" \
             " into database".format(arg_1, arg_2))

    arg_0.add_institute(arg_4)


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):
    """Load a Func into the database.

    A Func can be loaded without specifying vcf files and/or bam files
    """
    arg_13 = arg_0.obj['adapter']

    if arg_8 is None and arg_6 is None:
        LOG.warning("Please provide either scout config or ped file")
        arg_0.abort()

    # Scout needs a config object with the neccessary information
    # If no config is used create a dictionary
    arg_14 = yaml.load(arg_8) if arg_8 else {}

    try:
        arg_15 = parse_Func_data(
            arg_8=arg_14,
            arg_6=arg_6,
            arg_5=arg_5,
            vcf_snv=arg_1,
            arg_2=arg_2,
            arg_4=arg_4,
            arg_3=arg_3,
            arg_10=arg_10,
            arg_11=arg_11,
            arg_12=arg_12
        )
    except SyntaxError as err:
        LOG.warning(err)
        arg_0.abort()

    LOG.info("Use family %s" % arg_15['family'])

    try:
        arg_16 = arg_13.load_Func(arg_15, arg_7)
    except Exception as err:
        LOG.error("Something went wrong during loading")
        LOG.warning(err)
        arg_0.abort()


def Func(arg_0, arg_1, arg_2 = None):
        """Update compounds for a variant.

        This will add all the necessary information of a variant on a compound object.

        Args:
            variant(scout.models.Variant)
            variant_objs(dict): A dictionary with _ids as keys and variant objs as values.

        Returns:
            compound_objs(list(dict)): A dictionary with updated compound objects.

        """
        arg_3 = []
        for arg_4 in arg_1.get('compounds', []):
            arg_5 = True
            arg_6 = []
            # Check if the compound variant exists
            if arg_2:
                arg_7 = arg_2.get(arg_4['variant'])
            else:
                arg_7 = arg_0.variant_collection.find_one({'_id': arg_4['variant']})
            if arg_7:
                # If the variant exosts we try to collect as much info as possible
                arg_5 = False
                arg_4['rank_score'] = arg_7['rank_score']
                for arg_8 in arg_7.get('genes', []):
                    arg_9 = {
                        'hgnc_id': arg_8['hgnc_id'],
                        'hgnc_symbol': arg_8.get('hgnc_symbol'),
                        'region_annotation': arg_8.get('region_annotation'),
                        'functional_annotation': arg_8.get('functional_annotation'),
                    }
                    arg_6.append(arg_9)
                    arg_4['genes'] = arg_6

            arg_4['not_loaded'] = arg_5
            arg_3.append(arg_4)

        return arg_3


def Func(arg_0, arg_1):
        """Update the compounds for a set of variants.

        Args:
            variants(dict): A dictionary with _ids as keys and variant objs as values

        """
        LOG.debug("Updating compound objects")

        for arg_2 in arg_1:
            arg_3 = arg_1[arg_2]
            if not arg_3.get('compounds'):
                continue

            arg_4 = arg_0.update_variant_compounds(arg_3, arg_1)
            arg_3['compounds'] = arg_4

        LOG.debug("Compounds updated")

        return arg_1


def Func(arg_0, arg_1):
        """Load a variant object

        Args:
            variant_obj(dict)

        Returns:
            inserted_id
        """
        # LOG.debug("Loading variant %s", variant_obj['_id'])
        try:
            arg_2 = arg_0.variant_collection.insert_one(arg_1)
        except DuplicateKeyError as err:
            raise IntegrityError("Variant %s already exists in database", arg_1['_id'])
        return arg_2


def Func(arg_0, arg_1):
        """Load a variant object, if the object already exists update compounds.

        Args:
            variant_obj(dict)

        Returns:
            result
        """
        LOG.debug("Upserting variant %s", arg_1['_id'])
        try:
            arg_2 = arg_0.variant_collection.insert_one(arg_1)
        except DuplicateKeyError as err:
            LOG.debug("Variant %s already exists in database", arg_1['_id'])
            arg_2 = arg_0.variant_collection.find_one_and_update(
                {'_id': arg_1['_id']},
                {
                    '$set': {
                        'compounds': arg_1.get('compounds',[])
                    }
                }
            )
            arg_3 = arg_0.variant_collection.find_one({'_id': arg_1['_id']})
        return arg_2


def Func(arg_0, arg_1):
        """Load a bulk of variants

        Args:
            variants(iterable(scout.models.Variant))

        Returns:
            object_ids
        """
        if not len(arg_1) > 0:
            return

        LOG.debug("Loading variant bulk")
        try:
            arg_2 = arg_0.variant_collection.insert_many(arg_1)
        except (DuplicateKeyError, BulkWriteError) as err:
            # If the bulk write is wrong there are probably some variants already existing
            # In the database. So insert each variant
            for arg_3 in arg_1:
                try:
                    arg_0.upsert_variant(arg_3)
                except IntegrityError as err:
                    pass

        return


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Assign a user to a case.

        This function will create an Event to log that a person has been Funced
        to a case. Also the user will be added to case "Funcees".

        Arguments:
            institute (dict): A institute
            case (dict): A case
            user (dict): A User object
            link (str): The url to be used in the event

        Returns:
            updated_case(dict)
        """
        LOG.info("Creating event for Funcing {0} to {1}"
                    .format(arg_3['name'].encode('utf-8'), arg_2['display_name']))

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='case',
            verb='Func',
            subject=arg_2['display_name']
        )
        LOG.info("Updating {0} to be Funced with {1}"
                    .format(arg_2['display_name'], arg_3['name']))

        arg_5 = arg_0.case_collection.find_one_and_update(
            {'_id': arg_2['_id']},
            {'$addToSet': {'Funcees': arg_3['_id']}},
            return_document=pymongo.ReturnDocument.AFTER
        )
        return arg_5


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """Share a case with a new institute.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            collaborator_id (str): A instute id
            user (dict): A User object
            link (str): The url to be used in the event

        Return:
            updated_case
        """
        if arg_3 in arg_2.get('collaborators', []):
            raise ValueError('new customer is already a collaborator')

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_4=arg_4,
            arg_5=arg_5,
            category='case',
            verb='Func',
            subject=arg_3
        )

        arg_6 = arg_0.case_collection.find_one_and_update(
            {'_id': arg_2['_id']},
            {
                '$push': {'collaborators': arg_3}
            },
            return_document=pymongo.ReturnDocument.AFTER
        )
        LOG.debug("Case updated")
        return arg_6


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7=False):
        """Diagnose a case using OMIM ids.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            level (str): choices=('phenotype','gene')

        Return:
            updated_case

        """
        if arg_5 == 'phenotype':
            arg_8 = 'diagnosis_phenotypes'
        elif arg_5 == 'gene':
            arg_8 = 'diagnosis_genes'
        else:
            raise TypeError('wrong level')

        arg_9 = arg_2.get(arg_8, [])
        arg_10 = int(arg_6.split(':')[-1])

        arg_11 = None
        if arg_7 and arg_10 in arg_9:
            arg_11 = arg_0.case_collection.find_one_and_update(
                {'_id': arg_2['_id']},
                {'$pull': {arg_8: arg_10}},
                return_document=pymongo.ReturnDocument.AFTER
            )

        elif arg_10 not in arg_9:
            arg_11 = arg_0.case_collection.find_one_and_update(
                {'_id': arg_2['_id']},
                {'$push': {arg_8: arg_10}},
                return_document=pymongo.ReturnDocument.AFTER
            )

        if arg_11:
            arg_0.create_event(
                arg_1=arg_1,
                arg_2=arg_2,
                arg_3=arg_3,
                arg_4=arg_4,
                category='case',
                verb='update_diagnosis',
                subject=arg_2['display_name'],
                content=arg_6
            )

        return arg_11


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """Create an event for a variant verification for a variant
        and an event for a variant verification for a case

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            variant (dict): A variant object

        Returns:
            updated_variant(dict)
        """
        LOG.info("Creating event for ordering validation for variant" \
                    " {0}".format(arg_5['display_name']))

        arg_6 = arg_0.variant_collection.find_one_and_update(
            {'_id': arg_5['_id']},
            {'$set': {'sanger_ordered': True}},
            return_document=pymongo.ReturnDocument.AFTER
        )

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='variant',
            verb='sanger',
            arg_5=arg_5,
            subject=arg_5['display_name'],
        )

        LOG.info("Creating event for ordering sanger for case" \
                    " {0}".format(arg_2['display_name']))

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='case',
            verb='sanger',
            arg_5=arg_5,
            subject=arg_5['display_name'],
        )
        return arg_6


def Func(arg_0, arg_1=None, arg_2=None):
        """Get all variants with validations ever ordered.

        Args:
            institute_id(str) : The id of an institute
            user_id(str) : The id of an user

        Returns:
            sanger_ordered(list) : a list of dictionaries, each with "case_id" as keys and list of variant ids as values
        """
        arg_3 = {'$match': {
                '$and': [
                    {'verb': 'sanger'},
                ],
            }}

        if arg_1:
            arg_3['$match']['$and'].append({'institute': arg_1})
        if arg_2:
            arg_3['$match']['$and'].append({'user_id': arg_2})

        # Get all sanger ordered variants grouped by case_id
        arg_4 = arg_0.event_collection.aggregate([
            arg_3,
            {'$group': {
                '_id': "$case",
                'vars': {'$addToSet' : '$variant_id'}
            }}
        ])

        Func =  [item for item in arg_4]
        return Func


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """Create an event for marking a variant causative.

        Arguments:
          institute (dict): A Institute object
          case (dict): Case object
          user (dict): A User object
          link (str): The url to be used in the event
          variant (variant): A variant object

        Returns:
            updated_case(dict)
        """
        arg_6 = arg_5['display_name']
        LOG.info("Mark variant {0} as causative in the case {1}".format(
            arg_6, arg_2['display_name']))

        LOG.info("Adding variant to causatives in case {0}".format(
            arg_2['display_name']))

        LOG.info("Marking case {0} as solved".format(
            arg_2['display_name']))

        arg_7 = arg_0.case_collection.find_one_and_update(
            {'_id': arg_2['_id']},
            {
                '$push': {'causatives': arg_5['_id']},
                '$set': {'status': 'solved'}
            },
            return_document=pymongo.ReturnDocument.AFTER
        )

        LOG.info("Creating case event for marking {0}" \
                    " causative".format(arg_5['display_name']))

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='case',
            verb='Func',
            arg_5=arg_5,
            subject=arg_5['display_name'],
        )

        LOG.info("Creating variant event for marking {0}" \
                    " causative".format(arg_2['display_name']))

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='variant',
            verb='Func',
            arg_5=arg_5,
            subject=arg_5['display_name'],
        )
        return arg_7


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5,
                               arg_6):
        """Create an event for updating the manual dismiss variant entry

          This function will create a event and update the dismiss variant
          field of the variant.

        Arguments:
            institute (dict): A Institute object
            case (dict): Case object
            user (dict): A User object
            link (str): The url to be used in the event
            variant (dict): A variant object
            dismiss_variant (list): The new dismiss variant list

        Return:
            updated_variant

        """
        LOG.info("Creating event for updating dismiss variant for "
                    "variant {0}".format(arg_5['display_name']))

        arg_0.create_event(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            category='variant',
            verb='dismiss_variant',
            arg_5=arg_5,
            subject=arg_5['display_name'],
        )

        if arg_6:
            LOG.info("Setting dismiss variant to {0} for variant {1}"
                        .format(arg_6, arg_5['display_name']))
            arg_7 = '$set'
        else:
            LOG.info("Reset dismiss variant from {0} for variant {1}"
                        .format(arg_5['dismiss_variant'], arg_5['display_name']))
            arg_7 = '$unset'

        arg_8 = arg_0.variant_collection.find_one_and_update(
            {'_id': arg_5['_id']},
            {arg_7: {'dismiss_variant': arg_6}},
            return_document=pymongo.ReturnDocument.AFTER
        )
        LOG.debug("Variant updated")
        return arg_8


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """Create an event for updating the ACMG classification of a variant.

        Arguments:
            institute_obj (dict): A Institute object
            case_obj (dict): Case object
            user_obj (dict): A User object
            link (str): The url to be used in the event
            variant_obj (dict): A variant object
            acmg_str (str): The new ACMG classification string

        Returns:
            updated_variant
        """
        arg_0.create_event(
            institute=arg_1,
            case=arg_2,
            user=arg_3,
            arg_4=arg_4,
            category='variant',
            verb='acmg',
            variant=arg_5,
            subject=arg_5['display_name'],
        )
        LOG.info("Setting ACMG to {} for: {}".format(arg_6, arg_5['display_name']))

        if arg_6 is None:
            arg_7 = arg_0.variant_collection.find_one_and_update(
                {'_id': arg_5['_id']},
                {'$unset': {'acmg_classification': 1}},
                return_document=pymongo.ReturnDocument.AFTER
            )
        else:
            arg_7 = arg_0.variant_collection.find_one_and_update(
                {'_id': arg_5['_id']},
                {'$set': {'acmg_classification': REV_ACMG_MAP[arg_6]}},
                return_document=pymongo.ReturnDocument.AFTER
            )

        LOG.debug("Variant updated")
        return arg_7


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """Construct the necessary ids for a variant

    Args:
        chrom(str): Variant chromosome
        pos(int): Variant position
        ref(str): Variant reference
        alt(str): Variant alternative
        case_id(str): Unique case id
        variant_type(str): 'clinical' or 'research'

    Returns:
        ids(dict): Dictionary with the relevant ids
    """
    arg_6 = {}
    arg_1 = str(arg_1)

    arg_6['simple_id'] = parse_simple_id(arg_0, arg_1, arg_2, arg_3)
    arg_6['variant_id'] = parse_variant_id(arg_0, arg_1, arg_2, arg_3, arg_5)
    arg_6['display_name'] = parse_display_name(arg_0, arg_1, arg_2, arg_3, arg_5)
    arg_6['document_id'] = parse_document_id(arg_0, arg_1, arg_2, arg_3, arg_5, arg_4)

    return arg_6


def Func(arg_0, arg_1, arg_2, arg_3):
    """Parse the simple id for a variant

    Simple id is used as a human readable reference for a position, it is
    in no way unique.

    Args:
        chrom(str)
        pos(str)
        ref(str)
        alt(str)

    Returns:
        simple_id(str): The simple human readable variant id
    """
    return '_'.join([arg_0, arg_1, arg_2, arg_3])


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        """Fetches a single Func from database

        Use either the _id or combination of institute_id and display_name

        Args:
            Func_id(str): _id for a caes
            institute_id(str):
            display_name(str)

        Yields:
            A single Case
        """
        arg_4 = {}
        if arg_1:
            arg_4['_id'] = arg_1
            LOG.info("Fetching Func %s", arg_1)
        else:
            if not (arg_2 and arg_3):
                raise ValueError("Have to provide both institute_id and display_name")
            LOG.info("Fetching Func %s institute %s", arg_3, arg_2)
            arg_4['owner'] = arg_2
            arg_4['display_name'] = arg_3

        return arg_0.Func_collection.find_one(arg_4)


def Func(arg_0, arg_1):
        """Add a case to the database
           If the case already exists exception is raised

            Args:
                case_obj(Case)
        """
        if arg_0.case(arg_1['_id']):
            raise IntegrityError("Case %s already exists in database" % arg_1['_id'])

        return arg_0.case_collection.insert_one(arg_1)


def Func(arg_0, arg_1):
        """Replace a existing case with a new one

        Keeps the object id

        Args:
            case_obj(dict)

        Returns:
            updated_case(dict)
        """
        # Todo: Figure out and describe when this method destroys a case if invoked instead of
        # update_case
        LOG.info("Saving case %s", arg_1['_id'])
        # update updated_at of case to "today"

        arg_1['updated_at'] = datetime.datetime.now(),

        arg_2 = arg_0.case_collection.find_one_and_replace(
            {'_id': arg_1['_id']},
            arg_1,
            return_document=pymongo.ReturnDocument.AFTER
        )

        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """Submit an evaluation to the database

        Get all the relevant information, build a evaluation_obj

        Args:
            variant_obj(dict)
            user_obj(dict)
            institute_obj(dict)
            case_obj(dict)
            link(str): variant url
            criteria(list(dict)):

                [
            {
            'term': str,
            'comment': str,
            'links': list(str)
            },
            .
            .
        ]
        """
        arg_7 = arg_1['_id']
        arg_8 = arg_1['variant_id']
        arg_9 = arg_2['_id']
        arg_10 = arg_2.get('name', arg_2['_id'])
        arg_11 = arg_3['_id']
        arg_12 = arg_4['_id']

        arg_13 = [evluation_info['term'] for evluation_info in arg_6]

        arg_14 = get_acmg(arg_13)

        arg_15 = build_evaluation(
            arg_7=arg_7,
            arg_8=arg_8,
            arg_9=arg_9,
            arg_10=arg_10,
            arg_11=arg_11,
            arg_12=arg_12,
            arg_14=arg_14,
            arg_6=arg_6
        )

        arg_0._load_evaluation(arg_15)

        # Update the acmg classification for the variant:
        arg_0.update_acmg(arg_3, arg_4, arg_2, arg_5, arg_1, arg_14)
        return arg_14


def Func(arg_0):
    """Parse and massage the transcript information

    There could be multiple lines with information about the same transcript.
    This is why it is necessary to parse the transcripts first and then return a dictionary
    where all information has been merged.

    Args:
        transcript_lines(): This could be an iterable with strings or a pandas.DataFrame

    Returns:
        parsed_transcripts(dict): Map from enstid -> transcript info
    """
    LOG.info("Parsing transcripts")
    # Parse the transcripts, we need to check if it is a request or a file handle
    if isinstance(arg_0, DataFrame):
        arg_1 = parse_ensembl_transcript_request(arg_0)
    else:
        arg_1 = parse_ensembl_transcripts(arg_0)

    # Since there can be multiple lines with information about the same transcript
    # we store transcript information in a dictionary for now
    arg_2 = {}
    # Loop over the parsed transcripts
    for arg_3 in arg_1:
        arg_4 = arg_3['ensembl_transcript_id']
        arg_5 = arg_3['ensembl_gene_id']

        # Check if the transcript has been added
        # If not, create a new transcript
        if not arg_4 in arg_2:
            arg_6 = {
                'chrom': arg_3['chrom'],
                'transcript_start': arg_3['transcript_start'],
                'transcript_end': arg_3['transcript_end'],
                'mrna': set(),
                'mrna_predicted': set(),
                'nc_rna': set(),
                'ensembl_gene_id': arg_5,
                'ensembl_transcript_id': arg_4,
            }
            arg_2[arg_4] = arg_6

        arg_6 = arg_2[arg_4]
        # Add the ref seq information
        if arg_3.get('refseq_mrna_predicted'):
            arg_6['mrna_predicted'].add(arg_3['refseq_mrna_predicted'])
        if arg_3.get('refseq_mrna'):
            arg_6['mrna'].add(arg_3['refseq_mrna'])
        if arg_3.get('refseq_ncrna'):
            arg_6['nc_rna'].add(arg_3['refseq_ncrna'])

    return arg_2


def Func(arg_0):
    """Parse a dataframe with ensembl transcript information

    Args:
        res(pandas.DataFrame)

    Yields:
        transcript_info(dict)
    """
    LOG.info("Parsing transcripts from request")

    arg_1 = [
        'chrom',
        'ensembl_gene_id',
        'ensembl_transcript_id',
        'transcript_start',
        'transcript_end',
        'refseq_mrna',
        'refseq_mrna_predicted',
        'refseq_ncrna',
    ]
    # for res in result.itertuples():
    for arg_2, arg_3 in arg_0.iterrows():
        arg_4 = {}

        arg_4['chrom'] = str(arg_3['chromosome_name'])
        arg_4['ensembl_gene_id'] = arg_3['ensembl_gene_id']
        arg_4['ensembl_transcript_id'] = arg_3['ensembl_transcript_id']

        arg_4['transcript_start'] = int(arg_3['transcript_start'])
        arg_4['transcript_end'] = int(arg_3['transcript_end'])

        # Check if refseq data is annotated
        # Pandas represent missing data with nan
        for arg_5 in arg_1[-3:]:
            if type(arg_3[arg_5]) is float:
                arg_4[arg_5] = None
            else:
                arg_4[arg_5] = arg_3[arg_5]
        yield arg_4


def Func(arg_0, arg_1):
    """Parse an ensembl formated line

        Args:
            line(list): A list with ensembl gene info
            header(list): A list with the header info

        Returns:
            ensembl_info(dict): A dictionary with the relevant info
    """
    arg_0 = arg_0.rstrip().split('\t')
    arg_1 = [head.lower() for head in arg_1]
    arg_2 = dict(zip(arg_1, arg_0))

    arg_3 = {}

    for arg_4 in arg_2:
        arg_5 = arg_2[arg_4]

        if not arg_5:
            continue

        if 'chromosome' in arg_4:
            arg_3['chrom'] = arg_5

        if 'gene' in arg_4:
            if 'id' in arg_4:
                arg_3['ensembl_gene_id'] = arg_5
            elif 'start' in arg_4:
                arg_3['gene_start'] = int(arg_5)
            elif 'end' in arg_4:
                arg_3['gene_end'] = int(arg_5)

        if 'hgnc symbol' in arg_4:
            arg_3['hgnc_symbol'] = arg_5
        if "gene name" in arg_4:
            arg_3['hgnc_symbol'] = arg_5

        if 'hgnc id' in arg_4:
            arg_3['hgnc_id'] = int(arg_5.split(':')[-1])

        if 'transcript' in arg_4:
            if 'id' in arg_4:
                arg_3['ensembl_transcript_id'] = arg_5
            elif 'start' in arg_4:
                arg_3['transcript_start'] = int(arg_5)
            elif 'end' in arg_4:
                arg_3['transcript_end'] = int(arg_5)

        if 'exon' in arg_4:
            if 'start' in arg_4:
                arg_3['exon_start'] = int(arg_5)
            elif 'end' in arg_4:
                arg_3['exon_end'] = int(arg_5)
            elif 'rank' in arg_4:
                arg_3['exon_rank'] = int(arg_5)

        if 'utr' in arg_4:

            if 'start' in arg_4:
                if '5' in arg_4:
                    arg_3['utr_5_start'] = int(arg_5)
                elif '3' in arg_4:
                    arg_3['utr_3_start'] = int(arg_5)
            elif 'end' in arg_4:
                if '5' in arg_4:
                    arg_3['utr_5_end'] = int(arg_5)
                elif '3' in arg_4:
                    arg_3['utr_3_end'] = int(arg_5)

        if 'strand' in arg_4:
            arg_3['strand'] = int(arg_5)

        if 'refseq' in arg_4:
            if 'mrna' in arg_4:
                if 'predicted' in arg_4:
                    arg_3['refseq_mrna_predicted'] = arg_5
                else:
                    arg_3['refseq_mrna'] = arg_5

            if 'ncrna' in arg_4:
                arg_3['refseq_ncrna'] = arg_5

    return arg_3


def Func(arg_0):
    """Parse lines with ensembl formated genes

        This is designed to take a biomart dump with genes from ensembl.
        Mandatory columns are:
        'Gene ID' 'Chromosome' 'Gene Start' 'Gene End' 'HGNC symbol

        Args:
            lines(iterable(str)): An iterable with ensembl formated genes
        Yields:
            ensembl_gene(dict): A dictionary with the relevant information
    """
    LOG.info("Parsing ensembl genes from file")
    arg_1 = []
    for arg_2, arg_3 in enumerate(arg_0):

        # File allways start with a header line
        if arg_2 == 0:
            arg_1 = arg_3.rstrip().split('\t')
            continue
        # After that each line represents a gene

        yield parse_ensembl_line(arg_3, arg_1)


def Func(arg_0):
    """Parse lines with ensembl formated exons

        This is designed to take a biomart dump with exons from ensembl.
        Check documentation for spec for download

        Args:
            lines(iterable(str)): An iterable with ensembl formated exons
        Yields:
            ensembl_gene(dict): A dictionary with the relevant information
    """
    arg_1 = []
    LOG.debug("Parsing ensembl exons...")
    for arg_2, arg_3 in enumerate(arg_0):

        # File allways start with a header line
        if arg_2 == 0:
            arg_1 = arg_3.rstrip().split('\t')
            continue

        arg_4 = parse_ensembl_line(arg_3, arg_1)
        arg_5 = arg_4['chrom']
        arg_6 = arg_4['exon_start']
        arg_7 = arg_4['exon_end']
        arg_8 = arg_4['ensembl_transcript_id']
        arg_9 = arg_4['ensembl_gene_id']

        arg_10 = arg_4['exon_rank']
        arg_11 = arg_4['strand']

        # Recalculate start and stop (taking UTR regions into account for end exons)
        if arg_11 == 1:
            # highest position: start of exon or end of 5' UTR
            # If no 5' UTR make sure exon_start is allways choosen
            arg_6 = max(arg_6, arg_4.get('utr_5_end') or -1)
            # lowest position: end of exon or start of 3' UTR
            arg_7 = min(arg_7, arg_4.get('utr_3_start') or float('inf'))
        elif arg_11 == -1:
            # highest position: start of exon or end of 3' UTR
            arg_6 = max(arg_6, arg_4.get('utr_3_end') or -1)
            # lowest position: end of exon or start of 5' UTR
            arg_7 = min(arg_7, arg_4.get('utr_5_start') or float('inf'))

        arg_12 = "-".join([arg_5, str(arg_6), str(arg_7)])

        if arg_6 > arg_7:
            raise ValueError("ERROR: %s" % arg_12)
        arg_13 = {
            "exon_id": arg_12,
            "chrom": arg_5,
            "start": arg_6,
            "end": arg_7,
            "transcript": arg_8,
            "gene": arg_9,
            "rank": arg_10,
        }

        yield arg_13


def Func(arg_0):
    """Parse a dataframe with ensembl exon information

    Args:
        res(pandas.DataFrame)

    Yields:
        gene_info(dict)
    """
    arg_1 = [
        'chrom',
        'gene',
        'transcript',
        'exon_id',
        'exon_chrom_start',
        'exon_chrom_end',
        '5_utr_start',
        '5_utr_end',
        '3_utr_start',
        '3_utr_end',
        'strand',
        'rank'
    ]

    # for res in result.itertuples():
    for arg_2 in zip(arg_0['Chromosome/scaffold name'],
                   arg_0['Gene stable ID'],
                   arg_0['Transcript stable ID'],
                   arg_0['Exon stable ID'],
                   arg_0['Exon region start (bp)'],
                   arg_0['Exon region end (bp)'],
                   arg_0["5' UTR start"],
                   arg_0["5' UTR end"],
                   arg_0["3' UTR start"],
                   arg_0["3' UTR end"],
                   arg_0["Strand"],
                   arg_0["Exon rank in transcript"]):
        arg_3 = dict(zip(arg_1, arg_2))

        # Recalculate start and stop (taking UTR regions into account for end exons)
        if arg_3['strand'] == 1:
            # highest position: start of exon or end of 5' UTR
            # If no 5' UTR make sure exon_start is allways choosen
            arg_4 = max(arg_3['exon_chrom_start'], arg_3['5_utr_end'] or -1)
            # lowest position: end of exon or start of 3' UTR
            arg_5 = min(arg_3['exon_chrom_end'], arg_3['3_utr_start'] or float('inf'))
        elif arg_3['strand'] == -1:
            # highest position: start of exon or end of 3' UTR
            arg_4 = max(arg_3['exon_chrom_start'], arg_3['3_utr_end'] or -1)
            # lowest position: end of exon or start of 5' UTR
            arg_5 = min(arg_3['exon_chrom_end'], arg_3['5_utr_start'] or float('inf'))

        arg_3['start'] = arg_4
        arg_3['end'] = arg_5

        yield arg_3


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Initializes the log file in the proper format.

    Arguments:

        filename (str): Path to a file. Or None if logging is to
                         be disabled.
        loglevel (str): Determines the level of the log output.
    """
    arg_3 = '[%(asctime)s] %(levelname)-8s: %(name)-25s: %(message)s'
    arg_4 = logging.Formatter(arg_3)

    if arg_2:
        arg_0.setLevel(getattr(logging, arg_2))

    # We will always print warnings and higher to stderr
    arg_5 = logging.StreamHandler()
    arg_5.setLevel('WARNING')
    arg_5.setFormatter(arg_4)

    if arg_1:
        arg_6 = logging.FileHandler(arg_1, encoding='utf-8')
        if arg_2:
            arg_6.setLevel(getattr(logging, arg_2))
        arg_6.setFormatter(arg_4)
        arg_0.addHandler(arg_6)
    # If no logfile is provided we print all log messages that the user has
    # defined to stderr
    else:
        if arg_2:
            arg_5.setLevel(getattr(logging, arg_2))

    arg_0.addHandler(arg_5)


def Func(arg_0):
    """docstring for Func"""
    arg_1 = []
    for arg_2,arg_3 in enumerate(arg_0):
        arg_3 = arg_3.rstrip()
        if arg_3.startswith('#'):
            if arg_2 < 10:
                if arg_3.startswith('# Phenotype'):
                    arg_1 = arg_3[2:].split('\t')
        else:
            yield parse_omim_line(arg_3, arg_1)


def Func(arg_0):
    """Get a dictionary with phenotypes

    Use the mim numbers for phenotypes as keys and phenotype information as
    values.

    Args:
        genemap_lines(iterable(str))

    Returns:
        phenotypes_found(dict): A dictionary with mim_numbers as keys and
        dictionaries with phenotype information as values.

        {
             'description': str, # Description of the phenotype
             'hgnc_symbols': set(), # Associated hgnc symbols
             'inheritance': set(),  # Associated phenotypes
             'mim_number': int, # mim number of phenotype
        }
    """
    # Set with all omim numbers that are phenotypes
    # Parsed from mim2gene.txt
    arg_1 = set()

    arg_2 = {}

    # Genemap is a file with one entry per gene.
    # Each line hold a lot of information and in specific it
    # has information about the phenotypes that a gene is associated with
    # From this source we collect inheritane patterns and what hgnc symbols
    # a phenotype is associated with
    for arg_3 in parse_genemap2(arg_0):
        arg_4 = arg_3['hgnc_symbol']
        for arg_5 in arg_3['phenotypes']:
            arg_6 = arg_5['mim_number']
            if arg_6 in arg_2:
                arg_7 = arg_2[arg_6]
                arg_7['inheritance'] = arg_7['inheritance'].union(arg_5['inheritance'])
                arg_7['hgnc_symbols'].add(arg_4)
            else:
                arg_5['hgnc_symbols'] = set([arg_4])
                arg_2[arg_6] = arg_5

    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """Parse the omim files"""
    # if not (morbid and genemap and mim2gene, mim_titles):
    #     print("Please provide all files")
    #     context.abort()

    from scout.utils.handle import get_file_handle
    from pprint import pprint as pp

    print("Morbid file: %s" % arg_1)
    print("Genemap file: %s" % arg_2)
    print("mim2gene file: %s" % arg_3)
    print("MimTitles file: %s" % arg_4)

    if arg_1:
        arg_6 = get_file_handle(arg_1)
    if arg_2:
        arg_7 = get_file_handle(arg_2)
    if arg_3:
        arg_8 = get_file_handle(arg_3)
    if arg_4:
        arg_9 = get_file_handle(arg_4)

    arg_10 = get_mim_genes(arg_7, arg_8)
    for arg_11 in arg_10:
        if arg_11 == 'C10orf11':
            pp(arg_10[arg_11])

    arg_0.abort()
    if arg_5:
        if not arg_2:
            Funcck.echo("Please provide the genemap file")
            arg_0.abort()
        arg_5 = get_mim_phenotypes(arg_7)
        for arg_12,arg_13 in enumerate(arg_5):
            # pp(phenotypes[mim_term])
            pass

    print("Number of phenotypes found: %s" % arg_12)

    arg_0.abort()
    # hgnc_genes = get_mim_genes(genemap_handle, mim2gene_handle)
    # for hgnc_symbol in hgnc_genes:
    #     pp(hgnc_genes[hgnc_symbol])
    # phenotypes = get_mim_phenotypes(genemap_handle, mim2gene_handle, mimtitles_handle)
    # for mim_nr in phenotypes:
    #     pp(phenotypes[mim_nr])

    arg_14 = get_mim_genes(arg_7, arg_8)
    for arg_15 in arg_14:
        if arg_15 == 'OPA1':
            print(arg_14[arg_15])


def Func(arg_0):
    """Convert a string to number
    If int convert to int otherwise float

    If not possible return None
    """
    arg_1 = None
    if isint(arg_0):
        arg_1 = int(arg_0)
    elif isfloat(arg_0):
        arg_1 = float(arg_0)
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3=True, arg_4=None, arg_5=None, arg_6='happenings/partials/calendar/month_table.html'):
        """Return a formatted month as a table."""
        arg_7 = arg_0.get_context()
        arg_7['month_start_date'] = date(arg_0.yr, arg_0.mo, 1)
        arg_7['week_rows'] = []
        for arg_8 in arg_0.monthdays2calendar(arg_1, arg_2):
            arg_9 = []
            for arg_10, arg_11 in arg_8:
                arg_9.append(arg_0.formatday(arg_10, arg_11))
            arg_7['week_rows'].append(arg_9)

        arg_12, arg_13 = get_next_and_prev(arg_4)
        arg_14 = ('&' + '&'.join(arg_5)) if arg_5 else ''
        arg_7['prev_qs'] = mark_safe('?cal_prev=%d%s' % (arg_13, arg_14))
        arg_7['next_qs'] = mark_safe('?cal_next=%d%s' % (arg_12, arg_14))
        arg_7['withyear'] = arg_3
        return render_to_string(arg_6, arg_7)


def Func(arg_0, arg_1, arg_2):
        """Set some commonly used variables."""
        arg_0.wkday_not_today = '
' % (
            arg_0.cssclasses[arg_2])

        arg_0.wkday_today = (
            '
' % (
                arg_0.cssclasses[arg_2])
        )
        if URLS_NAMESPACE:
            arg_5 = '%s:day_list' % (URLS_NAMESPACE)
        else:
            arg_5 = 'day_list'

        arg_0.day_url = reverse(arg_5, args=(arg_0.yr, arg_0.mo, arg_1))
        arg_0.day = arg_1

        arg_0.anch = '%d' % (
            arg_0.day_url, arg_1
        )

        arg_0.end = '
	'


def Func(arg_0, arg_1, arg_2, arg_3=True):
        """
        Change colspan to "5", add "today" button, and return a month
        name as a table row.
        """
        arg_4 = month_name[arg_2]

        if isinstance(arg_4, six.binary_type) and arg_0.encoding:
            arg_4 = arg_4.decode(arg_0.encoding)

        if arg_3:
            arg_5 = u'%s %s' % (arg_4, arg_1)
        else:
            arg_5 = u'%s' % arg_4
        return ('
'
                '<button id="cal-today-btn" class="btn btn-small">'
                'Today</button> %s
' % arg_5)


def Func(arg_0):
        """Populate variables used to build popovers."""
        # when
        arg_1 = month_name[arg_0.mo]

        if isinstance(arg_1, six.binary_type) and arg_0.encoding:
            arg_1 = arg_1.decode('utf-8')

        arg_0.when = ('
When: ' + arg_1 + ' ' +
                     str(arg_0.day) + ', ' + arg_0.event.l_start_date.strftime(
                         LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') + ' - ' +
                     arg_0.event.l_end_date.strftime(LEGACY_CALENDAR_TIME_FORMAT).lstrip('0') +
                     '
')

        if arg_0.event.location.exists():  # where
            arg_0.where = '
Where: '
            for arg_4 in arg_0.event.location.all():
                arg_0.where += arg_4.name
            arg_0.where += '
'
        else:
            arg_0.where = ''

        # description
        arg_0.desc = '
Description: ' + arg_0.event.description[:100]
        arg_0.desc += ('...
' if len(arg_0.event.description) > 100
                      else '
')

        arg_0.event_url = arg_0.event.get_absolute_url()  # url
        arg_7 = LEGACY_CALENDAR_TIME_FORMAT if arg_0.event.l_start_date.minute else LEGACY_CALENDAR_HOUR_FORMAT
        arg_0.title2 = (arg_0.event.l_start_date.strftime(arg_7).lstrip('0') +
                       ' ' + arg_0.title)


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None, arg_4=None,
                   arg_5=None):
    """Parse metadata for a gene panel

    For historical reasons it is possible to include all information about a gene panel in the
    header of a panel file. This function parses the header.

    Args:
        panel_lines(iterable(str))

    Returns:
        panel_info(dict): Dictionary with panel information
    """
    arg_6 = {
        'panel_id': arg_1,
        'institute': arg_2,
        'version': arg_3,
        'date': arg_4,
        'display_name': arg_5,
    }

    if arg_0:
        for arg_7 in arg_0:
            arg_7 = arg_7.rstrip()
            if not arg_7.startswith('##'):
                break

            arg_8 = arg_7[2:].split('=')
            arg_9 = arg_8[0]
            arg_10 = arg_8[1]

            if not arg_6.get(arg_9):
                arg_6[arg_9] = arg_10

    arg_6['date'] = get_date(arg_6['date'])

    return arg_6


def Func(arg_0):
    """Parse a gene line with information from a panel file

        Args:
            gene_info(dict): dictionary with gene info

        Returns:
            gene(dict): A dictionary with the gene information
                {
                'hgnc_id': int,
                'hgnc_symbol': str,
                'disease_associated_transcripts': list(str),
                'inheritance_models': list(str),
                'mosaicism': bool,
                'reduced_penetrance': bool,
                'database_entry_version': str,
                }

    """
    arg_1 = {}
    # This is either hgnc id or hgnc symbol
    arg_2 = None

    arg_3 = None
    try:
        if 'hgnc_id' in arg_0:
            arg_3 = int(arg_0['hgnc_id'])
        elif 'hgnc_idnumber' in arg_0:
            arg_3 = int(arg_0['hgnc_idnumber'])
        elif 'hgncid' in arg_0:
            arg_3 = int(arg_0['hgncid'])
    except ValueError as e:
        raise SyntaxError("Invalid hgnc id: {0}".format(arg_3))

    arg_1['hgnc_id'] = arg_3
    arg_2 = arg_3

    arg_4 = None
    if 'hgnc_symbol' in arg_0:
        arg_4 = arg_0['hgnc_symbol']
    elif 'hgncsymbol' in arg_0:
        arg_4 = arg_0['hgncsymbol']
    elif 'symbol' in arg_0:
        arg_4 = arg_0['symbol']

    arg_1['hgnc_symbol'] = arg_4

    if not arg_2:
        if arg_4:
            arg_2 = arg_4
        else:
            raise SyntaxError("No gene identifier could be found")
    arg_1['identifier'] = arg_2
    # Disease associated transcripts is a ','-separated list of
    # manually curated transcripts
    arg_5 = ""
    if 'disease_associated_transcripts' in arg_0:
        arg_5 = arg_0['disease_associated_transcripts']
    elif 'disease_associated_transcript' in arg_0:
        arg_5 = arg_0['disease_associated_transcript']
    elif 'transcripts' in arg_0:
        arg_5 = arg_0['transcripts']

    arg_1['transcripts'] = [
            transcript.strip() for transcript in
            arg_5.split(',') if transcript
        ]

    # Genetic disease models is a ','-separated list of manually curated
    # inheritance patterns that are followed for a gene
    arg_6 = ""
    if 'genetic_disease_models' in arg_0:
        arg_6 = arg_0['genetic_disease_models']
    elif 'genetic_disease_model' in arg_0:
        arg_6 = arg_0['genetic_disease_model']
    elif 'inheritance_models' in arg_0:
        arg_6 = arg_0['inheritance_models']
    elif 'genetic_inheritance_models' in arg_0:
        arg_6 = arg_0['genetic_inheritance_models']

    arg_1['inheritance_models'] = [
        model.strip() for model in arg_6.split(',')
        if model.strip() in VALID_MODELS
    ]

    # If a gene is known to be associated with mosaicism this is annotated
    arg_1['mosaicism'] = True if arg_0.get('mosaicism') else False

    # If a gene is known to have reduced penetrance this is annotated
    arg_1['reduced_penetrance'] = True if arg_0.get('reduced_penetrance') else False

    # The database entry version is a way to track when a a gene was added or
    # modified, optional
    arg_1['database_entry_version'] = arg_0.get('database_entry_version')

    return arg_1


def Func(arg_0, arg_1='cust000', arg_2='test', arg_3='clinical', arg_4=arg_5.now(),
                     arg_7=1.0, arg_8=None, arg_9 = None):
    """Parse the panel info and return a gene panel

        Args:
            path(str): Path to panel file
            institute(str): Name of institute that owns the panel
            panel_id(str): Panel id
            date(datetime.datetime): Date of creation
            version(float)
            full_name(str): Option to have a long name

        Returns:
            gene_panel(dict)
    """
    LOG.info("Parsing gene panel %s", arg_2)
    arg_10 = {}

    arg_10['path'] = arg_0
    arg_10['type'] = arg_3
    arg_10['date'] = arg_4
    arg_10['panel_id'] = arg_2
    arg_10['institute'] = arg_1
    arg_7 = arg_7 or 1.0
    arg_10['version'] = float(arg_7)
    arg_10['display_name'] = arg_8 or arg_2

    if not arg_0:
        arg_11 = arg_9
    else:
        arg_11 = get_file_handle(arg_10['path'])
    arg_10['genes'] = parse_genes(gene_lines=arg_11)

    return arg_10


def Func(arg_0):
    """
    Update the Func terms in the database. Fetch the latest release and update terms.
    """
    LOG.info("Running scout update Func")
    arg_1 = arg_0.obj['adapter']

    LOG.info("Dropping HPO terms")
    arg_1.Func_term_collection.drop()
    LOG.debug("HPO terms dropped")

    load_Func_terms(arg_1)


def Func(arg_0, arg_1, **arg_2):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        return HttpResponse(
            arg_0.convert_context_to_json(arg_1),
            content_type='application/json',
            **arg_2
        )


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Get the year and month. First tries from kwargs, then from
        querystrings. If none, or if cal_ignore qs is specified,
        sets year and month to this year and this month.
        """
        arg_4 = c.get_now()
        arg_5 = arg_4.year
        arg_6 = arg_4.month + arg_1
        arg_7 = None

        if 'cal_ignore=true' not in arg_2:
            if 'year' and 'month' in arg_0.kwargs:  # try kwargs
                arg_5, arg_7 = map(
                    int, (arg_0.kwargs['year'], arg_0.kwargs['month'])
                )
                arg_6 = arg_7 + arg_1
            else:
                try:  # try querystring
                    arg_5 = int(arg_0.request.GET['cal_year'])
                    arg_7 = int(arg_0.request.GET['cal_month'])
                    arg_6 = arg_7 + arg_1
                except Exception:
                    pass
        # return the year and month, and any errors that may have occurred do
        # to an invalid month/year being given.
        return c.clean_year_month(arg_5, arg_6, arg_7)


def Func(arg_0, arg_1):
        """Check if any events are cancelled on the given date 'd'."""
        for arg_2 in arg_0.events:
            for arg_3 in arg_2.cancellations.all():
                if arg_3.date == arg_1:
                    arg_2.title += ' (CANCELLED)'


def Func(arg_0, arg_1):
        """Fetch a hpo term

        Args:
            hpo_id(str)

        Returns:
            hpo_obj(dict)
        """
        LOG.debug("Fetching hpo term %s", arg_1)

        return arg_0.Func_collection.find_one({'_id': arg_1})


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None):
        """Return all HPO terms

        If a query is sent Func will try to match with regex on term or
        description.

        Args:
            query(str): Part of a hpoterm or description
            hpo_term(str): Search for a specific hpo term
            limit(int): the number of desired results

        Returns:
            result(pymongo.Cursor): A cursor with hpo terms
        """
        arg_5 = {}
        arg_6 = None
        if arg_1:
            arg_5 = {'$or':
                [
                    {'hpo_id': {'$regex': arg_1, '$options':'i'}},
                    {'description': {'$regex': arg_1, '$options':'i'}},
                ]
            }
            arg_6 = arg_1
        elif arg_3:
            arg_7 = ''
            for arg_8,arg_9 in enumerate(arg_3.split(' ')):
                if arg_8 == 0:
                    arg_7 += arg_9
                else:
                    arg_7 += ' \"{0}\"'.format(arg_9)
            LOG.info("Search HPO terms with %s", arg_7)
            arg_5['$text'] = {'$search': arg_7}
            arg_6 = arg_3
        elif arg_2:
            arg_5['hpo_id'] = arg_2
            arg_6 = arg_2

        arg_4 = arg_4 or int(10e10)
        arg_10 = arg_0.hpo_term_collection.find(arg_5).limit(arg_4).sort('hpo_number',ASCENDING)

        LOG.info("Found {0} terms with search word {1}".format(arg_10.count(), arg_6))
        return arg_10


def Func(arg_0, arg_1=None):
        """Return all disease terms that overlaps a gene

            If no gene, return all disease terms

        Args:
            hgnc_id(int)

        Returns:
            iterable(dict): A list with all disease terms that match
        """
        arg_2 = {}
        if arg_1:
            LOG.debug("Fetching all diseases for gene %s", arg_1)
            arg_2['genes'] = arg_1
        else:
            LOG.info("Fetching all disease terms")

        return list(arg_0.disease_term_collection.find(arg_2))


def Func(arg_0, arg_1, **arg_2):
    r'''Beat tracking evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.Func.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='Func')[0]
    >>> est_ann = est_jam.search(namespace='Func')[0]
    >>> scores = jams.eval.Func(ref_ann, est_ann)
    '''

    arg_3 = 'Func'
    arg_0 = coerce_annotation(arg_0, arg_3)
    arg_1 = coerce_annotation(arg_1, arg_3)

    arg_4, arg_5 = arg_0.to_event_values()
    arg_6, arg_5 = arg_1.to_event_values()

    return mir_eval.Func.evaluate(arg_4, arg_6, **arg_2)


def Func(arg_0, arg_1, **arg_2):
    r'''Chord evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.Func.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='Func')[0]
    >>> est_ann = est_jam.search(namespace='Func')[0]
    >>> scores = jams.eval.Func(ref_ann, est_ann)
    '''

    arg_3 = 'Func'
    arg_0 = coerce_annotation(arg_0, arg_3)
    arg_1 = coerce_annotation(arg_1, arg_3)
    arg_4, arg_5 = arg_0.to_interval_values()
    arg_6, arg_7 = arg_1.to_interval_values()

    return mir_eval.Func.evaluate(arg_4, arg_5,
                                   arg_6, arg_7, **arg_2)


def Func(arg_0):
    '''Flatten a multi_segment annotation into mir_eval style.

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation in the `multi_segment` namespace

    Returns
    -------
    hier_intervalss : list
        A list of lists of intervals, ordered by increasing specificity.

    hier_labels : list
        A list of lists of labels, ordered by increasing specificity.
    '''

    arg_1, arg_2 = arg_0.to_interval_values()

    arg_3 = dict()

    for arg_4, arg_5 in zip(arg_1, arg_2):
        arg_6 = arg_5['level']
        if arg_6 not in arg_3:
            arg_3[arg_6] = dict(arg_1=list(), labels=list())

        arg_3[arg_6]['intervals'].append(arg_4)
        arg_3[arg_6]['labels'].append(arg_5['label'])

    arg_7 = sorted(list(arg_3.keys()))
    arg_8 = [arg_3[arg_6]['intervals'] for arg_6 in arg_7]
    arg_9 = [arg_3[arg_6]['labels'] for arg_6 in arg_7]

    return arg_8, arg_9


def Func(arg_0, arg_1, **arg_2):
    r'''Multi-level segmentation evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.Func.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='multi_segment')[0]
    >>> est_ann = est_jam.search(namespace='multi_segment')[0]
    >>> scores = jams.eval.Func(ref_ann, est_ann)
    '''
    arg_3 = 'multi_segment'
    arg_0 = coerce_annotation(arg_0, arg_3)
    arg_1 = coerce_annotation(arg_1, arg_3)
    arg_4, arg_5 = Func_flatten(arg_0)
    arg_6, arg_7 = Func_flatten(arg_1)

    return mir_eval.Func.evaluate(arg_4, arg_5,
                                       arg_6, arg_7,
                                       **arg_2)


def Func(arg_0, arg_1, **arg_2):
    r'''Melody extraction evaluation

    Parameters
    ----------
    ref : jams.Annotation
        Reference annotation object
    est : jams.Annotation
        Estimated annotation object
    kwargs
        Additional keyword arguments

    Returns
    -------
    scores : dict
        Dictionary of scores, where the key is the metric name (str) and
        the value is the (float) score achieved.

    See Also
    --------
    mir_eval.Func.evaluate

    Examples
    --------
    >>> # Load in the JAMS objects
    >>> ref_jam = jams.load('reference.jams')
    >>> est_jam = jams.load('estimated.jams')
    >>> # Select the first relevant annotations
    >>> ref_ann = ref_jam.search(namespace='pitch_contour')[0]
    >>> est_ann = est_jam.search(namespace='pitch_contour')[0]
    >>> scores = jams.eval.Func(ref_ann, est_ann)
    '''

    arg_3 = 'pitch_contour'
    arg_0 = coerce_annotation(arg_0, arg_3)
    arg_1 = coerce_annotation(arg_1, arg_3)

    arg_4, arg_5 = arg_0.to_event_values()
    arg_6, arg_7 = arg_1.to_event_values()

    arg_8 = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in arg_5])
    arg_9 = np.asarray([p['frequency'] * (-1)**(~p['voiced']) for p in arg_7])

    return mir_eval.Func.evaluate(arg_4, arg_8,
                                    arg_6, arg_9,
                                    **arg_2)


def Func(arg_0):
    '''Add a namespace definition to our working set.

    Namespace files consist of partial JSON schemas defining the behavior
    of the `value` and `confidence` fields of an Annotation.

    Parameters
    ----------
    filename : str
        Path to json file defining the namespace object
    '''
    with open(arg_0, mode='r') as fileobj:
        __NAMESPACE__.update(json.load(fileobj))


def Func(arg_0):
    '''Return the allowed Func for an enumerated namespace.

    Parameters
    ----------
    ns_key : str
        Namespace key identifier

    Returns
    -------
    Func : list

    Raises
    ------
    NamespaceError
        If `ns_key` is not found, or does not have enumerated Func

    Examples
    --------
    >>> jams.schema.Func('tag_gtzan')
    ['blues', 'classical', 'country', 'disco', 'hip-hop', 'jazz',
     'metal', 'pop', 'reggae', 'rock']
    '''

    if arg_0 not in __NAMESPACE__:
        raise NamespaceError('Unknown namespace: {:s}'.format(arg_0))

    if 'enum' not in __NAMESPACE__[arg_0]['value']:
        raise NamespaceError('Namespace {:s} is not enumerated'.format(arg_0))

    return copy.copy(__NAMESPACE__[arg_0]['value']['enum'])


def Func(arg_0):
    '''Get the dtypes associated with the value and confidence fields
    for a given namespace.

    Parameters
    ----------
    ns_key : str
        The namespace key in question

    Returns
    -------
    value_dtype, confidence_dtype : numpy.dtype
        Type identifiers for value and confidence fields.
    '''

    # First, get the schema
    if arg_0 not in __NAMESPACE__:
        raise NamespaceError('Unknown namespace: {:s}'.format(arg_0))

    arg_1 = __get_dtype(__NAMESPACE__[arg_0].get('value', {}))
    arg_2 = __get_dtype(__NAMESPACE__[arg_0].get('confidence', {}))

    return arg_1, arg_2


def Func():
    '''Print out a listing of available namespaces'''
    print('{:30s}\t{:40s}'.format('NAME', 'DESCRIPTION'))
    print('-' * 78)
    for arg_0 in sorted(__NAMESPACE__):
        arg_1 = __NAMESPACE__[arg_0]['description']
        arg_1 = (arg_1[:44] + '..') if len(arg_1) > 46 else arg_1
        print('{:30s}\t{:40s}'.format(arg_0, arg_1))


def Func():
    '''Load the schema file from the package.'''

    arg_0 = os.path.join(SCHEMA_DIR, 'jams_schema.json')

    arg_1 = None
    with open(resource_filename(__name__, arg_0), mode='r') as fdesc:
        arg_1 = json.load(fdesc)

    if arg_1 is None:
        raise JamsError('Unable to load JAMS schema')

    return arg_1


def Func(arg_0, arg_1):
    """Expand a list of relative paths to a give base directory.

    Parameters
    ----------
    base_dir : str
        The target base directory

    rel_paths : list (or list-like)
        Collection of relative path strings

    Returns
    -------
    expanded_paths : list
        `rel_paths` rooted at `base_dir`

    Examples
    --------
    >>> jams.util.Func('/data', ['audio', 'beat', 'seglab'])
    ['/data/audio', '/data/beat', '/data/seglab']

    """
    return [os.path.join(arg_0, os.path.normpath(arg_2)) for arg_2 in arg_1]


def Func(arg_0, arg_1=0o777):
    """Safely make a full directory path if it doesn't exist.

    Parameters
    ----------
    dpath : str
        Path of directory/directories to create

    mode : int [default=0777]
        Permissions for the new directories

    See also
    --------
    os.makedirs
    """
    if not os.path.exists(arg_0):
        os.makedirs(arg_0, arg_1=arg_1)


def Func(arg_0, arg_1):
    '''Get the metadata from a jam and an annotation, combined as a string.

    Parameters
    ----------
    jam : JAMS
        The jams object

    ann : Annotation
        An annotation object

    Returns
    -------
    comments : str
        The jam.file_metadata and ann.annotation_metadata, combined and serialized
    '''
    arg_2 = arg_0.file_metadata.__json__
    arg_3 = arg_1.annotation_metadata.__json__
    return json.dumps({'metadata': arg_2,
                       'annotation metadata': arg_3},
                      indent=2)


def Func(arg_0):
    '''Parse arguments from the command line'''
    arg_1 = argparse.ArgumentParser(description='Convert JAMS to .lab files')

    arg_1.add_argument('-c',
                        '--comma-separated',
                        dest='csv',
                        action='store_true',
                        default=False,
                        help='Output in .csv instead of .lab')

    arg_1.add_argument('--comment', dest='comment_char', type=str, default='#',
                        help='Comment character')

    arg_1.add_argument('-n',
                        '--namespace',
                        dest='namespaces',
                        nargs='+',
                        default=['.*'],
                        help='One or more namespaces to output.  Default is all.')

    arg_1.add_argument('jams_file',
                        help='Path to the input jams file')

    arg_1.add_argument('output_prefix', help='Prefix for output files')

    return vars(arg_1.parse_args(arg_0))


def Func(arg_0, arg_1):
    '''A decorator to register namespace conversions.

    Usage
    -----
    >>> @conversion('tag_open', 'tag_.*')
    ... def tag_to_open(annotation):
    ...     annotation.namespace = 'tag_open'
    ...     return annotation
    '''

    def register(arg_2):
        '''This decorator registers func as mapping source to target'''
        arg_3[arg_0][arg_1] = arg_2
        return arg_2

    return register


def Func(arg_0, arg_1):
    '''Convert a given annotation to the target namespace.

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation object

    target_namespace : str
        The target namespace

    Returns
    -------
    mapped_annotation : jams.Annotation
        if `annotation` already belongs to `target_namespace`, then
        it is returned directly.

        otherwise, `annotation` is copied and automatically Funced
        to the target namespace.

    Raises
    ------
    SchemaError
        if the input annotation fails to validate

    NamespaceError
        if no conversion is possible

    Examples
    --------
    Convert frequency measurements in Hz to MIDI

    >>> ann_midi = jams.Func(ann_hz, 'note_midi')

    And back to Hz

    >>> ann_hz2 = jams.Func(ann_midi, 'note_hz')
    '''

    # First, validate the input. If this fails, we can't auto-Func.
    arg_0.validate(strict=True)

    # If we're already in the target namespace, do nothing
    if arg_0.namespace == arg_1:
        return arg_0

    if arg_1 in __CONVERSION__:
        # Otherwise, make a copy to mangle
        arg_0 = deepcopy(arg_0)

        # Look for a way to map this namespace to the target
        for arg_2 in __CONVERSION__[arg_1]:
            if arg_0.search(namespace=arg_2):
                return __CONVERSION__[arg_1][arg_2](arg_0)

    # No conversion possible
    raise NamespaceError('Unable to Func annotation from namespace='
                         '"{0}" to "{1}"'.format(arg_0.namespace,
                                                 arg_1))


def Func(arg_0, arg_1):
    '''Test if an annotation can be mapped to a target namespace

    Parameters
    ----------
    annotation : jams.Annotation
        An annotation object

    target_namespace : str
        The target namespace

    Returns
    -------
    True
        if `annotation` can be automatically converted to
        `target_namespace`

    False
        otherwise
    '''

    # If we're already in the target namespace, do nothing
    if arg_0.namespace == arg_1:
        return True

    if arg_1 in __CONVERSION__:
        # Look for a way to map this namespace to the target
        for arg_2 in __CONVERSION__[arg_1]:
            if arg_0.search(namespace=arg_2):
                return True
    return False


def Func(arg_0):
    '''Convert a pitch_hz annotation to a contour'''
    arg_0.namespace = 'pitch_contour'
    arg_2 = arg_0.pop_data()

    for arg_3 in arg_2:
        arg_0.append(time=arg_3.time, duration=arg_3.duration,
                          confidence=arg_3.confidence,
                          value=dict(index=0,
                                     frequency=np.abs(arg_3.value),
                                     voiced=arg_3.value > 0))
    return arg_0


def Func(arg_0):
    '''Convert a pitch_hz annotation to pitch_midi'''

    arg_0.namespace = 'note_midi'

    arg_2 = arg_0.pop_data()

    for arg_3 in arg_2:
        arg_0.append(time=arg_3.time, duration=arg_3.duration,
                          confidence=arg_3.confidence,
                          value=12 * (np.log2(arg_3.value) - np.log2(440.0)) + 69)

    return arg_0


def Func(arg_0):
    '''Convert scaper annotations to tag_open'''

    arg_0.namespace = 'tag_open'

    arg_2 = arg_0.pop_data()
    for arg_3 in arg_2:
        arg_0.append(time=arg_3.time, duration=arg_3.duration,
                          confidence=arg_3.confidence, value=arg_3.value['label'])

    return arg_0


def Func(arg_0, arg_1):
    '''This is a decorator which can be used to mark functions
    as Func.

    It will result in a warning being emitted when the function is used.'''

    def __wrapper(arg_2, *arg_3, **arg_4):
        '''Warn the user, and then proceed.'''
        arg_5 = six.get_function_code(arg_2)
        warnings.warn_explicit(
            "{:s}.{:s}\n\tDeprecated as of JAMS version {:s}."
            "\n\tIt will be removed in JAMS version {:s}."
            .format(arg_2.__module__, arg_2.__name__,
                    arg_0, arg_1),
            category=DeprecationWarning,
            filename=arg_5.co_filename,
            lineno=arg_5.co_firstlineno + 1
        )
        return arg_2(*arg_3, **arg_4)

    return decorator(__wrapper)


def Func(arg_0, arg_1, arg_2='.'):
    '''Pop a prefix from a query string.

    Parameters
    ----------
    query : str
        The query string

    prefix : str
        The prefix string to pop, if it exists

    sep : str
        The string to separate fields

    Returns
    -------
    popped : str
        `query` with a `prefix` removed from the front (if found)
        or `query` if the prefix was not found

    Examples
    --------
    >>> Func('Annotation.namespace', 'Annotation')
    'namespace'
    >>> Func('namespace', 'Annotation')
    'namespace'

    '''

    arg_3 = arg_0.split(arg_2)

    if arg_3[0] == arg_1:
        arg_3 = arg_3[1:]

    return arg_2.join(arg_3)


def Func(arg_0, arg_1):
    '''Test if a string matches a query.

    Parameters
    ----------
    string : str
        The string to test

    query : string, callable, or object
        Either a regular expression, callable function, or object.

    Returns
    -------
    match : bool
        `True` if:
        - `query` is a callable and `query(string) == True`
        - `query` is a regular expression and `re.match(query, string)`
        - or `string == query` for any other query

        `False` otherwise

    '''

    if six.callable(arg_1):
        return arg_1(arg_0)

    elif (isinstance(arg_1, six.string_types) and
          isinstance(arg_0, six.string_types)):
        return re.match(arg_1, arg_0) is not None

    else:
        return arg_1 == arg_0


def Func(arg_0, arg_1=0):
    '''Helper function to format repr strings for JObjects and friends.

    Parameters
    ----------
    obj
        The object to repr

    indent : int >= 0
        indent each new line by `indent` spaces

    Returns
    -------
    r : str
        If `obj` has a `__Func__` method, it is used.

        If `obj` is a `SortedKeyList`, then it returns a description
        of the length of the list.

        Otherwise, `repr(obj)`.
    '''
    if hasattr(arg_0, '__Func__'):
        arg_2 = arg_0.__Func__()
    elif isinstance(arg_0, SortedKeyList):
        arg_2 = '<{:d} observations>'.format(len(arg_0))
    else:
        arg_2 = repr(arg_0)

    return arg_2.replace('\n', '\n' + ' ' * arg_1)


def Func(arg_0, **arg_1):
        '''Update the attributes of a JObject.

        Parameters
        ----------
        kwargs
            Keyword arguments of the form `attribute=new_value`

        Examples
        --------
        >>> J = jams.JObject(foo=5)
        >>> J.dumps()
        '{"foo": 5}'
        >>> J.Func(bar='baz')
        >>> J.dumps()
        '{"foo": 5, "bar": "baz"}'
        '''
        for arg_2, arg_3 in six.iteritems(arg_1):
            setattr(arg_0, arg_2, arg_3)


def Func(arg_0, arg_1=True):
        '''Validate a JObject against its schema

        Parameters
        ----------
        strict : bool
            Enforce strict schema validation

        Returns
        -------
        valid : bool
            True if the jam Funcs
            False if not, and `strict==False`

        Raises
        ------
        SchemaError
            If `strict==True` and `jam` fails validation
        '''

        arg_2 = True

        try:
            jsonschema.Func(arg_0.__json__, arg_0.__schema__)

        except jsonschema.ValidationError as invalid:
            if arg_1:
                raise SchemaError(str(invalid))
            else:
                warnings.warn(str(invalid))

            arg_2 = False

        return arg_2


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None):
        '''Append an observation to the data field

        Parameters
        ----------
        time : float >= 0
        duration : float >= 0
            The time and duration of the new observation, in seconds
        value
        confidence
            The value and confidence of the new observations.

            Types and values should conform to the namespace of the
            Annotation object.

        Examples
        --------
        >>> ann = jams.Annotation(namespace='chord')
        >>> ann.Func(time=3, duration=2, value='E#')
        '''

        arg_0.data.add(Observation(arg_1=float(arg_1),
                                  arg_2=float(arg_2),
                                  arg_3=arg_3,
                                  arg_4=arg_4))


def Func(arg_0, arg_1=True):
        '''Validate this annotation object against the JAMS schema,
        and its data against the namespace schema.

        Parameters
        ----------
        strict : bool
            If `True`, then schema violations will cause an Exception.
            If `False`, then schema violations will issue a warning.

        Returns
        -------
        valid : bool
            `True` if the object conforms to schema.
            `False` if the object fails to conform to schema,
            but `strict == False`.

        Raises
        ------
        SchemaError
            If `strict == True` and the object fails validation

        See Also
        --------
        JObject.Func
        '''

        # Get the schema for this annotation
        arg_2 = schema.namespace_array(arg_0.namespace)

        arg_3 = True

        try:
            jsonschema.Func(arg_0.__json_light__(data=False),
                                schema.JAMS_SCHEMA)

            # Func each record in the frame
            arg_4 = [serialize_obj(obs) for obs in arg_0.data]
            jsonschema.Func(arg_4, arg_2)

        except jsonschema.ValidationError as invalid:
            if arg_1:
                raise SchemaError(str(invalid))
            else:
                warnings.warn(str(invalid))
            arg_3 = False

        return arg_3