import torch
from delineation.utils import *

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

from torch import nn

def soft_skeletonize(x, thresh_width=1):
    '''
    Differenciable aproximation of morphological skelitonization operaton
    thresh_width - maximal expected width of vessel
    '''
    for i in range(thresh_width):
        min_pool_x = torch.nn.functional.max_pool2d(x*-1, (3, 3), 1, 1)*-1
        contour = torch.nn.functional.relu(torch.nn.functional.max_pool2d(min_pool_x, (3, 3), 1, 1) - min_pool_x)
        x = torch.nn.functional.relu(x - contour)
    return x

def norm_intersection(center_line, vessel):
    '''
    inputs shape  (batch, channel, height, width)
    intersection formalized by first ares
    x - suppose to be centerline of vessel (pred or gt) and y - is vessel (pred or gt)
    '''
    smooth = 1.
    clf = center_line.view(*center_line.shape[:2], -1)
    vf = vessel.view(*vessel.shape[:2], -1)
    intersection = (clf * vf).sum(-1)
    return (intersection + smooth) / (clf.sum(-1) + smooth)

def soft_cldice_loss(pred, target, target_skeleton=None):
    '''
    inputs shape  (batch, channel, height, width).
    calculate clDice loss
    Because pred and target at moment of loss calculation will be a torch tensors
    it is preferable to calculate target_skeleton on the step of batch forming,
    when it will be in numpy array format by means of opencv
    '''
    pred = pred.sigmoid()
    cl_pred = soft_skeletonize(pred)
    if target_skeleton is None:
        target_skeleton = soft_skeletonize(target)
    iflat = norm_intersection(cl_pred, target)
    tflat = norm_intersection(target_skeleton, pred)
    intersection = iflat * tflat
    return 1 -((2. * intersection) /
              (iflat + tflat))

def bce_segmentation_loss(projection, gt):
    criterion = torch.nn.BCEWithLogitsLoss()
    loss = criterion(projection, gt)
    return loss

def initia_loss_func(seg_l, lgt, seg_r, rgt):

    loss = 0.5 * bce_segmentation_loss(seg_l, lgt) \
           + 0.5 * bce_segmentation_loss(seg_r, rgt)

    return loss

class dice_cl_loss(torch.nn.Module):
    def __init__(self, ignore_index=250):

        super().__init__()

    def forward(self, seg_l, lgt, seg_r, rgt):

        _loss = 0.5 * soft_cldice_loss(seg_l, lgt).mean() + 0.5 * soft_cldice_loss(seg_r, rgt).mean()

        return _loss

class binary_cross_entropy_one(torch.nn.Module):
    def __init__(self, ignore_index=250):

        super().__init__()

        self.left_bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, seg_l, lgt):
        _loss = self.left_bce_logits(seg_l, lgt)
        return _loss

class binary_cross_entropy(torch.nn.Module):
    def __init__(self, ignore_index=250):

        super().__init__()

        self.left_bce_logits = torch.nn.BCEWithLogitsLoss()
        self.right_bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, seg_l, lgt, seg_r, rgt):

        _loss = 0.5 * self.left_bce_logits(seg_l, lgt) + 0.5 * self.right_bce_logits(seg_r, rgt)

        return _loss

class smooth_l1_masked_disparity(torch.nn.Module):
    def __init__(self):

        super().__init__()

    def forward(self, dl, seg_r, dlgt, lgt):

        mask = lgt > 0
        print('Max: {} Min: {}'.format(dlgt.unsqueeze(1)[mask].max(),
                                       dlgt.unsqueeze(1)[mask].min()))

        print('Predicted Max: {} Min: {}'.format(dl[mask].max(),
                                       dl[mask].min()))

        print(dl[mask].squeeze()[0:10])
        print(dlgt.unsqueeze(1)[mask].squeeze()[0:10])

        _loss = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')

        return _loss

class warp_only(torch.nn.Module):
    def __init__(self):

        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, dl, seg_r, dlgt, lgt):

        mask = lgt > 0
        recon_l =  F.sigmoid(warp(seg_r, dl))

        recon_l = recon_l*mask

        _loss_recon = F.smooth_l1_loss(recon_l[mask], lgt[mask], reduction='mean')

        return _loss_recon

class warp_only_joint(torch.nn.Module):
    def __init__(self):

        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, l_aug, r_aug, l_gt_aug, r_gt_aug, dl, seg_r, seg_l, dlgt, lgt, rgt):

        loss_seg1 = 0.5 * bce_segmentation_loss(l_aug, l_gt_aug) \
               + 0.5 * bce_segmentation_loss(r_aug, l_gt_aug)

        recon_l =  warp(seg_r, dl)*seg_l
        _loss_recon = F.smooth_l1_loss(recon_l, lgt, reduction='mean')

        return 0.5*loss_seg1 + _loss_recon

class smooth_l1_masked_disparity_joint(torch.nn.Module):
    def __init__(self):

        super().__init__()

    def forward(self, l_aug, r_aug, l_gt_aug, r_gt_aug, dl, seg_r, seg_l, dlgt, lgt, rgt):

        loss_seg1 = 0.5 * bce_segmentation_loss(l_aug, l_gt_aug) \
               + 0.5 * bce_segmentation_loss(r_aug, l_gt_aug)

        mask = lgt > 0
        print('Max: {} Min: {}'.format(dlgt.unsqueeze(1)[mask].max(),
                                       dlgt.unsqueeze(1)[mask].min()))

        print('Predicted Max: {} Min: {}'.format(dl[mask].max(),
                                       dl[mask].min()))

        print(dl[mask].squeeze()[0:10])
        print(dlgt.unsqueeze(1)[mask].squeeze()[0:10])

        _loss = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')
        _loss[torch.isnan(_loss)] = 0

        return 0.5*loss_seg1+ _loss

class smooth_l1_disparity_and_edge_warp_joint(torch.nn.Module):

    def __init__(self):

        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, l_aug, r_aug, l_gt_aug, r_gt_aug, dl, seg_r, seg_l, dlgt, lgt, rgt):

        loss_seg1 = 0.5 * bce_segmentation_loss(l_aug, l_gt_aug) \
               + 0.5 * bce_segmentation_loss(r_aug, l_gt_aug)

        mask = lgt > 0

        recon_l =  warp(F.sigmoid(seg_r), dl)*seg_l

        _loss_recon = F.smooth_l1_loss(recon_l, lgt, reduction='mean')

        _loss = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')
        _loss[torch.isnan(_loss)] = 0

        return 0.5*loss_seg1+_loss+ 0.5*_loss_recon

class smooth_l1_disparity_and_edge_warp(torch.nn.Module):
    def __init__(self):

        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, dl, seg_r, dlgt, lgt):

        mask = lgt > 0
        recon_l =  F.sigmoid(warp(seg_r, dl))
     #   recon_l_gt = F.sigmoid(warp(seg_r, dlgt.unsqueeze(1)))

        # recon_l_gt = recon_l_gt*mask
        recon_l = recon_l*mask
        _loss_recon = F.smooth_l1_loss(recon_l[mask], lgt[mask], reduction='mean')

        _loss = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')
        _loss[torch.isnan(_loss)] = 0

        return _loss+ 0.5*_loss_recon

class smooth_l1_disparity(torch.nn.Module):
    def __init__(self):

        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, dl, seg_r, dlgt, lgt):

        mask = lgt > 0
        recon_l =  F.sigmoid(warp(seg_r, dl))

        # recon_l_gt = recon_l_gt*mask
        recon_l = recon_l*mask

        _loss_recon = F.smooth_l1_loss(recon_l[mask], lgt[mask], reduction='mean')

        _loss = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')
        _loss[torch.isnan(_loss)] = 0

        return _loss

class smooth_l1_disparity_and_bce(torch.nn.Module):
    def __init__(self):
        super().__init__()

        self.bce_logits = torch.nn.BCEWithLogitsLoss()

    def forward(self, dl, dlgt, sl, lgt):
        mask = lgt > 0

        _loss_seg = self.bce_logits(sl, lgt)
        _loss_seg[torch.isnan(_loss_seg)] = 0

        _loss_disp = F.smooth_l1_loss(dl[mask], dlgt.unsqueeze(1)[mask], reduction='mean')
        _loss_disp[torch.isnan(_loss_disp)] = 0

        _loss = _loss_disp + 2 * _loss_seg
        return _loss, _loss_disp, _loss_seg


from match import Match
from match_list import MatchList
from summoner_id import Summoner
import csv
import os
import pandas as pd
import time

stats_available = ['win', 'kills', 'deaths', 'assists', 'largestKillingSpree', 'largestMultiKill', 'killingSprees',
                   'longestTimeSpentLiving', 'doubleKills', 'tripleKills', 'quadraKills', 'pentaKills',
                   'totalDamageDealt', 'magicDamageDealt', 'physicalDamageDealt', 'trueDamageDealt',
                   'totalDamageDealtToChampions', 'magicDamageDealtToChampions', 'physicalDamageDealtToChampions',
                   'trueDamageDealtToChampions', 'totalHeal', 'damageSelfMitigated', 'timeCCingOthers',
                   'totalDamageTaken', 'goldEarned', 'goldSpent', 'totalTimeCrowdControlDealt']

# Intro asking for needed information
API_KEY = os.environ['API_KEY']

summoner = Summoner(api_key=API_KEY)

# get summoner name
ign = input('What is you League in-game name?: ')
summoner.get_info(ign)
account_id = summoner.account_id

match_list = MatchList(API_KEY, account_id)
match = Match(API_KEY)

def create_new_dataset():
    choice1 = True
    match_listing = []
    while choice1:
        choice = input('Type "all" if you want to see all ARAM matches, or "select" for a selection: ').lower()

        # Selecting type of search
        if choice == 'select':
            choice_start = input('Where would you like to start the selection? (most recent is "0"): ')
            choice_end = input('Where would you like to end the selection? (not inclusive): ')
            match_listing = match_list.get_select_matches(choice_start, choice_end)
            choice1 = False
        elif choice == 'all':
            match_listing = match_list.get_all_matches()
            choice1 = False
        else:
            print('Please enter a valid answer.')

    match_listing = match.find_match_ids(match_listing)
    match_stats = []
    counter = 0

    # loop for finding info for each match
    for item in match_listing:
        # # finding info for particular match and adding initial info
        match_info = match.match_info(item['gameId'])
        participant_num = ''
        stat = {'game_id': item['gameId'],
                'game_duration': match_info.get('gameDuration')}

        # # finding player number in json data
        for y in range(10):
            if match_info['participantIdentities'][y]['player'].get('accountId') == account_id:
                participant_num = y
                break
        # # getting summoner stats
        requested_summoner = match_info['participants'][participant_num]
        stat.update(match.find_summoner_stats(requested_summoner, *stats_available))

        # # append to match_stats list
        match_stats.append(stat)

        counter += 1
        if counter == 100:
            time.sleep(125)
            counter = 0
        else:
            time.sleep(0.5)

    # write data into .csv file
    csv_header = ['game_id', 'game_duration', 'champion', *stats_available]

    with open('aram-data1.csv', newline="", mode='w', encoding='utf8') as file:
        writer = csv.DictWriter(file, fieldnames=csv_header)
        writer.writeheader()
        for x in range(0, len(match_stats)):
            stat_to_write = {header: match_stats[x][header] for header in csv_header}
            writer.writerow(stat_to_write)

    return print('\nTask Completed.')

def update_dataset():
    try:
        data = pd.read_csv('aram-data1.csv')
    except FileNotFoundError:
        return print('File Not Found. Try creating a dataset instead.')
    else:
        most_recent_game = data.game_id[0]

    choice2 = True
    match_listing = []
    while choice2:
        choice = input('Type "all" if you want to select all ARAM matches, or "select" for a selection: ').lower()

        # Selecting type of search
        if choice == 'select':
            choice_start = input('Where would you like to start the selection? (most recent is "0"): ')
            choice_end = input('Where would you like to end the selection? (not inclusive): ')
            match_listing = match_list.get_select_matches(choice_start, choice_end)
            choice2 = False
        elif choice == 'all':
            match_listing = match_list.get_all_matches()
            choice2 = False
        else:
            print('Please enter a valid answer.')

    match_listing = match.find_match_ids(match_listing)

    # checking if the most recent game in dataset is present in the search
    recent_game_index = match_listing.index({'gameId': most_recent_game})
    if recent_game_index:
        match_listing = match_listing[:recent_game_index]

    match_stats = []

    # loop for finding info for each match
    for item in match_listing:
        # # finding info for particular match and adding initial info
        match_info = match.match_info(item['gameId'])
        participant_num = ''
        stat = {'game_id': match_info['gameId'],
                'game_duration': match_info['gameDuration']}

        # # finding player number in json data
        for y in range(10):
            if match_info['participantIdentities'][y]['player']['accountId'] == account_id:
                participant_num = y
                time.sleep(1.5)
                break
        # # getting summoner stats
        requested_summoner = match_info['participants'][participant_num]
        stat.update(match.find_summoner_stats(requested_summoner, *stats_available))

        # # append to match_stats list
        match_stats.append(stat)

    # write data into .csv file
    csv_header = ['game_id', 'game_duration', 'champion', *stats_available]
    # creating a csv -> dataframe for the new stats
    with open('aram-data-transfer.csv', newline="", mode='w', encoding='utf8') as file:
        writer = csv.DictWriter(file, fieldnames=csv_header)
        writer.writeheader()
        for x in range(0, len(match_stats)):
            stat_to_write = {header: match_stats[x][header] for header in csv_header}
            writer.writerow(stat_to_write)

    # appending old stats to new stats so that the recent stat is on top
    data_new = pd.read_csv('aram-data-transfer.csv')
    data_new = data_new.append(data, ignore_index=True)

    # replacing the original file with one up-to-date and deleting the in-between file
    data_new.to_csv('aram-data1.csv')
    os.remove('aram-data-transfer.csv')

    return print('\nTask Completed.')

new_dataset_loop = True
while new_dataset_loop:
    path1 = input('Do you want to create a new Aram stat dataset? (y/n): ')
    if path1 == 'y':
        create_new_dataset()
        new_dataset_loop = False
    elif path1 == 'n':
        new_dataset_loop = False
    else:
        print('Please enter a valid answer.')

update_loop = True
while update_loop:
    path2 = input('\nDo you want to update you Aram stats? (y/n): ').lower()
    if path2 == 'y':
        update_dataset()
        update_loop = False
    elif path2 == 'n':
        update_loop = False
    else:
        print('Please enter a valid answer.')


from urllib.parse import urlparse

from normalizers.registry import (
    register_facets_normalizer,
    register_nlp_preprocessor,
)
from normalizers.lib.normalizers import (
    update_from_theme_taxonomy,
    common_normalizer,
    check_blacklist_whitelist,
    add_counts,
)
from normalizers.lib.nlp import common_preprocess
import logging

logger = logging.getLogger(__file__)

@register_facets_normalizer("eionet")
def normalize_eionet(doc, config):
    logger.info("NORMALIZE EIONET")
    logger.info(doc["raw_value"].get("@id", ""))
    logger.info(doc["raw_value"].get("@type", ""))
    logger.info(doc)
    ct_normalize_config = config["site"].get("normalize", {})

    if not check_blacklist_whitelist(
        doc,
        ct_normalize_config.get("blacklist", []),
        ct_normalize_config.get("whitelist", []),
    ):
        logger.info("blacklisted")
        return None
    logger.info("whitelisted")

    normalized_doc = common_normalizer(doc, config)
    if not normalized_doc:
        return None

    normalized_doc["issued"] = doc["raw_value"].get("publication_date", normalized_doc.get("issued"))

    normalized_doc["cluster_name"] = "etc"

    doc_loc = urlparse(normalized_doc["id"]).path
    doc_loc_parts = doc_loc.strip("/").split("/")
    if doc_loc_parts[0] == "etcs" and len(doc_loc_parts) > 1:
        if doc_loc_parts[1] == "etc-atni":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term2", "term29"]

        if doc_loc_parts[1] == "etc-bd":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term4"]

        if doc_loc_parts[1] == "etc-cca":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term10"]

        if doc_loc_parts[1] == "etc-cme":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term11", "term14"]

        if doc_loc_parts[1] == "etc-icm":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term45", "term34"]

        if doc_loc_parts[1] == "etc-uls":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term23", "term35"]

        if doc_loc_parts[1] == "etc-wmge":
            #            normalized_doc["cluster_name"] = doc_loc_parts[1]
            normalized_doc["topic"] = ["term44"]

    normalized_doc["topic"] = update_from_theme_taxonomy(
        normalized_doc["topic"],
        config.get("full_config", {}).get("theme_taxonomy", {}),
    )

    normalized_doc = add_counts(normalized_doc)
    return normalized_doc

@register_nlp_preprocessor("eionet")
def preprocess_eionet(doc, config):
    dict_doc = common_preprocess(doc, config)

    return dict_doc


import numpy as np
from flask import Flask, request, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict',methods=["POST"])
def predict():
    '''
    For rendering results on HTML GUI
    '''
    int_features = [int(x) for x in request.form.values()]
    final_features = [np.array(int_features)]
    prediction = model.predict(final_features)

    if prediction == 0:
        output = "Extremely Weak. Please go to a doctor to check."
    elif prediction == 1:
        output = "Weak"
    elif prediction == 2:
        output = "Normal"
    elif prediction == 3:
        output = "Overweight"
    elif prediction == 4:
        output = "Obesity. Please go to a doctor to check."
    elif prediction == 5:
        output = "Extreme Obesity. Please go to a doctor to check."
    return render_template("index.html", prediction_text = output)

if __name__ == "__main__":
    app.run(port = 5000, debug=True)


import pint
import pytest

import eradiate
from eradiate import unit_registry as ureg
from eradiate.contexts import SpectralContext
from eradiate.radprops import AFGL1986RadProfile

@pytest.fixture
def test_ckd_spectral_ctx_1650():
    spectral_cfg = eradiate.scenes.measure._core.CKDMeasureSpectralConfig(bins="1650")
    bindex = eradiate.ckd.Bindex(bin=spectral_cfg.bins[0], index=3)
    return SpectralContext.new(bindex=bindex, bin_set="10nm")

@pytest.fixture
def test_ckd_spectral_ctx_550():
    spectral_cfg = eradiate.scenes.measure._core.CKDMeasureSpectralConfig(bins="550")
    bindex = eradiate.ckd.Bindex(bin=spectral_cfg.bins[0], index=3)
    return SpectralContext.new(bindex=bindex, bin_set="10nm")

@pytest.mark.parametrize("model_id", ["midlatitude_summer", "us_standard"])
def test_afgl_1986_rad_profile_default_ckd(mode_ckd, model_id):
    """
    Collision coefficient evaluation methods return pint.Quantity objects.
    """
    p = AFGL1986RadProfile(dict(model_id=model_id))

    spectral_ctx = SpectralContext.new(bin_set="10nm")
    for field in ["albedo", "sigma_a", "sigma_t"]:
        x = getattr(p, f"eval_{field}_ckd")(
            spectral_ctx.bindex, bin_set_id=spectral_ctx.bin_set.id
        )
        assert isinstance(x, ureg.Quantity)

    sigma_s = p.eval_sigma_s_ckd(spectral_ctx.bindex)
    assert isinstance(sigma_s, ureg.Quantity)

@pytest.mark.parametrize("model_id", ["midlatitude_summer", "us_standard"])
def test_afgl_1986_rad_profile_has_absorption_default(
    mode_ckd, test_ckd_spectral_ctx_1650, model_id
):
    """
    Default value for 'has_absorption' is True, hence the absorption
    coefficient is computed and is not zero everywhere at 1650 nm.
    """
    p = AFGL1986RadProfile(dict(model_id=model_id))
    assert p.has_absorption
    ds = p.eval_dataset(test_ckd_spectral_ctx_1650)
    assert (ds.sigma_a.values != 0.0).any()

@pytest.mark.parametrize("model_id", ["midlatitude_summer", "us_standard"])
def test_afgl_1986_rad_profile_has_absorption_true(
    mode_ckd, test_ckd_spectral_ctx_1650, model_id
):
    """
    When 'has_absorption' is True, the absorption coefficient is computed
    and is not zero everywhere at 1650 nm.
    """
    p = AFGL1986RadProfile(thermoprops=dict(model_id=model_id), has_absorption=True)
    assert p.has_absorption
    ds = p.eval_dataset(test_ckd_spectral_ctx_1650)
    assert (ds.sigma_a.values != 0.0).any()

@pytest.mark.parametrize("model_id", ["midlatitude_summer", "us_standard"])
def test_afgl_1986_rad_profile_has_absorption_false(
    mode_ckd, test_ckd_spectral_ctx_1650, model_id
):
    """
    When 'has_absorption' is False, the absorption coefficient is not
    computed and is zero everywhere.
    """
    p = AFGL1986RadProfile(thermoprops=dict(model_id=model_id), has_absorption=False)
    assert not p.has_absorption
    ds = p.eval_dataset(test_ckd_spectral_ctx_1650)
    assert (ds.sigma_a.values == 0.0).all()

def test_afgl_1986_rad_profile_has_scattering_default(
    mode_ckd, test_ckd_spectral_ctx_550
):
    """
    Default value for 'has_scattering' is True, hence the absorption
    coefficient is computed and is not zero everywhere at 550 nm.
    """
    p = AFGL1986RadProfile()
    assert p.has_scattering
    ds = p.eval_dataset(test_ckd_spectral_ctx_550)
    assert (ds.sigma_s.values != 0.0).any()

def test_afgl_1986_rad_profile_has_scattering_true(mode_ckd, test_ckd_spectral_ctx_550):
    """
    When 'has_scattering' is True, the scattering coefficient is computed
    and is not zero everywhere at 550 nm.
    """
    p = AFGL1986RadProfile(has_scattering=True)
    assert p.has_scattering
    ds = p.eval_dataset(test_ckd_spectral_ctx_550)
    assert (ds.sigma_s.values != 0.0).any()

def test_afgl_1986_rad_profile_has_scattering_false(
    mode_ckd, test_ckd_spectral_ctx_550
):
    """
    When 'has_scattering' is False, the scattering coefficient is not
    computed and is zero everywhere.
    """
    p = AFGL1986RadProfile(has_scattering=False)
    assert not p.has_scattering
    ds = p.eval_dataset(test_ckd_spectral_ctx_550)
    assert (ds.sigma_s.values == 0.0).all()

@pytest.mark.parametrize(
    "model_id",
    [
        "tropical",
        "midlatitude_summer",
        "midlatitude_winter",
        "subarctic_summer",
        "subarctic_winter",
        "us_standard",
    ],
)
def test_afgl_1986_rad_profile_model_id(mode_ckd, model_id):
    """
    All models are supported in ckd mode.
    """
    AFGL1986RadProfile(thermoprops=dict(model_id=model_id))

@pytest.mark.parametrize(
    "molecule",
    ["N2O", "CO", "CH4", "O2"],
)
def test_afgl_1986_rad_profile_concentrations_ckd_not_implemented(mode_ckd, molecule):
    """
    Concentrations rescaling is not implemented for molecules other than
    H2O and O3 in CKD mode.
    """
    with pytest.raises(NotImplementedError):
        AFGL1986RadProfile(
            thermoprops=dict(concentrations={molecule: 0.0 * ureg.dimensionless})
        )

@pytest.mark.parametrize(
    "bin", ["280", "550", "790", "1040", "1270", "1590", "2220", "2400"]
)
@pytest.mark.parametrize("model_id", ["midlatitude_summer", "us_standard"])
def test_afgl_1986_rad_profile_ckd_10nm(mode_ckd, bin, model_id):
    """
    Can evaluate absorption coefficient.
    """
    p = AFGL1986RadProfile(thermoprops=dict(model_id=model_id))
    bin = eradiate.scenes.measure._core.CKDMeasureSpectralConfig(bins=bin).bins[0]
    bindex = eradiate.ckd.Bindex(bin=bin, index=3)
    spectral_ctx = SpectralContext.new(bindex=bindex, bin_set="10nm")
    assert isinstance(p.eval_sigma_a(spectral_ctx), pint.Quantity)


import pytest

def test_assembly_from_related_datasets(testapp, base_reference_epigenome, base_experiment_submitted, hg19_file, GRCh38_file):
    # If only original file is present in series, assembly should be ['hg19']
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'] == ['hg19']
    # Adding a related_dataset with a file in GRCh38 should now give it both ['hg19', 'GRCh38']
    testapp.patch_json(base_reference_epigenome['@id'], {'related_datasets': [base_experiment_submitted['@id']]})
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'].sort() == ['hg19', 'GRCh38'].sort()
    # Setting the experiment in related_dataset to delete it should exclude its assembly from the calculation
    testapp.patch_json(base_experiment_submitted['@id'], {'status': 'deleted'})
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'] == ['hg19']

def test_assay_single_cell_rna_series(testapp, base_single_cell_series):
    res = testapp.get(base_single_cell_series['@id'] + '@@index-data')
    assert sorted(res.json['object']['assay_term_name']) == ["RNA-seq"]

def test_gene_silencing_series(testapp, base_gene_silencing_series):
    res = testapp.get(base_gene_silencing_series['@id'] + '@@index-data')
    assert sorted(res.json['object']['assay_term_name']) == ["RNA-seq"]

def test_assay_differentiation_series(testapp, base_differentiation_series):
    res = testapp.get(base_differentiation_series['@id'] + '@@index-data')
    assert sorted(res.json['object']['assay_term_name']) == ['RNA-seq']

def test_assay_pulse_chase_time_series(testapp, base_pulse_chase_time_series):
    res = testapp.get(base_pulse_chase_time_series['@id'] + '@@index-data')
    assert sorted(res.json['object']['assay_term_name']) == ['RNA-seq']

def test_assay_type_single_cell_rna_series(testapp, single_cell_series):
    assay_slims = testapp.get(single_cell_series['@id'] + '@@index-data').json['object']['assay_slims']
    assert len(assay_slims) == 2
    assert 'Single cell' in assay_slims
    assert 'Transcription' in assay_slims

def test_biosample_summary_from_related_datasets(testapp,
    treated_differentiation_series,
    experiment_1,
    experiment_2,
    donor_1,
    donor_2,
    biosample_1,
    biosample_2,
    library_1,
    library_2,
    treatment_12,
    treatment_with_duration_amount_units,
    replicate_1_1,
    replicate_2_1,
    heart,
    liver,
    crispr_deletion_1
):
    testapp.patch_json(
        biosample_1['@id'],
        {
            'donor': donor_1['@id'],
            'treatments': [treatment_12['@id']],
            'biosample_ontology': heart['uuid']
        }
    )
    testapp.patch_json(
        biosample_2['@id'],
        {
            'donor': donor_2['@id'],
            'biosample_ontology': liver['uuid'],
            'treatments': [treatment_with_duration_amount_units['@id']]
        }
    )
    testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
    testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
    testapp.patch_json(
        replicate_1_1['@id'],
        {'library': library_1['@id'], 'experiment': experiment_1['@id']}
    )
    testapp.patch_json(experiment_1['@id'], {'biosample_ontology': heart['uuid']})
    testapp.patch_json(
        replicate_2_1['@id'],
        {'library': library_2['@id'], 'experiment': experiment_2['@id']}
    )
    testapp.patch_json(experiment_2['@id'], {'biosample_ontology': liver['uuid']})
    res = testapp.get(treated_differentiation_series['@id']+'@@index-data')
    assert res.json['object']['biosample_summary'] == 'Homo sapiens heart tissue treated with estradiol'

    testapp.patch_json(
        treated_differentiation_series['@id'],
        {'related_datasets': [experiment_1['@id'], experiment_2['@id']]}
    )
    res = testapp.get(treated_differentiation_series['@id']+'@@index-data')
    biosample_summary = testapp.get(treated_differentiation_series['@id']+'@@index-data').json['object']['biosample_summary']
    assert 'heart tissue' and 'liver tissue' and 'treated with' and 'ethanol' and 'estradiol' in biosample_summary

    testapp.patch_json(
        biosample_2['@id'],
        {
            'biosample_ontology': heart['uuid'],
        }
    )
    testapp.patch_json(experiment_2['@id'], {'biosample_ontology': heart['uuid']})
    res = testapp.get(treated_differentiation_series['@id']+'@@index-data')
    biosample_summary = testapp.get(treated_differentiation_series['@id']+'@@index-data').json['object']['biosample_summary']
    assert 'heart tissue treated with' and 'ethanol' and 'estradiol' in biosample_summary

    testapp.patch_json(
        biosample_2['@id'],
        {
            'genetic_modifications': [crispr_deletion_1['uuid']],
        }
    )
    res = testapp.get(treated_differentiation_series['@id']+'@@index-data')
    biosample_summary = testapp.get(treated_differentiation_series['@id']+'@@index-data').json['object']['biosample_summary']
    assert 'heart tissue treated with' and 'ethanol' and 'estradiol' and \
        'genetically modified (deletion) using CRISPR targeting ATF4' in biosample_summary

def test_assay_collection_series(testapp, base_collection_series):
    res = testapp.get(base_collection_series['@id'] + '@@index-data')
    assert sorted(res.json['object']['assay_term_name']) == ['MPRA']


import csv
import numpy as np

class Csv:
    def transformCsvToMatrix(csvFile: csv):
        numpy_array = np.loadtxt(open("../systemExamples/data/" + csvFile + ".csv"), delimiter=",", dtype = "float")

        rows = np.shape(numpy_array)[0]
        cols = np.shape(numpy_array)[1]
        result = np.ndarray((rows, cols), dtype = "float")

        for x in range(0, cols):
            for y in range(0, rows):
                result[y][x] = float(numpy_array[y,x])

        return result

    def transformComplexCsvToMatrix(csvFile: csv):
        numpy_array = np.loadtxt(open("../systemExamples/data/" + csvFile + ".csv"), delimiter=",", dtype = "str")

        rows = np.shape(numpy_array)[0]
        result = np.ndarray((rows, 1), dtype = "complex")

        for x in range(0, rows):
            numpy_array[x] = numpy_array[x].replace('i', 'j')
            result[x] = complex(numpy_array[x])

        return result

    def transformMatrixToCVS(A: np.ndarray, systemName, matrixName):
        np.savetxt("../results/" + systemName + "_reduced_" + matrixName + ".csv", A, fmt="%f", delimiter=",")

    def transformComplexMatrixToCVS(A: np.ndarray, systemName, matrixName):
        np.savetxt("../results/" + systemName + "_reduced_" + matrixName + ".csv", A, delimiter=",")


import requests
import time
import pandas as pd
from pprint import pprint
from bs4 import BeautifulSoup

class NikeScrape():

    def __init__(self, browser, dbEngine) -> None:

        self.browser = browser
        self.dbEngine = dbEngine

        self.SCROLL_PAUSE_TIME = 5

        self.product_categories = []
        self.products = []
        self.product_styles = []
        self.product_images = []

    def get_categories(self):
        """method to fetch categories from nike store"""
        url = 'https://www.nike.com/in/w/sale-3yaep'

        page = requests.get(url)
        soup = BeautifulSoup(page.content, 'html.parser')

        categories = soup.find_all('div', class_='categories')
        categories = categories[0].find_all('a')

        category_id = 1

        for category in categories:
            product_category = {
                'name': category.get_text(),
                '_link': category.get('href'),
                'id': category_id
            }
            self.product_categories.append(product_category)
            print(f'---{product_category["id"]} {product_category["name"]}---')
            category_id += 1

    def get_products(self):
        """method to fetch products of each category"""
        p_count = 1

        for category in self.product_categories:
            self.browser.get(category['_link'])
            self.scroll()

            category_soup = BeautifulSoup(self.browser.page_source)
            products = category_soup.find_all('div', class_='product-card')

            for product in products:
                main_link = product.find_all(
                    'a', class_='product-card__link-overlay')
                name = product.find_all(
                    'div', class_='product-card__title')[0].get_text()
                price = product.find_all(
                    'div', class_='product-price is--current-price css-s56yt7')[0].get_text()
                price_in_number = price[1:].split(',')
                short_description = product.find_all(
                    'div', class_='product-card__subtitle')[0].get_text()
                p = {
                    'product_category_id': category['id'],
                    'name': name,
                    '_link': main_link[0].get('href'),
                    'id': p_count,
                    'price': int(''.join(price_in_number)),
                    'short_description': short_description,
                    'long_description': None
                }
                self.products.append(p)
                print(f'---{p["id"]} {p["name"]}---')
                p_count += 1

    def scroll(self):
        """function to scroll to end of the page"""

        last_height = self.browser.execute_script(
            "return document.body.scrollHeight")

        while True:
            # Scroll down to bottom
            self.browser.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")

            # Wait to load page
            time.sleep(self.SCROLL_PAUSE_TIME)

            # Calculate new scroll height and compare with last scroll height
            new_height = self.browser.execute_script(
                "return document.body.scrollHeight")
            if new_height == last_height:
                break
            last_height = new_height

    def get_product_styles(self):
        """method to fetch product styles of each products"""
        product_style_id = 1

        self.product_image_id = 1

        for product in self.products:
            # open the page of the product
            self.browser.get(product['_link'])

            product_soup = BeautifulSoup(self.browser.page_source)
            product_description = product_soup.find_all('div', class_='description-preview')
            if product_description:
                long_description = product_description[0].find_all('p')[0].get_text()
                product['long_description'] = long_description

            styles_container = product_soup.find_all('div', class_='colorway-images')
            if styles_container:
                styles = styles_container[0]
                styles = styles.find_all('a')

                for style in styles:
                    # open different styles
                    self.browser.get(style.get('href'))
                    self.scroll()

                    style_soup = BeautifulSoup(self.browser.page_source)
                    color = style_soup.find_all(
                        'li', class_='description-preview__color-description')[0].get_text()
                    color_processed = color.split(':')[1][1:]
                    style = style_soup.find_all(
                        'li', class_='description-preview__style-color')[0].get_text()
                    style_processed = style.split(':')[1][1:]
                    ps = {
                        'id': product_style_id,
                        'product_id': product['id'],
                        'colour': color_processed,
                        'style_name': style_processed
                    }
                    self.product_styles.append(ps)
                    print(f'---{ps["id"]} {ps["colour"]} {ps["style_name"]}---')

                    self.get_product_images(style_soup, product_style_id)

                    product_style_id += 1

    def get_product_images(self, style_soup, product_style_id):
        """method to fetch images of different styles"""
        product_images = style_soup.find_all('div', class_='css-du206p')

        for image in product_images:
            picture_tag = image.find_all('picture')[1]
            img_tag = picture_tag.find_all('img')[0]
            # print(img_tag)
            if img_tag.has_attr('src'):
                img_url = img_tag['src']
                product_image = {
                    'id': self.product_image_id,
                    'product_style_id': product_style_id,
                    'image_url': img_url
                }
                self.product_images.append(product_image)
                print(f'---{product_image["id"]} {product_image["image_url"]}---')
                self.product_image_id += 1

    def save_to_db(self):
        df_product_categories = pd.DataFrame(self.product_categories)
        df_product_categories.drop('_link', 1, inplace=True)
        df_product_categories.to_sql(con=self.dbEngine, name='product_categories',
                                     if_exists='append', index=False)

        df_products = pd.DataFrame(self.products)
        df_products.drop('_link', 1, inplace=True)
        df_products.to_sql(con=self.dbEngine, name='products',
                           if_exists='append', index=False)

        df_product_styles = pd.DataFrame(self.product_styles)
        df_product_styles.to_sql(con=self.dbEngine, name='product_styles',
                                 if_exists='append', index=False)

        df_product_images = pd.DataFrame(self.product_images)
        df_product_images.to_sql(con=self.dbEngine, name='product_images',
                                 if_exists='append', index=False)


# -*- coding: cp1252 -*-

import uictrl as ui
from libsimpa import *
import xml.etree.ElementTree as ET
import os

def extractReceiverPositionFromXml(xmlFilePath):
    tree = ET.parse(xmlFilePath)
    root = tree.getroot()

    receivers_data = []

    def toNum(val):
        return float(val.replace(",", "."))

    for receiver_group in root.iter('recepteursp'):
        for receiver in receiver_group.iter('recepteur_ponctuel'):
            receivers_data.append([receiver.attrib["name"], toNum(receiver.attrib["x"]), toNum(receiver.attrib["y"]),
                                   toNum(receiver.attrib["z"])])

    # sort receiver by x coordinate

    receivers_data.sort(key=lambda item: item[1])

    return receivers_data

def GetMixedLevel(folderwxid):
    """
     Retourne un tableau contenant le niveau sonore global et toute bande des récepteurs ponctuels d'un dossier
     folderwxid identifiant wxid de l'élément dossier contenant les récepteurs ponctuels.
    """
    i_cols=[]
    myfrequency_labels=[]
    #folder devient l'objet dossier
    recplist=[]
    folder=ui.element(folderwxid)
    # retrieve computation result main folder location
    folderpath = ui.e_file(folder.getinfos()["parentid"]).buildfullpath()
    recpPosition = extractReceiverPositionFromXml(os.path.join(folderpath, 'config.xml'))

    for child in folder.childs():
        if child[1]==ui.element_type.ELEMENT_TYPE_REPORT_FOLDER:
            recplist.append(child[0])
    #Pour chaque récepteur on demande a l'application les données traitées du fichier ( niveau sonore et cumuls )
    intensityElements = {}
    for idrecp in recplist:
        #recp devient l'objet ayant comme indice idrecp (entier)
        parent=ui.element(idrecp)
        #application.sendevent(pere,idevent.IDEVENT_RELOAD_FOLDER)
        receiverName=parent.getinfos()["label"]
        #on recupere les données calculées
        elid = parent.getelementbylibelle('Punctual receiver intensity')
        if elid != -1:
            intensity=ui.element(elid)
            intensityElements[receiverName] = intensity

    for receiverInfo in recpPosition:
        receiverName, rx, ry, rz = receiverInfo
        if receiverName in intensityElements:
            intensity = intensityElements[receiverName]
            #on stocke dans gridspl le tableau des niveaux de pression
            gridparam=ui.application.getdataarray(intensity)
            values=gridparam[-1][1:]
            #retrieve the last row
            if len(myfrequency_labels)==0:
                myfrequency_labels=list(gridparam[0][1:])
                myfrequency_labels.insert(0, "z")
                myfrequency_labels.insert(0, "y")
                myfrequency_labels.insert(0, "x")
                myfrequency_labels.insert(0, "")
            myReceiverRow = [receiverName,rx,ry,rz]
            for idxyz in range(len(values)):
                I=values[idxyz]*1
                myReceiverRow.append(I)
            i_cols.append(myReceiverRow)
    i_cols.insert(0,myfrequency_labels)
    return i_cols
def SaveLevel(tab,path):
    #Creation de l'objet qui lit et ecris les fichier gabe
    gabewriter=Gabe_rw(len(tab))
    labelcol=stringarray()
    for cell in tab[0][1:]:
        labelcol.append(cell.encode('cp1252'))
    gabewriter.AppendStrCol(labelcol, "label")
    for col in tab[1:]:
        datacol=floatarray()
        for cell in col[1:]:
            datacol.append(float(cell))
        gabewriter.AppendFloatCol(datacol,str(col[0]))
    gabewriter.Save(path.encode('cp1252'))

def dofusion(folderwxid, path):
    arraydata=GetMixedLevel(folderwxid)
    SaveLevel(zip(*arraydata),path)
    #raffraichie l'arbre complet
    ui.application.sendevent(ui.element(ui.element(ui.application.getrootreport()).childs()[0][0]),ui.idevent.IDEVENT_RELOAD_FOLDER)

class manager:
    def __init__(self):
        self.GetD=ui.application.register_event(self.OnDFusion)
    def getmenu(self,typeel,idel,menu):
        el=ui.element(idel)
        infos=el.getinfos()
        if infos["name"]==u"Punctual receivers":
            menu.insert(0,())
            menu.insert(0,(u"Compute Intensity all",self.GetD))
            return True
        else:
            return False
    def OnDFusion(self,idel):
        grp=ui.e_file(idel)
        dofusion(idel,grp.buildfullpath()+ui._("TousInt")+".gabe")
ui.application.register_menu_manager(ui.element_type.ELEMENT_TYPE_REPORT_FOLDER, manager())


from tkinter import *
from tkinter.ttk import *
import sqlite3

class Win_Infrastructure:
    def __init__(self, driver):
        self.driver = driver

    # Function to manage infrastructure
    def open_inf(self, root):
        # Create infrastructure window
        win = Toplevel(root)
        win.title("Infrastructure")
        # Rezise patient window
        win.geometry("1600x900")

        #======================================================================================================
        #============================================= Rooms =================================================
        #======================================================================================================
        # Databases
        # Create a database or connect to one
        conn = sqlite3.connect("hospital.db")

        # Create cursor
        c = conn.cursor()

        # Create Treeview Frame
        tree1_frame = Frame(win)
        tree1_frame.pack()

        # Add some style
        style2 = Style()
        style2.configure("Treeview",
                rowheight = 15)

        # Treeview scrollbar
        tree1_scroll = Scrollbar(tree1_frame)
        tree1_scroll.pack(side=RIGHT, fill= Y)

        # Create Treeview
        my_tree1 = Treeview(tree1_frame, yscrollcommand= tree1_scroll.set, selectmode='extended')

        # Pack to the screen
        my_tree1.pack()

        # Configure the scrollbar
        tree1_scroll.config(command=my_tree1.yview)

        # Define our columns
        my_tree1['columns'] = ("ID", "Name")

        # Formate our columns
        my_tree1.column("#0", width = 0, stretch = NO)
        my_tree1.column("ID", anchor = W, width =100)
        my_tree1.column("Name", anchor = CENTER, width = 200)

        # Create Headings
        my_tree1.heading("#0", text = "", anchor = CENTER)
        my_tree1.heading("ID", text = "ID", anchor=CENTER)
        my_tree1.heading("Name", text = "Name", anchor=CENTER)

        # Create striped row tags
        my_tree1.tag_configure("oddrow", background= "white")
        my_tree1.tag_configure("evenrow", background= "lightblue")

        # Room Record Frame
        add_frame = LabelFrame(win, text = "Room Record")
        add_frame.pack(fill="x", expand="yes", padx= 20)

        id1 = Label(add_frame, text="ID")
        id1.grid(row=0, column=0, padx= 10, pady= 5)

        name1 = Label(add_frame, text="Name")
        name1.grid(row=0, column = 1, padx= 10, pady= 5)

        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        #~~~~~~~~~~~~~~~~~~~ Entry ~~~~~~~~~~~~~~~~~~~~~~~~~
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # Room ID
        id1_box = Entry(add_frame)
        id1_box.grid(row=1, column=0, padx= 10, pady= 5)

        # Room Name
        name1_box = Entry(add_frame)
        name1_box.grid(row=1, column=1, padx= 10, pady= 5)

        # Select Record
        def select_record1(e):
            # Clear boxes
            id1_box.delete(0, END)
            name1_box.delete(0, END)

            # Grab record Number
            selected = my_tree1.focus()

            # Grab record values
            values = my_tree1.item(selected, 'values')

            # Output to entry boxes
            id1_box.insert(0, values[0])
            name1_box.insert(0, values[1])

        # Update Record
        def update_record1():

            #Grab the record Number
            selected = my_tree1.focus()

            # Update record
            my_tree1.item(selected, text='', values=(id1_box.get(),name1_box.get()))

            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            c.execute("""UPDATE rooms SET
                    r_id = :r_id,
                    r_name = :r_name

                    WHERE r_id = :r_id""",
                    {
                        'r_id' : id1_box.get(),
                        'r_name': name1_box.get()

                    }
                    )

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Pull data before running program
            query_database1()

        # Add record
        def add_record1():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            # Add New Record
            c.execute("INSERT INTO rooms (r_id, r_name) Values (:r_id, :r_name)",
            {
                'r_id' : id1_box.get(),
                'r_name' : name1_box.get()
            }
            )

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear boxes
            id1_box.delete(0, END)
            name1_box.delete(0, END)

            # Clear The Treeview Table
            my_tree1.delete(*my_tree1.get_children())

            # Run to pull data from database on start
            query_database1()

        # Show records upon running program
        def query_database1():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            # Query the database
            c.execute("SELECT * FROM rooms")
            records = c.fetchall()

            # Loop Thru Results
            global count
            count = 0
            for record in records:
                if count % 2 == 0:
                    my_tree1.insert(parent='', index='end', iid= count , text=f'count', values=(record[0], record[1]) , tags= ("evenrow",))
                else:
                    my_tree1.insert(parent='', index='end', iid= count , text=f'count', values=(record[0], record[1]) , tags= ("oddrow",))
                count += 1

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

        # Remove all
        def remove_all1():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            for record in my_tree1.get_children():
                my_tree1.delete(record)

            c.execute("DELETE from rooms")
            # Remove data away from database here

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree1.delete(*my_tree1.get_children())

            # Run to pull data from database on start
            query_database1()

        # Remove one selected
        def remove_one1():
            x = my_tree1.selection()[0]
            my_tree1.delete(x)

            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            c.execute("DELETE from rooms WHERE r_id=" + room_id_box.get())

            # Clear boxes
            id1_box.delete(0, END)
            name1_box.delete(0, END)

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree1.delete(*my_tree1.get_children())

            # Run to pull data from database on start
            query_database1()

        # Remove many selected
        def remove_many1():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            x = my_tree1.selection()
            for record in x:
                my_tree1.delete(record)
                c.execute("DELETE from rooms WHERE r_id=" + record[0])

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree1.delete(*my_tree1.get_children())

            # Run to pull data from database on start
            query_database1()

        btn_frame1 = LabelFrame(win, text= "Room Command")
        btn_frame1.pack(fill ="x", expand="yes", padx=20)

        # Buttons
        add_record1 = Button(btn_frame1, text="Add Record", command= add_record1)
        add_record1.grid(row= 0 , column= 0, padx= 10, pady= 5)

        # Update Records
        update_record = Button(btn_frame1, text = "Update Record", command= update_record1)
        update_record.grid(row = 0, column= 1, padx= 10, pady= 5)

        # Remove all
        remove_all1 = Button(btn_frame1, text = "Remove All Record", command = remove_all1)
        remove_all1.grid(row = 0, column= 2, padx= 10, pady= 5)

        # Remove one
        remove_one1 = Button(btn_frame1, text= "Remove One Selected", command=remove_one1)
        remove_one1.grid(row= 0, column= 3, padx= 10, pady= 5)

        # Remove many selected
        remove_many1 = Button(btn_frame1, text = "Remove Many Selected", command= remove_many1)
        remove_many1.grid(row = 0, column= 4, padx= 10, pady= 5)

        # Bind the treeview
        my_tree1.bind("<ButtonRelease-1>", select_record1)

        # Pull data before running program
        query_database1()

        #======================================================================================================
        #============================================= Beds =================================================
        #======================================================================================================

        # Create Treeview Frame
        tree2_frame = Frame(win)
        tree2_frame.pack()

        # Treeview scrollbar
        tree2_scroll = Scrollbar(tree2_frame)
        tree2_scroll.pack(side=RIGHT, fill= Y)

        # Create Treeview
        my_tree2 = Treeview(tree2_frame, yscrollcommand= tree2_scroll.set, selectmode='extended')

        # Pack to the screen
        my_tree2.pack()

        # Configure the scrollbar
        tree2_scroll.config(command=my_tree2.yview)

        # Define our columns
        my_tree2['columns'] = ("Bed ID", "Room Name", "Room ID", "Patient ID")

        # Formate our columns
        my_tree2.column("#0", width = 0, stretch = NO)
        my_tree2.column("Bed ID", anchor = W, width =100)
        my_tree2.column("Room Name", anchor = CENTER, width = 200)
        my_tree2.column("Room ID", anchor = W, width = 200)
        my_tree2.column("Patient ID", anchor = W, width = 100)

        # Create Headings
        my_tree2.heading("#0", text = "", anchor = CENTER)
        my_tree2.heading("Bed ID", text = "Bed ID", anchor=CENTER)
        my_tree2.heading("Room Name", text = "Room Name", anchor=CENTER)
        my_tree2.heading("Room ID", text = "Room ID", anchor=CENTER)
        my_tree2.heading("Patient ID", text = "Patient ID", anchor=CENTER)

        # Create striped row tags
        my_tree2.tag_configure("oddrow", background= "white")
        my_tree2.tag_configure("evenrow", background= "lightblue")

        my_tree2.pack(pady= 10)

        add_frame2 = LabelFrame(win, text= "Bed Record")
        add_frame2.pack(fill="x", expand="yes", padx= 20)

        bed_id = Label(add_frame2, text="Bed ID")
        bed_id.grid(row=0, column=0)

        room_name = Label(add_frame2, text="Room Name")
        room_name.grid(row=0, column = 1)

        room_id = Label(add_frame2, text="Room ID")
        room_id.grid(row=0, column = 2)

        patient_id = Label(add_frame2, text = "Patient ID")
        patient_id.grid(row=0, column = 3)

        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        #~~~~~~~~~~~~~~~~~~~ Entry ~~~~~~~~~~~~~~~~~~~~~~~~~
        #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # ID
        bed_id_box = Entry(add_frame2)
        bed_id_box.grid(row=1, column=0, padx= 10, pady= 5)

        # Room Name
        room_name_box = Entry(add_frame2)
        room_name_box.grid(row=1, column=1, padx= 10, pady= 5)

        # Room ID
        room_id_box = Entry(add_frame2)
        room_id_box.grid(row=1, column=2, padx= 10, pady= 5)

        # Patient ID
        patient_id_box = Entry(add_frame2)
        patient_id_box.grid(row=1, column=3, padx= 10, pady= 5)

        # Select Record
        def select_record2(e):
            # Clear boxes
            bed_id_box.delete(0, END)
            room_name_box.delete(0, END)
            room_id_box.delete(0, END)
            patient_id_box.delete(0, END)

            # Grab record Number
            selected = my_tree2.focus()

            # Grab record values
            values = my_tree2.item(selected, 'values')

            # Output to entry boxes
            bed_id_box.insert(0, values[0])
            room_name_box.insert(0, values[1])
            room_id_box.insert(0, values[2])
            patient_id_box.insert(0, values[3])

        # Update Record
        def update_record2():

            #Grab the record Number
            selected = my_tree2.focus()

            # Update record
            my_tree2.item(selected, text='', values=(bed_id_box.get(),room_name_box.get(), room_id_box.get(), patient_id_box.get()))

            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            # Still lack of foreign key!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            c.execute("""UPDATE beds SET
                    bed_id = :bed_id,
                    bed_r_name = :bed_r_name,
                    bed_r_id = :bed_r_id,
                    bed_p_id = :bed_p_id,

                    WHERE bed_id = :bed_id""",
                    {
                        'bed_id' : bed_id_box.get(),
                        'bed_r_name': room_name_box.get(),
                        'bed_r_id' : room_id_box.get(),
                        'bed_p_id' : patient_id_box.get(),

                    }
                    )

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Pull data before running program
            query_database2()

        # Add record
        def add_record2():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            # Add New Record
            c.execute("INSERT INTO beds (bed_r_name, bed_r_id, bed_p_id) Values (:bed_r_name, :bed_r_id, :bed_p_id)",
            {
                'bed_r_name' : room_name_box.get(),
                'bed_r_id' : room_id_box.get(),
                'bed_p_id' : patient_id_box.get(),
            }
            )

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear boxes
            room_name_box.delete(0, END)
            room_id_box.delete(0, END)
            patient_id_box.delete(0, END)

            # Clear The Treeview Table
            my_tree2.delete(*my_tree2.get_children())

            # Run to pull data from database on start
            query_database2()

        # Show records upon running program
        def query_database2():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            # Query the database
            c.execute("SELECT * FROM beds")
            records = c.fetchall()

            # Loop Thru Results
            global count
            count = 0
            for record in records:
                if count % 2 == 0:
                    my_tree2.insert(parent='', index='end', iid= count , text=f'count', values=(record[0], record[1], record[2], record[3]) , tags= ("evenrow",))
                else:
                    my_tree2.insert(parent='', index='end', iid= count , text=f'count', values=(record[0], record[1], record[2], record[3]) , tags= ("oddrow",))
                count += 1

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

        # Remove all
        def remove_all2():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            for record in my_tree2.get_children():
                my_tree2.delete(record)

            c.execute("DELETE from beds")

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree2.delete(*my_tree2.get_children())

            # Run to pull data from database on start
            query_database2()

        # Remove one selected
        def remove_one2():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            x = my_tree2.selection()[0]
            my_tree2.delete(x)

            c.execute("DELETE from nurses WHERE nur_id=" + bed_id_box.get())

            # Clear boxes
            bed_id_box.delete(0, END)
            room_name_box.delete(0, END)
            room_id_box.delete(0, END)
            patient_id_box.delete(0, END)

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree2.delete(*my_tree2.get_children())

            # Run to pull data from database on start
            query_database2()

        # Remove many selected
        def remove_many2():
            # Create a database or connect to one
            conn = sqlite3.connect("hospital.db")

            # Create cursor
            c = conn.cursor()

            x = my_tree2.selection()
            for record in x:
                my_tree2.delete(record)
                c.execute("DELETE from beds WHERE bed_id=" + record[0])

            # Commit Changes
            conn.commit()

            # Close Connection
            conn.close()

            # Clear The Treeview Table
            my_tree2.delete(*my_tree2.get_children())

            # Run to pull data from database on start
            query_database2()

        # Buttons frame
        btn_frame2 = LabelFrame(win, text= "Bed Command")
        btn_frame2.pack(fill ="x", expand="yes", padx=20)

        # Buttons
        add_recordx2 = Button(btn_frame2, text="Add Record", command= add_record2)
        add_recordx2.grid(row= 0 , column= 0, padx= 10, pady= 5)

        # Show Records
        update_record2 = Button(btn_frame2, text = "Update Record", command= update_record2)
        update_record2.grid(row = 0, column= 1, padx= 10, pady= 5)

        # Remove all
        remove_allx2 = Button(btn_frame2, text = "Remove All Record", command = remove_all2)
        remove_allx2.grid(row = 0, column= 2, padx= 10, pady= 5)

        # Remove one
        remove_onex2 = Button(btn_frame2, text= "Remove One Selected", command=remove_one2)
        remove_onex2.grid(row= 0, column= 3, padx= 10, pady= 5)

        # Remove many selected
        remove_manyx2 = Button(btn_frame2, text = "Remove Many Selected", command= remove_many2)
        remove_manyx2.grid(row = 0, column= 4, padx= 10, pady= 5)

        # Bind the treeview
        my_tree2.bind("<ButtonRelease-1>", select_record2)

        # Pull data before running program
        query_database2()

        # Win loop
        win.mainloop()


from py_agent.credentials import get_credential
from py_agent.utils import listen_for
import dropbox
import re

@listen_for({'event_type': ('==', 'archive_article')})
def add_article_to_dropbox(event=None, handler=None):
    print("adding article")
    dbx = dropbox.Dropbox(get_credential("dropbox"))
    data = event.data
    markdown = []

    markdown.append('## ' + data['title'])

    markdown.append('Category: #' + data['category'].lower().replace(" ", "_"))

    markdown.append('**Keywords**: ' + ', '.join(data['keywords']))
    markdown.append('url: ' + data['url'])
    if len(data['notes']) > 0:
        markdown.append('### Notes')
        for note in data['notes']:
            markdown.append('- ' + note)

    markdown.append('### Summary')
    markdown.append(data['summary'])

    sanitized_title = re.sub(r"[^a-zA-Z0-9]+", ' ', data['title'])
    upload_path='/notes/articles/{}/{}.md'.format(data['category'], sanitized_title)

    existing_file = None
    try:
        # if the file doesn't exist, the api throws an exception
        f = dbx.files_download(upload_path)[1]
        existing_file = f.content.decode('utf-8')
    except:
        pass

    to_upload = '\n\n'.join(markdown)
    if existing_file:
        to_upload = existing_file + '\n\n\n\n' + to_upload

    dbx.files_upload(to_upload.encode('utf-8'),
        upload_path, mode=dropbox.files.WriteMode.overwrite)


from flask_app.models.model_user import User
from flask_app.models.model_post import Post

from flask_app import app
from flask import render_template, redirect, flash, session, request

@app.route('/ideas')
def list_user_posts():
    if 'user_id' not in session:
        return redirect('/login')
    # Collects all the posts from the database and their users
    posts = Post.get_all_posts()
    print(posts)
    return render_template('ideas.html', posts = posts)

@app.route('/add_blog', methods=['POST'])
def add_post():
    if 'user_id' not in session:
        return redirect('/login')
    data = {
        'title' : request.form['title'],
        'content' : request.form['content'],
        'user_id' : session['user_id']
    }

    Post.add_blog(data)
    return redirect('/ideas')

@app.route('/delete_blog/<int:blog_id>')
def delete_blog(blog_id):
    data = {
        'blog_id' : blog_id
    }

    Post.delete(data)
    return redirect('/ideas')

@app.route('/update_blog/<int:blog_id>')
def update_blog(blog_id):
    if 'user_id' not in session:
        return redirect('/login')
    data = {
        'blog_id' : blog_id
    }
    post = Post.get_post(data)
    return render_template('update_blog.html', post = post)

@app.route('/update', methods=["POST"])
def update():
    data = {
        'blog_id' : request.form['blog_id'],
        'title' : request.form['title'],
        'content' : request.form['content']
    }

    Post.update_the_blog(data)
    return redirect('/ideas')


# read data from input.txt
with open("input.txt", "r") as f:
    data = f.read()

# split data into list by line breaks
elfs = data.split("\n\n")

calories_per_elf = []

for elf in elfs:
    food_items = elf.split("\n")
    total_calorie = 0
    for food in food_items:
        total_calorie += int(food)
    calories_per_elf.append(total_calorie)
print(max(calories_per_elf))


import magic

def get_mime(filepath):
    mime = magic.Magic(mime=True)
    return mime.from_file(filepath)

def get_mime_memory_file(file):
    initial_pos = file.tell()
    file.seek(0)
    mime_type = magic.from_buffer(file.read(1024), mime=True)
    file.seek(initial_pos)
    return mime_type


from __future__ import print_function
from __future__ import division

import os
import sys
curdir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(curdir, os.path.pardir))

if sys.version_info[0] < 3:
    reload(sys)
    sys.setdefaultencoding("utf-8")
    # raise "Must be using Python 3"

from absl import app
from absl import flags
from absl import logging
from collections import defaultdict
import copy
import random
from ml import ml

from common import *
from common.exceptions import *
from transitionparser.configurations import *

class TransitionBasedParser:
    """
    Refactored ArcStandardParser, with a Configuration object
    """
    Configuration = None
    """
   Configuration class, defines how the parser behaves
   """

    def __init__(self, decider):
        self.d = decider
        pass

    def decide(self, conf):
        actions = self.d.next_actions(
            conf.stack, conf.deps, conf.sent, conf.i, conf)
        return actions

    def parse(self, sent):
        logging.debug("parse: %s", sent)
        sent = [ROOT] + sent
        conf = self.Configuration(sent)
        logging.debug("parse: resolve conf")
        while not conf.is_in_finish_state():
            logging.debug("parse: not finish")
            next_actions = self.decide(conf)
            for act in next_actions:
                try:
                    logging.debug("parse: next_actions [%s]", act)
                    conf.do_action(act)
                    logging.debug("parse: stack len(%s), deps(%s), buffer len(%s)", len(conf.stack), len(conf.deps), (len(conf.sent) - conf.i))
                    break
                except IllegalActionException as e:
                    logging.debug("parse: next_actions error - %s", e)
                    pass
        logging.debug("parse: finish")
        return conf.deps  # ,conf.chunks

class ArcStandardParser2(TransitionBasedParser):
    Configuration = ArcStandardConfiguration

class ArcEagerParser(TransitionBasedParser):
    Configuration = ArcEagerConfiguration

class ErrorInspectionParser(ArcStandardParser2):  # {{{
    def __init__(self, decider, oracle, confPrinter, out=sys.stdout):
        ArcStandardParser2.__init__(self, decider)
        self.oracle = oracle
        self.confPrinter = confPrinter
        self.out = out

        self.raise_on_error = False
        self.use_oracle_answer = True

    def decide(self, conf):
        action = ArcStandardParser2.decide(self, conf)
        real = self.oracle.next_action(
            conf.stack, conf.deps, conf.sent, conf.i)
        if action != real:
            self.out.write(
                "%s -> %s %s\n" %
                (real, action, self.confPrinter.format(conf)))
            if self.raise_on_error:
                raise MLTrainerWrongActionException()

        if self.use_oracle_answer:
            return real
        else:
            return action


from collections import defaultdict
from collections import OrderedDict
from encoded.cart_view import CartWithElements
from encoded.reports.constants import ANNOTATION_METADATA_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_ALLOWED_TYPES
from encoded.reports.constants import METADATA_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_AUDIT_TO_AUDIT_COLUMN_MAPPING
from encoded.reports.constants import PUBLICATION_DATA_METADATA_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import SERIES_METADATA_COLUMN_TO_FIELDS_MAPPING
from encoded.reports.constants import METADATA_SERIES_TYPES
from encoded.reports.csv import CSVGenerator
from encoded.reports.decorators import allowed_types
from encoded.reports.inequalities import map_param_values_to_inequalities
from encoded.reports.inequalities import try_to_evaluate_inequality
from encoded.reports.search import BatchedSearchGenerator
from encoded.reports.serializers import make_experiment_cell
from encoded.reports.serializers import make_file_cell
from encoded.reports.serializers import map_strings_to_booleans_and_ints
from encoded.search_views import search_generator
from encoded.vis_defines import is_file_visualizable
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.response import Response
from pyramid.view import view_config
from snosearch.interfaces import EXISTS
from snosearch.interfaces import MUST
from snosearch.interfaces import RANGES
from snosearch.parsers import QueryString
from snovault.util import simple_path_ids

def includeme(config):
    config.add_route('metadata', '/metadata{slash:/?}')
    config.scan(__name__)

def file_matches_file_params(file_, positive_file_param_set):
    # Expects file_param_set where FILES_PREFIX (e.g. 'files.') has been
    # stripped off of key (files.file_type -> file_type)
    # and params with field negation (i.e. file_type!=bigWig)
    # have been filtered out. Param values should be
    # coerced to ints ('2' -> 2) or booleans ('true' -> True)
    # and put into a set for comparison with file values.
    for field, set_of_param_values in positive_file_param_set.items():
        file_value = list(simple_path_ids(file_, field))
        if not file_value:
            return False
        if '*' in set_of_param_values:
            continue
        if not set_of_param_values.intersection(file_value):
            return False
    return True

def some_value_satisfies_inequalities(values, inequalities):
    return all(
        any(
            try_to_evaluate_inequality(inequality, value)
            for value in values
        )
        for inequality in inequalities
    )

def file_satisfies_inequality_constraints(file_, positive_file_inequalities):
    for field, inequalities in positive_file_inequalities.items():
        file_value = list(simple_path_ids(file_, field))
        if not file_value:
            return False
        if not some_value_satisfies_inequalities(file_value, inequalities):
            return False
    return True

def group_audits_by_files_and_type(audits):
    grouped_file_audits = defaultdict(lambda: defaultdict(list))
    grouped_other_audits = defaultdict(list)
    for audit_type, audit_column in METADATA_AUDIT_TO_AUDIT_COLUMN_MAPPING:
        for audit in audits.get(audit_type, []):
            path = audit.get('path')
            if '/files/' in path:
                grouped_file_audits[path][audit_type].append(audit.get('category'))
            else:
                grouped_other_audits[audit_type].append(audit.get('category'))
    return grouped_file_audits, grouped_other_audits

class MetadataReport:

    SEARCH_PATH = '/search/'
    EXCLUDED_COLUMNS = (
        'Restricted',
        'No File Available',
    )
    DEFAULT_PARAMS = [
        ('field', 'audit'),
        ('field', 'files.@id'),
        ('field', 'files.restricted'),
        ('field', 'files.no_file_available'),
        ('field', 'files.file_format'),
        ('field', 'files.file_format_type'),
        ('field', 'files.status'),
        ('field', 'files.assembly'),
        ('limit', 'all'),
    ]
    CONTENT_TYPE = 'text/tsv'
    CONTENT_DISPOSITION = 'attachment; filename="metadata.tsv"'
    FILES_PREFIX = 'files.'

    def __init__(self, request):
        self.request = request
        self.query_string = QueryString(request)
        self.param_list = self.query_string.group_values_by_key()
        self.split_file_filters = {}
        self.positive_file_param_set = {}
        self.positive_file_inequalities = {}
        self.header = []
        self.experiment_column_to_fields_mapping = OrderedDict()
        self.file_column_to_fields_mapping = OrderedDict()
        self.visualizable_only = self.query_string.is_param('option', 'visualizable')
        self.raw_only = self.query_string.is_param('option', 'raw')
        self.csv = CSVGenerator()

    def _get_column_to_fields_mapping(self):
        return METADATA_COLUMN_TO_FIELDS_MAPPING

    def _build_header(self):
        for column in self._get_column_to_fields_mapping():
            if column not in self.EXCLUDED_COLUMNS:
                self.header.append(column)
        for audit, column in METADATA_AUDIT_TO_AUDIT_COLUMN_MAPPING:
            self.header.append(column)

    def _split_column_and_fields_by_experiment_and_file(self):
        for column, fields in self._get_column_to_fields_mapping().items():
            if fields[0].startswith(self.FILES_PREFIX):
                self.file_column_to_fields_mapping[column] = [
                    field.replace(self.FILES_PREFIX, '')
                    for field in fields
                ]
            else:
                self.experiment_column_to_fields_mapping[column] = fields

    def _set_split_file_filters(self):
        file_params = self.query_string.get_filters_by_condition(
            key_and_value_condition=lambda k, _: k.startswith(self.FILES_PREFIX)
        )
        self.split_file_filters = self.query_string.split_filters(
            params=file_params
        )

    def _set_positive_file_param_set(self):
        grouped_positive_file_params = self.query_string.group_values_by_key(
            params=self.split_file_filters[MUST] + self.split_file_filters[EXISTS]
        )
        self.positive_file_param_set = {
            k.replace(self.FILES_PREFIX, ''): set(map_strings_to_booleans_and_ints(v))
            for k, v in grouped_positive_file_params.items()
        }

    def _set_positive_file_inequalities(self):
        grouped_positive_file_inequalities = self.query_string.group_values_by_key(
            params=self.split_file_filters[RANGES]
        )
        self.positive_file_inequalities = {
            k.replace(self.FILES_PREFIX, ''): map_param_values_to_inequalities(v)
            for k, v in grouped_positive_file_inequalities.items()
        }

    def _add_positive_file_filters_as_fields_to_param_list(self):
        self.param_list['field'] = self.param_list.get('field', [])
        self.param_list['field'].extend(
            (
                k
                for k, v in self.query_string._get_original_params()
                if k.startswith(self.FILES_PREFIX) and '!' not in k
            )
        )

    def _add_fields_to_param_list(self):
        self.param_list['field'] = self.param_list.get('field', [])
        for column, fields in self._get_column_to_fields_mapping().items():
            self.param_list['field'].extend(fields)
        self._add_positive_file_filters_as_fields_to_param_list()

    def _initialize_at_id_param(self):
        self.param_list['@id'] = self.param_list.get('@id', [])

    def _maybe_add_cart_elements_to_param_list(self):
        # Don't need to limit max_cart_elements here since
        # search is batched.
        cart = CartWithElements(
            self.request,
            max_cart_elements=None
        )
        self.param_list['@id'].extend(cart.elements)
        self.param_list.pop('cart', None)

    def _get_json_elements_or_empty_list(self):
        try:
            return self.request.json.get('elements', [])
        except ValueError:
            return []

    def _maybe_add_json_elements_to_param_list(self):
        self.param_list['@id'].extend(
            self._get_json_elements_or_empty_list()
        )

    def _get_field_params(self):
        return [
            ('field', p)
            for p in self.param_list.get('field', [])
        ]

    def _get_at_id_params(self):
        return [
            ('@id', p)
            for p in self.param_list.get('@id', [])
        ]

    def _get_default_params(self):
        return self.DEFAULT_PARAMS

    def _build_query_string(self):
        self.query_string.drop('limit')
        self.query_string.drop('option')
        self.query_string.extend(
            self._get_default_params()
            + self._get_field_params()
            + self._get_at_id_params()
        )

    def _get_search_path(self):
        return self.SEARCH_PATH

    def _build_new_request(self):
        self._build_query_string()
        request = self.query_string.get_request_with_new_query_string()
        request.path_info = self._get_search_path()
        return request

    def _get_search_results_generator(self):
        return BatchedSearchGenerator(
            self._build_new_request()
        ).results()

    def _should_not_report_file(self, file_):
        conditions = [
            not file_matches_file_params(file_, self.positive_file_param_set),
            not file_satisfies_inequality_constraints(file_, self.positive_file_inequalities),
            self.visualizable_only and not is_file_visualizable(file_),
            self.raw_only and file_.get('assembly'),
            file_.get('restricted'),
            file_.get('no_file_available'),
        ]
        return any(conditions)

    def _get_experiment_data(self, experiment):
        return {
            column: make_experiment_cell(fields, experiment)
            for column, fields in self.experiment_column_to_fields_mapping.items()
        }

    def _get_file_data(self, file_):
        file_['href'] = self.request.host_url + file_['href']
        return {
            column: make_file_cell(fields, file_)
            for column, fields in self.file_column_to_fields_mapping.items()
        }

    def _get_audit_data(self, grouped_audits_for_file, grouped_other_audits):
        return {
            audit_column: ', '.join(
                set(
                    grouped_audits_for_file.get(audit_type, [])
                    + grouped_other_audits.get(audit_type, [])
                )
            ) for audit_type, audit_column in METADATA_AUDIT_TO_AUDIT_COLUMN_MAPPING
        }

    def _output_sorted_row(self, experiment_data, file_data):
        row = []
        for column in self.header:
            row.append(
                file_data.get(
                    column,
                    experiment_data.get(column)
                )
            )
        return row

    def _generate_rows(self):
        yield self.csv.writerow(self.header)
        for experiment in self._get_search_results_generator():
            if not experiment.get('files', []):
                continue
            grouped_file_audits, grouped_other_audits = group_audits_by_files_and_type(
                experiment.get('audit', {})
            )
            experiment_data = self._get_experiment_data(experiment)
            for file_ in experiment.get('files', []):
                if self._should_not_report_file(file_):
                    continue
                file_data = self._get_file_data(file_)
                audit_data = self._get_audit_data(
                    grouped_file_audits.get(file_.get('@id'), {}),
                    grouped_other_audits
                )
                file_data.update(audit_data)
                yield self.csv.writerow(
                    self._output_sorted_row(experiment_data, file_data)
                )

    def _validate_request(self):
        type_params = self.param_list.get('type', [])
        if len(type_params) != 1:
            raise HTTPBadRequest(explanation='URL requires one "type" parameter.')
        return True

    def _initialize_report(self):
        self._build_header()
        self._split_column_and_fields_by_experiment_and_file()
        self._set_split_file_filters()
        self._set_positive_file_param_set()
        self._set_positive_file_inequalities()

    def _build_params(self):
        self._add_fields_to_param_list()
        self._initialize_at_id_param()
        self._maybe_add_cart_elements_to_param_list()
        self._maybe_add_json_elements_to_param_list()

    def generate(self):
        self._validate_request()
        self._initialize_report()
        self._build_params()
        return Response(
             content_type=self.CONTENT_TYPE,
             app_iter=self._generate_rows(),
             content_disposition=self.CONTENT_DISPOSITION,
        )

class AnnotationMetadataReport(MetadataReport):

    def _get_column_to_fields_mapping(self):
        return ANNOTATION_METADATA_COLUMN_TO_FIELDS_MAPPING

class PublicationDataMetadataReport(MetadataReport):
    '''
    PublicationData objects don't embed file attributes so
    we have to get file metadata with separate search request.
    We try to get all the file metadata together in a batched request
    instead of making a request for every file. This requires some
    extra machinery compared to normal MetdataReport.
    '''

    DEFAULT_PARAMS = [
        ('limit', 'all'),
        ('field', 'files')
    ]
    DEFAULT_FILE_PARAMS = [
        ('type', 'File'),
        ('limit', 'all'),
        ('field', '@id'),
        ('field', 'href'),
        ('field', 'restricted'),
        ('field', 'no_file_available'),
        ('field', 'file_format'),
        ('field', 'file_format_type'),
        ('field', 'status'),
        ('field', 'assembly'),
    ]

    def __init__(self, request):
        super().__init__(request)
        self.file_query_string = QueryString(request)
        self.file_params = []
        self.file_at_ids = []

    # Overrides parent.
    def _get_column_to_fields_mapping(self):
        return PUBLICATION_DATA_METADATA_COLUMN_TO_FIELDS_MAPPING

    # Overrides parent.
    def _build_header(self):
        for column in self._get_column_to_fields_mapping():
            if column not in self.EXCLUDED_COLUMNS:
                self.header.append(column)

    # Overrides parent.
    def _add_fields_to_param_list(self):
        self.param_list['field'] = []
        for column, fields in self.experiment_column_to_fields_mapping.items():
            self.param_list['field'].extend(fields)

    def _add_default_file_params_to_file_params(self):
        self.file_params.extend(self.DEFAULT_FILE_PARAMS)

    def _add_report_file_fields_to_file_params(self):
        for column, fields in self.file_column_to_fields_mapping.items():
            self.file_params.extend(
                [
                    ('field', field)
                    for field in fields
                ]
            )

    def _convert_experiment_params_to_file_params(self):
        return [
            (k.replace(self.FILES_PREFIX, ''), v)
            for k, v in self.query_string._get_original_params()
            if k.startswith(self.FILES_PREFIX)
        ]

    def _add_experiment_file_filters_as_fields_to_file_params(self):
        self.file_params.extend(
            ('field', k)
            for k, v in self._convert_experiment_params_to_file_params()
        )

    def _add_experiment_file_filters_to_file_params(self):
        self.file_params.extend(
            self._convert_experiment_params_to_file_params()
        )

    def _build_file_params(self):
        self._add_default_file_params_to_file_params()
        self._add_report_file_fields_to_file_params()
        self._add_experiment_file_filters_as_fields_to_file_params()
        self._add_experiment_file_filters_to_file_params()

    def _filter_file_params_from_query_string(self):
        self.query_string.params = [
            (k, v)
            for k, v in self.query_string.params
            if not k.startswith(self.FILES_PREFIX)
        ]

    # Overrides parent.
    def _build_params(self):
        super()._build_params()
        self._build_file_params()
        self._filter_file_params_from_query_string()

    def _get_at_id_file_params(self):
        return [
            ('@id', file_at_id)
            for file_at_id in self.file_at_ids
        ]

    def _build_new_file_request(self):
        self.file_query_string.params = (
            self.file_params + self._get_at_id_file_params()
        )
        request = self.file_query_string.get_request_with_new_query_string()
        request.path_info = self._get_search_path()
        return request

    def _get_file_search_results_generator(self):
        request = self._build_new_file_request()
        bsg = BatchedSearchGenerator(request)
        return bsg.results()

    # Overrides parent.
    def _generate_rows(self):
        yield self.csv.writerow(self.header)
        for experiment in self._get_search_results_generator():
            self.file_at_ids = experiment.get('files', [])
            if not self.file_at_ids:
                continue
            experiment_data = self._get_experiment_data(experiment)
            for file_ in self._get_file_search_results_generator():
                if self._should_not_report_file(file_):
                    continue
                file_data = self._get_file_data(file_)
                yield self.csv.writerow(
                    self._output_sorted_row(experiment_data, file_data)
                )

class SeriesMetadataReport(MetadataReport):

    DEFAULT_PARAMS = [
        ('limit', 'all'),
        ('field', 'series_files.@id'),
        ('field', 'series_files.href'),
        ('field', 'series_files.restricted'),
        ('field', 'series_files.no_file_available'),
        ('field', 'series_files.file_format'),
        ('field', 'series_files.file_format_type'),
        ('field', 'series_files.preferred_default'),
        ('field', 'series_files.status'),
        ('field', 'series_files.assembly'),
    ]
    FILES_PREFIX = 'series_files.'

    def _get_column_to_fields_mapping(self):
        return SERIES_METADATA_COLUMN_TO_FIELDS_MAPPING

    def _generate_rows(self):
        yield self.csv.writerow(self.header)
        for series in self._get_search_results_generator():
            series_data = self._get_experiment_data(series)
            for file_ in series.get('series_files', []):
                if self._should_not_report_file(file_):
                    continue
                file_data = self._get_file_data(file_)
                yield self.csv.writerow(
                    self._output_sorted_row(series_data, file_data)
                )

def _get_metadata(context, request):
    metadata_report = MetadataReport(request)
    return metadata_report.generate()

def _get_annotation_metadata(context, request):
    annotation_metadata_report = AnnotationMetadataReport(request)
    return annotation_metadata_report.generate()

def _get_publication_data_metadata(context, request):
    publication_data_metadata_report = PublicationDataMetadataReport(request)
    return publication_data_metadata_report.generate()

def _get_series_metadata(context, request):
    series_metadata_report = SeriesMetadataReport(request)
    return series_metadata_report.generate()

def metadata_report_factory(context, request):
    qs = QueryString(request)
    specified_type = qs.get_one_value(
            params=qs.get_type_filters()
    )
    if specified_type == 'Annotation':
        return _get_annotation_metadata(context, request)
    elif specified_type == 'PublicationData':
        return _get_publication_data_metadata(context, request)
    elif specified_type in METADATA_SERIES_TYPES:
        return _get_series_metadata(context, request)
    else:
        return _get_metadata(context, request)

@view_config(route_name='metadata', request_method=['GET', 'POST'])
@allowed_types(METADATA_ALLOWED_TYPES)
def metadata_tsv(context, request):
    return metadata_report_factory(context, request)


from scipy.misc import imresize
import numpy as np

class Preprocessor:

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def process(self, frame):
        roi_height, roi_width = frame.shape[0], int(frame.shape[1] * .68)
        processed = np.zeros((roi_height, roi_width))

        roi = frame[:, :roi_width, 0]
        all_obstacles_idx = roi > 50
        processed[all_obstacles_idx] = 1
        unharmful_obstacles_idx = roi > 200
        processed[unharmful_obstacles_idx] = 0

        processed = imresize(processed, (self.height, self.width, 1))
        processed = processed / 255.0
        return processed

    def get_initial_state(self, first_frame):
        self.state = np.array([first_frame, first_frame, first_frame, first_frame])
        return self.state

    def get_updated_state(self, next_frame):
        self.state =  np.array([*self.state[-3:], next_frame])
        return self.state


# -*- coding: utf-8 -*-
"""
Created on Wed May 30 12:29:30 2018

@author: sande
"""
from pandas import read_csv
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('../')
from Data.datareader import *

#for fivegrams, iterate over all sensors
#F_PU3, F_PU5, F_PU9 have been ignored because they contain only zeros in the dataset
for fields in ['L_T1', 'L_T2', 'L_T3', 'L_T4', 'L_T5','L_T6', 'L_T7', 'F_PU1','F_PU2', 'F_PU4', 'F_PU6', 'F_PU7', 'F_PU8', 'F_PU10','F_PU11', 'F_V2', 'S_V2', 'P_J269', 'P_J300', 'P_J256', 'P_J289', 'P_J415','P_J302', 'P_J306', 'P_J307', 'P_J317', 'P_J14', 'P_J422']:
        print ("for sensor", fields)
        series = read_3_series(fields)
        #and for each sensor, discretize the data using different number of quantiles
        for no_quantiles in [5]:
            _, bins = pd.qcut(series, no_quantiles, retbins=True, duplicates = 'drop')
            cut_data, bins = pd.qcut(series, no_quantiles, retbins=True, labels=range(len(bins)-1),duplicates = 'drop')

            #create a matrix of dimensions of no_quantiles
            occurrences_train = np.ones((no_quantiles,no_quantiles,no_quantiles,no_quantiles,no_quantiles))
            sum = 0
            #try for five-grams
            for i in range(0,len(cut_data)-5):
                a = cut_data[i]
                b = cut_data[i+1]
                c = cut_data[i+2]
                d = cut_data[i+3]
                e = cut_data[i+4]
                occurrences_train[a][b][c][d][e] = occurrences_train[a][b][c][d][e] + 1

            #convert to probabilities
            occurrences_train_prob = np.true_divide(occurrences_train, len(cut_data))
            #For test data, evaluate the performance
            series = read_4_series(fields)
            #print (occurrences_train_prob)
            _, bins = pd.qcut(series, no_quantiles, retbins=True, duplicates = 'drop')
            #no_quantiles = len(bins)
            cut_data, bins = pd.qcut(series, no_quantiles, retbins=True, labels=range(len(bins)-1), duplicates = 'drop')

            for threshold in [0.005] :
                count = 0
                true_positive_count = 0
                for i in range(0,len(cut_data)-5):
                    a = cut_data[i]
                    b = cut_data[i+1]
                    c = cut_data[i+2]
                    d = cut_data[i+3]
                    e = cut_data[i+4]
                    if (occurrences_train_prob[a][b][c][d][e] < threshold):
                        #Count the number of five grams which are under threshold
                        count = count + 1
                        if attack_at_time_04(cut_data.index[i+4]) :
                            #If there is an attack at the time of the fifth entry of five grams, then it is true positive
                            true_positive_count = true_positive_count + 1

                if ((count > 0) and (true_positive_count > 0)) :
                    print ("Precision: ",true_positive_count/count," for threshold: ", threshold," and number of percentiles: ",no_quantiles)


from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from book.models import CommentForm, Comment

def index(request):
    text="Merhaba Django";

    return HttpResponse("Product Page")

@login_required(login_url='/login')

def addcomment(request,id):
    url = request.META.get('HTTP_REFERER')
    if request.method == 'POST':
        form= CommentForm(request.POST)
        if form.is_valid():
            current_user=request.user #login olan user den gelecek

            data=Comment() #model ile baglantı
            data.user_id = current_user.id
            data.book_id = id
            data.subject = form.cleaned_data['subject']
            data.comment = form.cleaned_data['comment']
            data.rate = form.cleaned_data['rate']
            data.ip =request.META.get('REMOTE_ADDR') #ip adresini aldık
            data.save() #veritabanına kaydet
            messages.success(request, "Yorumunuz basari ile gönderilmiştir.Teşekkür Ederiz")

            return HttpResponseRedirect(url)
    messages.error(request, "Yorumunuz gönderilememiştir.Lütfen kontrol ediniz")
    return HttpResponse("url")


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 21:48:09 2019

@author: rakshith kunchum

Simple program to demonstrate Controlled-NOT gate.
Circuit:
0: ───H───@───M('q0')───
          │
1: ───────X───M('q1')───
Results:
q0=0111100111
q1=0111100111
Counter({1: 7, 0: 3})
Counter({1: 7, 0: 3})
"""
import cirq

def main():
    circuit = cirq.Circuit()
    (q0, q1) = cirq.LineQubit.range(2)
    circuit.append([cirq.H(q0), cirq.CNOT(q0, q1),
                    cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')])
    sim = cirq.Simulator()
    results = sim.run(circuit, repetitions=10)
    print("Circuit:", circuit, sep='\n')
    print("Results:", results, sep='\n')
    print(results.histogram(key='q0'))
    print(results.histogram(key='q1'))

if __name__ == '__main__':
    main()


from collections import deque

import numpy as np

from ..agents.sample_efficient import Dyna_Q_Agent

class Trial:

    def __init__(self, env, agent, episodes, scores : deque, lrews : list):

        # Just to store the long-term-reward of the last 100 experiments
        self.scores = scores
        self.lrews = lrews

        self.env = env
        self.agent = agent
        self.episodes = episodes

    def interact(self):

        for episode in range(1, self.episodes+1):
            state = self.env.reset()
            R = 0
            done = False
            R, reward = 0,0

            for step in range(self.env.spec.max_episode_steps):
                action = self.agent.select_action(state)

                next_state, reward, done, info = self.env.step(action)

                self.agent.update(state, action, reward, next_state)

                if isinstance(self.agent, Dyna_Q_Agent):
                    self.agent.update_model(state, action, reward, next_state)

                state = next_state
                R += reward

                if done:
                    break

            self.scores.append(R)
            self.lrews.append(np.mean(self.scores))