class Node:
    def __init__(self, initialValue):
        self.data = initialValue
        self.nextNode = None

    def getData(self):
        return self.data

    def getNextNode(self):
        return self.nextNode

    def setData(self, inputData):
        self.data = inputData

    def setNextNode(self, newNextNode):
        self.nextNode = newNextNode

class OrderedList:
    def __init__(self):
        self.head = None

    def __repr__(self):
        nodes = []
        current = self.head
        while current:
            if current is self.head:
                nodes.append("[Head: %s]" % current.data)
            elif current.getNextNode() is None:
                nodes.append("[Tail: %s]" % current.data)
            else:
                nodes.append("[%s]" % current.data)
            current = current.getNextNode()
        return '->'.join(nodes)

    def search(self, item):
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.getData() == item:
                found = True
            else:
                if current.getData() > item:
                    stop = True
                else:
                    current = current.getNextNode()
        return found

    def add(self, item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNextNode()

        temp = Node(item)
        if previous == None:
            temp.setNextNode(self.head)
            self.head = temp
        else:
            temp.setNextNode(current)
            previous.setNextNode(temp)

    def isEmpty(self):
        return self.head == None

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.getNextNode()
        return count

    def remove(self, item):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.getData() == item:
                found = True
            else:
                previous = current
                current = current.getNext()

        if previous == None:
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)

print(mylist.size())
print(mylist.search(93))
print(mylist.search(100))
print (mylist)


import itertools

import matplotlib.pyplot as plt
import pytorch_lightning as pl
import torch
import wandb
from fish_audio_preprocess.utils.loudness_norm import loudness_norm
from mmengine.optim import OPTIMIZERS
from pytorch_lightning.loggers import TensorBoardLogger, WandbLogger
from torch.nn import functional as F

from fish_diffusion.modules.vocoders.nsf_hifigan.models import (
    AttrDict,
    MultiPeriodDiscriminator,
    MultiScaleDiscriminator,
    discriminator_loss,
    feature_loss,
    generator_loss,
)
from fish_diffusion.schedulers import LR_SCHEUDLERS
from fish_diffusion.utils.audio import dynamic_range_compression, get_mel_transform
from fish_diffusion.utils.viz import plot_mel

from .core import HiFiSinger

class HiFiSingerV1Lightning(pl.LightningModule):
    def __init__(self, config):
        super().__init__()

        self.h = AttrDict(config.model.encoder)
        self.config = config

        self.generator = HiFiSinger(config.model)
        self.mpd = MultiPeriodDiscriminator(self.h["discriminator_periods"])
        self.msd = MultiScaleDiscriminator()

        # This is for validation only
        self.mel_transform = get_mel_transform(
            sample_rate=config.sampling_rate,
            n_fft=self.h.n_fft,
            hop_length=self.h.hop_size,
            win_length=self.h.win_size,
            f_min=self.h.fmin,
            f_max=self.h.fmax,
            n_mels=self.h.num_mels,
        )

        # The below are for training
        self.multi_scale_mels = [
            get_mel_transform(
                sample_rate=config.sampling_rate,
                n_fft=n_fft,
                hop_length=hop_length,
                win_length=win_length,
                # Shouldn't ise fmin and fmax here
                # Otherwise high frequency will be cut off
                f_min=0,
                f_max=config.sampling_rate // 2,
                n_mels=self.h.num_mels,
            )
            for (n_fft, hop_length, win_length) in self.h.multi_scale_mels
        ]

        self.automatic_optimization = False

    def configure_optimizers(self):
        optim_g = OPTIMIZERS.build(
            {
                "params": self.generator.parameters(),
                **self.config.optimizer,
            }
        )
        optim_d = OPTIMIZERS.build(
            {
                "params": itertools.chain(self.msd.parameters(), self.mpd.parameters()),
                **self.config.optimizer,
            }
        )

        scheduler_g = LR_SCHEUDLERS.build(
            {
                "optimizer": optim_g,
                **self.config.scheduler,
            }
        )
        scheduler_d = LR_SCHEUDLERS.build(
            {
                "optimizer": optim_d,
                **self.config.scheduler,
            }
        )

        return [optim_g, optim_d], [scheduler_g, scheduler_d]

    def training_step(self, batch, batch_idx):
        optim_g, optim_d = self.optimizers()

        y = batch["audio"].float()

        y_g_hat = self.generator(
            speakers=batch["speaker"],
            contents=batch["contents"],
            contents_lens=batch["contents_lens"],
            contents_max_len=batch["contents_max_len"],
            pitches=batch["pitches"],
            pitch_shift=batch.get("key_shift", None),
            phones2mel=batch.get("phones2mel", None),
            energy=batch.get("energy", None),
        )

        optim_d.zero_grad()

        # MPD
        y_df_hat_r, y_df_hat_g, _, _ = self.mpd(y, y_g_hat.detach())
        loss_disc_f, _, _ = discriminator_loss(y_df_hat_r, y_df_hat_g)

        # MSD
        y_ds_hat_r, y_ds_hat_g, _, _ = self.msd(y, y_g_hat.detach())
        loss_disc_s, _, _ = discriminator_loss(y_ds_hat_r, y_ds_hat_g)

        loss_disc_all = loss_disc_s + loss_disc_f

        self.manual_backward(loss_disc_all)
        optim_d.step()

        self.log(
            f"train_loss_disc",
            loss_disc_all,
            on_step=True,
            on_epoch=True,
            prog_bar=True,
            logger=True,
            sync_dist=True,
            batch_size=batch["contents"].shape[0],
        )

        # Generator
        optim_g.zero_grad()

        # We referenced STFT and Mel-Spectrogram loss from SingGAN
        # L1 STFT Loss

        loss_stft = 0
        for n_fft, hop_length, win_length in self.h.multi_scale_stfts:
            y_stft = torch.stft(
                y.squeeze(1), n_fft, hop_length, win_length, return_complex=True
            )
            y_g_hat_stft = torch.stft(
                y_g_hat.squeeze(1), n_fft, hop_length, win_length, return_complex=True
            )
            y_stft = torch.view_as_real(y_stft)
            y_g_hat_stft = torch.view_as_real(y_g_hat_stft)

            loss_stft += F.l1_loss(y_stft, y_g_hat_stft)

        loss_stft /= len(self.h.multi_scale_stfts)

        # L1 Mel-Spectrogram Loss
        loss_mel = 0
        for mel_transform in self.multi_scale_mels:
            y_mel = self.get_mels(y, mel_transform)
            y_g_hat_mel = self.get_mels(y_g_hat, mel_transform)
            loss_mel += F.l1_loss(y_mel, y_g_hat_mel)

        loss_mel /= len(self.multi_scale_mels)

        loss_aux = 0.5 * loss_stft + loss_mel

        # Discriminator Loss
        y_df_hat_r, y_df_hat_g, fmap_f_r, fmap_f_g = self.mpd(y, y_g_hat)
        y_ds_hat_r, y_ds_hat_g, fmap_s_r, fmap_s_g = self.msd(y, y_g_hat)
        loss_fm_f = feature_loss(fmap_f_r, fmap_f_g)
        loss_fm_s = feature_loss(fmap_s_r, fmap_s_g)
        loss_gen_f, _ = generator_loss(y_df_hat_g)
        loss_gen_s, _ = generator_loss(y_ds_hat_g)
        loss_gen_all = loss_gen_s + loss_gen_f + loss_fm_s + loss_fm_f + loss_aux * 45

        self.manual_backward(loss_gen_all)
        optim_g.step()

        self.log(
            f"train_loss_gen",
            loss_gen_all,
            on_step=True,
            on_epoch=True,
            prog_bar=True,
            logger=True,
            sync_dist=True,
            batch_size=batch["contents"].shape[0],
        )

        self.log(
            f"train_loss_aux",
            loss_aux,
            on_step=True,
            on_epoch=False,
            prog_bar=False,
            logger=True,
            sync_dist=True,
            batch_size=batch["contents"].shape[0],
        )

        # Manual LR Scheduler
        scheduler_g, scheduler_d = self.lr_schedulers()

        if self.trainer.is_last_batch:
            scheduler_g.step()
            scheduler_d.step()

    def get_mels(self, audios, transform=None):
        if transform is None:
            transform = self.mel_transform

        transform = transform.to(audios.device)
        x = transform(audios.squeeze(1))

        return dynamic_range_compression(x)

    def validation_step(self, batch, batch_idx):
        y_g_hat = self.generator(
            speakers=batch["speaker"],
            contents=batch["contents"],
            contents_lens=batch["contents_lens"],
            contents_max_len=batch["contents_max_len"],
            pitches=batch["pitches"],
            pitch_shift=batch.get("key_shift", None),
            phones2mel=batch.get("phones2mel", None),
            energy=batch.get("energy", None),
        )

        mels = self.get_mels(batch["audio"])
        y_g_hat_mel = self.get_mels(y_g_hat)[:, :, : mels.shape[2]]

        # L1 Mel-Spectrogram Loss
        mel_lens = batch["contents_lens"]

        # create mask
        mask = (
            torch.arange(mels.shape[2], device=mels.device)[None, :] < mel_lens[:, None]
        )
        mask = mask[:, None].float()

        loss_mel = F.l1_loss(mels * mask, y_g_hat_mel * mask)
        self.log(
            "valid_loss",
            loss_mel,
            on_step=True,
            on_epoch=True,
            prog_bar=True,
            logger=True,
            sync_dist=True,
            batch_size=batch["contents"].shape[0],
        )

        for idx, (mel, gen_mel, audio, gen_audio, mel_len, audio_len) in enumerate(
            zip(
                mels.cpu().numpy(),
                y_g_hat_mel.cpu().numpy(),
                batch["audio"].cpu().type(torch.float32).numpy(),
                y_g_hat.type(torch.float32).cpu().numpy(),
                batch["contents_lens"].cpu().numpy(),
                batch["audio_lens"].cpu().numpy(),
            )
        ):
            image_mels = plot_mel(
                [
                    gen_mel[:, :mel_len],
                    mel[:, :mel_len],
                ],
                ["Sampled Spectrogram", "Ground-Truth Spectrogram"],
            )

            wav_gt = loudness_norm(audio[0, :audio_len], 44100, block_size=0.1)
            wav_prediction = loudness_norm(
                gen_audio[0, :audio_len], 44100, block_size=0.1
            )

            if isinstance(self.logger, WandbLogger):
                self.logger.experiment.log(
                    {
                        f"reconstruction_mel": wandb.Image(image_mels, caption="mels"),
                        f"wavs": [
                            wandb.Audio(
                                wav_gt,
                                sample_rate=self.config.sampling_rate,
                                caption=f"gt",
                            ),
                            wandb.Audio(
                                wav_prediction,
                                sample_rate=self.config.sampling_rate,
                                caption=f"prediction",
                            ),
                        ],
                    },
                )

            if isinstance(self.logger, TensorBoardLogger):
                self.logger.experiment.add_figure(
                    f"sample-{idx}/mels",
                    image_mels,
                    global_step=self.global_step,
                )
                self.logger.experiment.add_audio(
                    f"sample-{idx}/wavs/gt",
                    wav_gt,
                    self.global_step,
                    sample_rate=self.config.sampling_rate,
                )
                self.logger.experiment.add_audio(
                    f"sample-{idx}/wavs/prediction",
                    wav_prediction,
                    self.global_step,
                    sample_rate=self.config.sampling_rate,
                )

            plt.close(image_mels)


import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn import preprocessing
from sklearn.cluster import KMeans

data = pd.read_csv('Data/30_128_X.csv').values
label = pd.read_csv('Data/30_y.csv').values.astype(np.int).squeeze()

print(data.shape)
print(label.shape)

# plt.plot(np.mean(data[label == 0], axis=0), color='g', label='cylider')
# plt.plot(np.mean(data[label == 1], axis=0), color='b', label='bell')
# plt.plot(np.mean(data[label == 2], axis=0), color='r', label='funnel')
# plt.legend()
# plt.xlabel('Date')
# plt.show()

# linked = linkage(data, 'single')
# plt.figure(figsize=(10, 7))
# dendrogram(linked,
#            orientation='top',
#            labels=np.array([i for i in range(len(data))]),
#            distance_sort='descending',
#            show_leaf_counts=True,
#            leaf_font_size=14)
# plt.show()

# km = KMeans(
#     n_clusters=3, init='random',
#     n_init=10, max_iter=300,
#     tol=1e-04, random_state=0
# )
# y_km = km.fit_predict(data)
#
# plt.plot(np.mean(data[y_km == 0], axis=0), color='g', label='Cluster 1 with {} sample'.format(len(data[y_km == 0])))
# plt.plot(np.mean(data[y_km == 1], axis=0), color='b', label='Cluster 2 with {} sample'.format(len(data[y_km == 1])))
# plt.plot(np.mean(data[y_km == 2], axis=0), color='r', label='Cluster 3 with {} sample'.format(len(data[y_km == 2])))
# plt.legend()
# plt.xlabel('Date')
# plt.show()

data_cat = data.ravel()
print(data_cat.shape)

data_conv = []
pace = 128
for i in range(len(data_cat) - pace):
    data_conv.append(data_cat[i:i+pace])

data_conv = np.array(data_conv)
print(data_conv.shape)
data_conv = preprocessing.minmax_scale(data_conv, axis=1)

# labels = np.random.randint(3584, size=50)
# linked = linkage(data_conv[labels, :], 'single')
#
# plt.figure(figsize=(10, 7))
# dendrogram(linked,
#            orientation='top',
#            labels=labels,
#            distance_sort='descending',
#            show_leaf_counts=True,
#            leaf_font_size=14)
# plt.show()

km = KMeans(
    n_clusters=4, init='random',
    n_init=10, max_iter=300,
    tol=1e-04, random_state=0
)
y_km = km.fit_predict(data_conv)

plt.plot(np.mean(data_conv[y_km == 0], axis=0), color='g', label='Cluster 1 with {} sample'.format(len(data_conv[y_km == 0])))
plt.plot(np.mean(data_conv[y_km == 1], axis=0), color='b', label='Cluster 2 with {} sample'.format(len(data_conv[y_km == 1])))
plt.plot(np.mean(data_conv[y_km == 2], axis=0), color='r', label='Cluster 3 with {} sample'.format(len(data_conv[y_km == 2])))
plt.plot(np.mean(data_conv[y_km == 3], axis=0), color='orange', label='Cluster 4 with {} sample'.format(len(data_conv[y_km == 3])))
plt.legend()
plt.show()


from copy import deepcopy
from random import choice
from typing import Dict, List, Tuple

class Headers:
    def __init__(self, options: Dict[str, str] | None = None) -> None:
        self.options = options or {}

        self.chrome_version: Tuple[str, str] | None = None

        # sec-ch-ua
        self.sec_ch_ua_conf: Dict | None = None

        self.sec_ch_ua: str | None = None
        self.sec_ch_ua_full_version: str | None = None
        self.sec_ch_ua_full_version_list: str | None = None
        self.sec_ch_ua_platform: str | None = None
        self.sec_ch_ua_platform_version: str | None = None
        self.sec_ch_ua_arch: str | None = None
        self.sec_ch_ua_bitness: str | None = None
        self.sec_ch_ua_mobile: str | None = None
        self.sec_ch_ua_model: str | None = None

        # user-agent
        self.user_agent: str | None = None

    @property
    def headers(self) -> Dict[str, str]:
        return self.options

class ChromeHeadersBuilder:
    CHROME_VERSIONS: Dict[str, List[str]] = {
        "100": [
            "100.0.4896.127",  # ~  04-2022
            "100.0.4896.143",  # ~  04-2022
        ],
        "101": [
            "101.0.4951.41",  # ~   04-2022
            "101.0.4951.67",  # ~   05-2022
        ],
        "102": [
            "102.0.5005.61",  # ~   05-2022
            "102.0.5005.62",  # ~   05-2022
            "102.0.5005.63",  # ~   05-2022
            "102.0.5005.134",  # ~  06-2022
            "102.0.5005.167",  # ~  07-2022
        ],
        "103": [
            "103.0.5060.53",  # ~   06-2022
            "103.0.5060.66",  # ~   06-2022
            "103.0.5060.134",  # ~  07-2022
        ],
        "104": [
            "104.0.5112.101",  # ~  08-2022
            "104.0.5112.111",  # ~  08-2022
        ],
        "105": [
            "105.0.5195.52",  # ~   08-2022
        ],
        "106": [
            "106.0.5249.61",  # ~   09-2022
            "106.0.5249.91",  # ~   09-2022
            "106.0.5249.165",  # ~  10-2022
            "106.0.5249.168",  # ~  10-2022
            "106.0.5249.181",  # ~  11-2022
            "106.0.5249.199",  # ~  11-2022
        ],
        "107": [
            "107.0.5304.62",  # ~   10-2022
            "107.0.5304.87",  # ~   10-2022
            "107.0.5304.110",  # ~  11-2022
            "107.0.5304.121",  # ~  11-2022
        ],
        "108": [
            "108.0.5359.71",  # ~   11-2022
            "108.0.5359.94",  # ~   12-2022
            "108.0.5359.98",  # ~   12-2022
            "108.0.5359.124",  # ~  12-2022
            "108.0.5359.179",  # ~  01-2023
            "108.0.5359.215",  # ~  01-2023
        ],
        "109": [
            "109.0.5414.74",  # ~   01-2023
            "109.0.5414.119",  # ~  01-2023
        ],
        "110": [
            "110.0.5481.77",  # ~   02-2023
            "110.0.5481.208",  # ~  03-2023
        ],
        "111": [
            "111.0.5563.110",  # ~  03-2023
            "111.0.5563.147",  # ~  03-2023
        ],
        "112": [
            "112.0.5615.49",  # ~   04-2023
            "112.0.5615.86",  # ~   04-2023
            "112.0.5615.87",  # ~   04-2023
            "112.0.5615.121",  # ~  04-2023
            "112.0.5615.137",  # ~  04-2023
            "112.0.5615.138",  # ~  04-2023
        ],
        "113": [
            "113.0.5672.126",  # ~  05-2023
        ],
        "114": [
            "114.0.5735.90",  # ~   05-2023
            "114.0.5735.133",  # ~  06-2023
            "114.0.5735.198",  # ~  06-2023
        ],
    }

    # sec-ch-ua
    __SEC_CH_UA_BASE_POS: str = "{}, {}, {}"
    __SEC_CH_UA_ITEMS: Dict[int, str] = {
        1: '"Chromium";v="{v}"',
        2: '"Google Chrome";v="{v}"',
        3: '"Not{spec_1}A{spec_2}Brand";v="{v}"',
    }
    __SEC_CH_UA_PLATFORM: List[str] = ["Linux", "Windows"]
    __SEC_CH_UA_PLATFORM_VERSION: Dict[str, List[str]] = {  # OS versions numbers
        "Linux": [
            "6.4.0",
            "6.3.0",
            "6.2.0",
            "6.1.0",
            "6.0.0",
            "5.19.0",
            "5.18.0",
            "5.17.0",
            "5.16.0",
            "5.15.0",
        ],
        "Windows": ["13.0.0", "10.0.0"],
    }
    __SEC_CH_UA_ARCH: List[str] = ["x86"]
    __SEC_CH_UA_BITNESS: List[str] = ["64", "32"]
    __SEC_CH_UA_MODEL: List[str] = ['""']
    __SEC_CH_UA_MOBILE: List[str] = [
        "?0",
        # '?1',
    ]

    # user-agent
    __USER_AGENT_STRING: str = (
        "Mozilla/5.0 ({system_information}) {platform} ({platform_details}) {extensions}"
    )
    __USER_AGENT_SYSTEM_INFORMATION: Dict[str, Dict[str, str] | Dict[str, str]] = {
        "Linux": {"64": "X11; Linux x86_64", "32": "X11; Linux x86_64"},
        "Windows": {
            "64": "Windows NT 10.0; Win64; x64",
            "32": "Windows NT 10.0",
        },
    }
    __USER_AGENT_PLATFORM: Tuple[str, str] = ("AppleWebKit", "537.36")
    __USER_AGENT_PLATFORM_DETAILS: str = "KHTML, like Gecko"
    __USER_AGENT_EXTENSIONS: str = "Chrome/{chrome_v}.0.0.0 Safari/{safari_v}"

    def __random_chrome_version(self) -> Tuple[str, str]:
        ver_num = choice(list(self.CHROME_VERSIONS.keys()))
        ver_val = choice(self.CHROME_VERSIONS.get(ver_num))

        return ver_num, ver_val

    def __build_extensions(self, item: Headers) -> str:
        return self.__USER_AGENT_EXTENSIONS.format(
            chrome_v=item.chrome_version[0],
            safari_v=self.__USER_AGENT_PLATFORM[1],
        )

    @classmethod
    def __random_pick(cls, array: List, remove: bool = True) -> str:
        item = choice(array)

        if remove:
            array.remove(item)

        return item

    @classmethod
    def __not_a_brand__random(cls) -> Tuple[str, str, str, str]:
        # 8 = './'
        # 99 = '_ ' ':-' ' :' ' ;'
        # 24 = '-.' '=?'

        spec_symbols = {
            "8": [
                "./",
            ],
            "24": [
                "-.",
                "=?",
            ],
            "99": [
                "_ ",
                ":-",
                " :",
                " ;",
                "/)",  # 115
            ],
        }

        not_a_brand_v = ["99", "24", "8"]

        v = choice(not_a_brand_v)
        v_full = f"{v}.0.0.0"
        spec_1, spec_2 = choice(spec_symbols.get(v, [0]))

        return v, v_full, spec_1, spec_2

    def __sec_ch_ua_conf__random(self) -> Dict:
        keys = list(self.__SEC_CH_UA_ITEMS.keys())

        return {
            "pos": (
                self.__random_pick(keys),
                self.__random_pick(keys),
                self.__random_pick(keys),
            ),
            "not_a_brand": self.__not_a_brand__random(),
        }

    @classmethod
    def __sec_ch_ua_full_version__random(cls, item: Headers) -> str:
        return f"{item.chrome_version[1]}"

    def __positioning(self, position: int, item: Headers) -> Tuple[str, str, str]:
        sec_ch_ua_items = deepcopy(self.__SEC_CH_UA_ITEMS)

        sec_ch_ua_items[1] = sec_ch_ua_items.get(1).format(
            v=item.chrome_version[position],
        )
        sec_ch_ua_items[2] = sec_ch_ua_items.get(2).format(
            v=item.chrome_version[position],
        )
        sec_ch_ua_items[3] = sec_ch_ua_items.get(3).format(
            v=item.sec_ch_ua_conf["not_a_brand"][position],
            spec_1=item.sec_ch_ua_conf["not_a_brand"][2],
            spec_2=item.sec_ch_ua_conf["not_a_brand"][3],
        )

        pos_1 = sec_ch_ua_items[item.sec_ch_ua_conf["pos"][0]]
        pos_2 = sec_ch_ua_items[item.sec_ch_ua_conf["pos"][1]]
        pos_3 = sec_ch_ua_items[item.sec_ch_ua_conf["pos"][2]]

        return pos_1, pos_2, pos_3

    def __sec_ch_ua__random(self, item: Headers) -> str:
        return self.__SEC_CH_UA_BASE_POS.format(*self.__positioning(0, item))

    def __sec_ch_ua_full_version_list__random(self, item: Headers) -> str:
        return self.__SEC_CH_UA_BASE_POS.format(*self.__positioning(1, item))

    def __sec_ch_ua_platform__random(self) -> str:
        return choice(self.__SEC_CH_UA_PLATFORM)

    def __sec_ch_ua_platform_version__random(self, item: Headers) -> str:
        return choice(self.__SEC_CH_UA_PLATFORM_VERSION[item.sec_ch_ua_platform])

    def __sec_ch_ua_arch__random(self) -> str:
        return choice(self.__SEC_CH_UA_ARCH)

    def __sec_ch_ua_bitness_random(self) -> str:
        return choice(self.__SEC_CH_UA_BITNESS)

    def __sec_ch_ua_model_random(self) -> str:
        return choice(self.__SEC_CH_UA_MODEL)

    def __sec_ch_ua_mobile__random(self) -> str:
        return choice(self.__SEC_CH_UA_MOBILE)

    def __user_agent__random(self, item: Headers) -> str:
        platform = f"{self.__USER_AGENT_PLATFORM[0]}/{self.__USER_AGENT_PLATFORM[1]}"

        extensions = self.__build_extensions(item)
        system_information = self.__USER_AGENT_SYSTEM_INFORMATION[
            item.sec_ch_ua_platform
        ][item.sec_ch_ua_bitness]

        return self.__USER_AGENT_STRING.format(
            system_information=system_information,
            platform=platform,
            platform_details=self.__USER_AGENT_PLATFORM_DETAILS,
            extensions=extensions,
        )

    @classmethod
    def add__sec_ch_ua(cls, item: Headers) -> None:
        """
        Set sec-ch-ua headers:
            - sec-ch-ua
            - sec-ch-ua-full-version
            - sec-ch-ua-full-version-list
            - sec-ch-ua-platform
            - sec-ch-ua-arch
            - sec-ch-ua-bitness
            - sec-ch-ua-mobile
            - sec-ch-ua-model
        """
        item.options["sec-ch-ua"] = item.sec_ch_ua
        item.options["sec-ch-ua-full-version"] = item.sec_ch_ua_full_version
        item.options["sec-ch-ua-full-version-list"] = item.sec_ch_ua_full_version_list
        item.options["sec-ch-ua-platform"] = item.sec_ch_ua_platform
        item.options["sec-ch-ua-platform-version"] = item.sec_ch_ua_full_version_list
        item.options["sec-ch-ua-arch"] = item.sec_ch_ua_arch
        item.options["sec-ch-ua-bitness"] = item.sec_ch_ua_bitness
        item.options["sec-ch-ua-mobile"] = item.sec_ch_ua_mobile
        item.options["sec-ch-ua-model"] = item.sec_ch_ua_model

    @classmethod
    def add__user_agent(cls, item: Headers) -> None:
        """
        Set user-agent header
        """
        item.options["user-agent"] = item.user_agent

    def randomize_headers(self, headers: Headers) -> Dict[str, str]:
        return self.__randomize(headers).headers

    def __randomize(self, item: Headers) -> Headers:
        # Chrome version
        item.chrome_version = self.__random_chrome_version()

        # sec-ch-ua
        item.sec_ch_ua_conf = self.__sec_ch_ua_conf__random()

        item.sec_ch_ua = self.__sec_ch_ua__random(item)
        item.sec_ch_ua_full_version = self.__sec_ch_ua_full_version__random(item)
        item.sec_ch_ua_full_version_list = self.__sec_ch_ua_full_version_list__random(
            item,
        )
        item.sec_ch_ua_platform = self.__sec_ch_ua_platform__random()
        item.sec_ch_ua_platform_version = self.__sec_ch_ua_platform_version__random(item)
        item.sec_ch_ua_mobile = self.__sec_ch_ua_mobile__random()
        item.sec_ch_ua_arch = self.__sec_ch_ua_arch__random()
        item.sec_ch_ua_bitness = self.__sec_ch_ua_bitness_random()
        item.sec_ch_ua_model = self.__sec_ch_ua_model_random()

        self.add__sec_ch_ua(item)

        # user-agent
        item.user_agent = self.__user_agent__random(item)

        self.add__user_agent(item)

        return item


from hypothesis import strategies, given, settings, example
import binascii

@given(data=strategies.binary())
@settings(max_examples=30000, max_iterations=200000)
def test_base64_pack_unpack(data):
    assert binascii.a2b_base64(binascii.b2a_base64(data)) == data

@given(binary_data=strategies.binary())
@settings(max_examples=30000, max_iterations=200000)
def test_hexlify(binary_data):
    assert binascii.unhexlify(binascii.hexlify(binary_data)) == binary_data


from typing import Dict, List

from rest_framework import serializers

from apps.users.models import Profile

META_FIELDS: Dict[str, List[str]] = {
    'PROFILE_SERIALIZER_FIELDS': ['url', 'id', 'avatar_image'],
}

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = META_FIELDS['PROFILE_SERIALIZER_FIELDS']
        extra_kwargs = {
            'url': {'view_name': 'users:profile', 'lookup_field': 'pk'}
        }


from google.cloud import bigquery
import pandas as pd
import numpy as np

confs = {}
Home_Loan = ['Housing Loan', 'Property Loan', 'Leasing', 'Microfinance Housing Loan']
Credit_Loan = ['Credit Card', 'Loan on Credit Card', 'Secured Credit Card', 'Corporate Credit Card', 'Kisan Credit Card']

def get_confs():
    global confs
    conf_df = pd.read_csv("Raw.txt", delimiter='=', names=['key', 'value'])
    confs = dict(zip(conf_df['key'], conf_df['value']))
    return confs

def make_model_base_unique(df):
    df.sort_values(by=['CREDT_RPT_ID', 'DATE_REPORTED'], ascending=[False, False], inplace=True)
    unq_df = df.drop_duplicates(subset='CREDT_RPT_ID', keep='first')
    return unq_df

def model_base_func():
    global confs
    get_confs()  # Call get_confs to update the global confs dictionary
    client = bigquery.Client()
    sub_types = ''
    if confs['Product_Type'] == 'Home Loan':
        for element in Home_Loan:
            sub_types = sub_types + "'" + element + "'" + ','
        sub_types = sub_types[:len(sub_types) - 1]
    else:
        for element in Credit_Loan:
            sub_types = sub_types + "'" + element + "'" + ','
        sub_types = sub_types[:len(sub_types) - 1]

    query = """
    SELECT * FROM `geoalgo-208508.roopya_analytics_dw.v3_account`
    WHERE ACCT_TYPE in ({})
    AND DISBURSED_DT BETWEEN  DATE '{}' AND DATE '{}'
    AND DATE_DIFF(DATE_REPORTED, DISBURSED_DT, MONTH) BETWEEN {} AND {}
    AND OWNERSHIP_IND <> 'Guarantor';""".format(sub_types, confs['DISBURSED_Date_start'], confs['DISBURSED_Date_end'], confs['DATE_DIFF_start'], confs['DATE_DIFF_end'])

    #print(query)

    # Run the query
    query_job = client.query(query)
    results = query_job.result()
    df = results.to_dataframe()

    # Calling the function to sort the values of Credit Report Id and Date Reported and also dropping the duplicates
    df = make_model_base_unique(df)

    # df.to_csv('Model_Base.csv', index=False)
    return df

model_base = model_base_func()
print('Initiating Model Base function')
model_base.to_csv('Model_Base_{}.csv'.format(confs['Product_Type']), index=False)
print('After model_base:', model_base.shape)
print('Initiation done')

def historical_data_func():
    global confs
    get_confs()  # Call get_confs to update the global confs dictionary
    client = bigquery.Client()
    sub_types = ''
    if confs['Product_Type'] == 'Home Loan':
        for element in Home_Loan:
            sub_types = sub_types + "'" + element + "'" + ','
        sub_types = sub_types[:len(sub_types) - 1]
    # elif confs['Product_Type'] == 'Credit Card':
    else:
        for element in Credit_Loan:
            sub_types = sub_types + "'" + element + "'" + ','
        sub_types = sub_types[:len(sub_types) - 1]
    query = """WITH CTE1 AS
            (SELECT * FROM `geoalgo-208508.roopya_analytics_dw.v3_account`
            WHERE ACCT_TYPE in ({})
            AND DISBURSED_DT BETWEEN  DATE '{}' AND DATE '{}'
            AND DATE_DIFF(DATE_REPORTED, DISBURSED_DT, MONTH) BETWEEN {} AND {}
            AND OWNERSHIP_IND <> 'Guarantor'),
            CTE2 AS (
            SELECT T1.* , CTE1.DISBURSED_DT AS Ref_DISBURSED_DT,
            DATE_DIFF(CTE1.DISBURSED_DT, T1.DISBURSED_DT, MONTH) AS Prev_loan_LOR ,
            LENGTH(T1.DPD___HIST)/3 AS Count_DPD_stream,
            DATE_ADD(T1.DATE_REPORTED ,INTERVAL CAST((LENGTH(T1.DPD___HIST)/3*(-1) +1)AS INT64) MONTH) AS DPD_First_month
            FROM `geoalgo-208508.roopya_analytics_dw.v3_account` AS T1
            JOIN CTE1 ON T1.CREDT_RPT_ID = CTE1.CREDT_RPT_ID
            AND CTE1.DISBURSED_DT > T1.DISBURSED_DT)
            SELECT * ,
            DATE_DIFF(Ref_DISBURSED_DT, DPD_First_month, MONTH) AS DPD_month_tb_considered FROM CTE2;""".format(sub_types, confs['DISBURSED_Date_start'], confs['DISBURSED_Date_end'], confs['DATE_DIFF_start'], confs['DATE_DIFF_end'])

    #print(query)
    # Run the query
    query_job = client.query(query)
    results = query_job.result()

    df = results.to_dataframe()

    # df.to_csv('Historical_Data.csv', index=False)
    return df

historical_data = historical_data_func()
print('Initiating Historical function')
historical_data.to_csv('Historical_Data_{}.csv'.format(confs['Product_Type']), index=False)
print('After historical_data:', model_base.shape)
print('Initiation done')

def merged_data_func():
    data1 = pd.read_csv('Model_Base_{}.csv'.format(confs['Product_Type']))
    data2 = pd.read_csv('Historical_Data_{}.csv'.format(confs['Product_Type']))

    def contributor_categories(df):
        # Contributor Type Categories
        categories = {
            'Category 1': ['NBF', 'CCC'],
            'Category 2': ['COP', 'OFI', 'HFC', 'RRB', 'MFI'],
            'Category 3': ['FRB', 'NAB', 'PRB', 'SFB'],
            'Category 4': ['ARC']
        }

        # Create a new column to represent the category for each entity
        df['Category'] = df['CONTRIBUTOR_TYPE'].apply(lambda x: next((key for key, values in categories.items() if x in values), None))

        # Pivot the DataFrame to create separate columns for each category
        ct_df = df.pivot_table(index='CREDT_RPT_ID', columns='Category', values='CONTRIBUTOR_TYPE', aggfunc='count', fill_value=0)

        # Reset the index to make 'Entity' a column again
        ct_df.reset_index(inplace=True)

        # Rename columns for better readability
        ct_df.rename_axis(columns=None, inplace=True)

        # Rename columns for better readability
        ct_df.rename(columns={'Category 1': 'CONTRIBUTOR_TYPE_NBF_CCC',
                              'Category 2': 'CONTRIBUTOR_TYPE_COP_OFI_HFC_RRB_MFI',
                              'Category 3': 'CONTRIBUTOR_TYPE_FRB_NAB_PRB_SFB',
                              'Category 4': 'CONTRIBUTOR_TYPE_ARC'}, inplace=True)

        return ct_df

    def account_status(df):
        categories = {
            'Category 1': ['Active'],
            'Category 2': ['Closed'],
            'Category 3': ['Delinquent', 'Written Off', 'Settled', 'Sold/Purchased', 'Restructured', 'Suit Filed',
                           'WILFUL DEFAULT', 'SUIT FILED (WILFUL DEFAULT)']
        }

        # Create a new column to represent the category for each entity
        df['Acc_St_Category'] = df['ACCOUNT_STATUS'].apply(
            lambda x: next((key for key, values in categories.items() if x in values), None))

        # Pivot the DataFrame to create separate columns for each category
        as_df = df.pivot_table(index='CREDT_RPT_ID', columns='Acc_St_Category', values='ACCOUNT_STATUS',
                              aggfunc='count', fill_value=0)

        # Reset the index to make 'Entity' a column again
        as_df.reset_index(inplace=True)

        # Rename columns for better readability
        as_df.rename_axis(columns=None, inplace=True)

        # Rename columns for better readability
        as_df.rename(columns={'Category 1': 'ACCOUNT_STATUS_Active', 'Category 2': 'ACCOUNT_STATUS_Closed',
                              'Category 3': 'ACCOUNT_STATUS_Others'}, inplace=True)

        return as_df

    print('Data1:', data1.shape)
    print('Data2:', data2.shape)
    contributor_categories_df = contributor_categories(data2)
    print('contributor_categories_df:', contributor_categories_df.shape)
    data1 = pd.merge(data1, contributor_categories_df, on='CREDT_RPT_ID', how='left')
    print('After contributer_categories:', data1.shape)

    account_status_df = account_status(data2)
    print('account_status_df:', account_status_df.shape)
    data1 = pd.merge(data1, account_status_df, on='CREDT_RPT_ID', how='left')
    print('After account_status:', data1.shape)

    def customer_type(df_t1):
        print('Initiating customer type')
        df_t1.drop_duplicates(inplace=True)

        def split_dpd_hist(x):
            if isinstance(x, str) and x != "":
                return [x[i:i + 3] for i in range(0, len(x), 3)]
            else:
                return []

        # Split the 'DPD___HIST' column into 36 separate columns and reverse the order
        df_t1['DPD___HIST'] = df_t1['DPD___HIST'].apply(split_dpd_hist)

        # Reverse the order of values in each list
        df_t1['DPD___HIST'] = df_t1['DPD___HIST'].apply(lambda x: x[::-1])

        # Create 36 new columns for each month
        for i in range(1, 37):
            df_t1[f'M{i}'] = df_t1['DPD___HIST'].apply(lambda x: x[i - 1] if i <= len(x) else '')

        # Replace "XXX" and "DDD" values with "000" in all columns
        for i in range(1, 37):
            df_t1[f'M{i}'] = df_t1[f'M{i}'].replace({"XXX": "000", "DDD": "000"})

        # Define a function to categorize the values into buckets
        def categorize_value(value):
            if value == "000":
                return 0
            elif value.isdigit() and 1 <= int(value) <= 30:
                return 1
            elif value.isdigit() and 31 <= int(value) <= 60:
                return 2
            elif value.isdigit() and 61 <= int(value) <= 90:
                return 3
            elif value.isdigit() and int(value) > 90:
                return 4
            return value  # Return the original value if it doesn't match any criteria

        # Apply the categorize_value function to each of the 36 columns
        for i in range(1, 37):
            column_name = f'M{i}'
            df_t1[column_name] = df_t1[column_name].apply(categorize_value)

        # Convert "month1" through "month36" columns to integers, handling non-numeric values
        for i in range(1, 37):
            column_name = f'M{i}'
            df_t1[column_name] = pd.to_numeric(df_t1[column_name], errors='coerce').fillna(0).astype(int)

        def find_first_delinquency(row):
            for i in range(1, int(confs['Rolling_window']) + 1):
                column_name = f'M{i}'
                if int(row[column_name]) >= int(confs['Bucket']):
                    return i
            return 0  # If no delinquency is found, return 0

        # Apply the find_first_delinquency function to each row to create the "first_delinquency" column
        df_t1['first_delinquency'] = df_t1.apply(find_first_delinquency, axis=1)

        # Create a new column 'Good/Bad' based on the condition
        df_t1['Good/Bad'] = np.where(df_t1['first_delinquency'] == 0, 'Good', 'Bad')

        # Convert 'Good' to 0 and 'Bad' to 1
        df_t1['Good/Bad'] = df_t1['Good/Bad'].replace({'Good': 0, 'Bad': 1})

        print('Customer_type is about to end')

        return df_t1

    def max_delinquency(df_t2):
        print('Initiating max delinquency')
        #df_t2 = df_t1.copy()  # Create a copy of the input dataframe
        df_t2.drop_duplicates(inplace=True)
        print('CREDT_RPT_ID:', len(df_t2['CREDT_RPT_ID'].unique()))
        print('No of rows:', df_t2.shape)

        def split_dpd_hist(x):
            if isinstance(x, str) and x != "":
                return [x[i:i + 3] for i in range(0, len(x), 3)]
            else:
                return []

        # Split the 'DPD___HIST' column into 36 separate columns and reverse the order
        df_t2['DPD___HIST'] = df_t2['DPD___HIST'].apply(split_dpd_hist)
        df_t2['DPD___HIST'] = df_t2['DPD___HIST'].apply(lambda x: x[::-1])

        for i in range(1, 37):
            df_t2[f'M{i}'] = df_t2['DPD___HIST'].apply(lambda x: x[i - 1] if i <= len(x) else '')

        for i in range(1, 37):
            df_t2[f'M{i}'] = df_t2[f'M{i}'].replace({"XXX": "000", "DDD": "000"})

        def categorize_value(value):
            if value == "000":
                return 0
            elif value.isdigit() and 1 <= int(value) <= 30:
                return 1
            elif value.isdigit() and 31 <= int(value) <= 60:
                return 2
            elif value.isdigit() and 61 <= int(value) <= 90:
                return 3
            elif value.isdigit() and int(value) > 90:
                return 4
            return value

        for i in range(1, 37):
            column_name = f'M{i}'
            df_t2[column_name] = df_t2[column_name].apply(categorize_value)

        for i in range(1, 37):
            column_name = f'M{i}'
            df_t2[column_name] = pd.to_numeric(df_t2[column_name], errors='coerce').fillna(0).astype(int)

        def calculate_current_bucket(row):
            dpd_month_tb_considered = row['DPD_month_tb_considered']

            if pd.notna(dpd_month_tb_considered):
                for i in range(1, 37):
                    if dpd_month_tb_considered <= i:
                        return row[f'M{i}']
                else:
                    return row['M36']
            else:
                return pd.NA

        df_t2['CURRENT_BUCKET'] = df_t2.apply(calculate_current_bucket, axis=1)
        df_t2['CURRENT_BUCKET'] = df_t2['CURRENT_BUCKET'].replace('<NA>', np.nan)

        def extract_max_delinquency_status(bucket):
            if pd.notna(bucket):
                if isinstance(bucket, str):
                    statuses = [int(status) for status in bucket.split(',') if status.isdigit() and int(status) in [0, 1, 2, 3]]
                    if statuses:
                        return max(statuses)
            return 0

        df_t2['max_delinquency_status'] = df_t2['CURRENT_BUCKET'].apply(extract_max_delinquency_status)

        df_t2_max_delq = df_t2.groupby(['CREDT_RPT_ID']).agg({
            'max_delinquency_status': 'max'
        }).reset_index()

        print('Max_delinquency function done')
        return df_t2_max_delq

    print('Before Customer_type:', data1.shape)
    data1 = customer_type(data1)
    print('After Customer_type:', data1.shape)

    max_delinquency_df = max_delinquency(data2)
    print('After max_delinquency:', max_delinquency_df.shape)

    print('Before joining max_delinquency:', data1.shape)
    data1 = pd.merge(data1, max_delinquency_df, on='CREDT_RPT_ID', how='left')
    print('After joining max_delinquency:', data1.shape)
    #data1 = pd.merge(data1, customer_type_df, on='CREDT_RPT_ID', how='left')

    return data1

merged_data = merged_data_func()
print('Initiating Merged function')
merged_data.to_csv('Training data_{}.csv'.format(confs['Product_Type']), index=False)
print('Initiation done')


# main.py
import torch
from data_loader import load_data, preprocess_data, create_datasets
from train import train_model, compute_metrics
from inference import load_trained_model, correct_grammar
import config
from transformers import T5Tokenizer

if __name__ == "__main__":
    # Load data
    data = load_data(config.DATA_FILE_PATH)
    print('01')

    # Preprocess data
    preprocessed_data = preprocess_data(data)
    print('02')

    # Create datasets
    tokenizer = T5Tokenizer.from_pretrained(config.MODEL_NAME)
    print('03')

    # Create datasets, passing the tokenizer argument
    train_dataset, test_dataset = create_datasets(preprocessed_data, tokenizer)
    print('04')

    # Train the model
    trained_model = train_model(train_dataset, test_dataset)
    print('05')

    # Save the trained model
    #save_model(trained_model, config.MODEL_OUTPUT_DIR)

    # Load the trained model for inference
    inference_model, inference_tokenizer = load_trained_model(config.INFERENCE_MODEL_PATH, config.TORCH_DEVICE)
    print('06')

    # Perform inference to correct grammar
    input_text = 'He are moving here.'  # Replace with your input sentence
    num_return_sequences = 2  # Number of corrected sequences to generate
    corrected_sentences = correct_grammar(inference_model, inference_tokenizer, input_text, num_return_sequences)

    # Print corrected sentences
    for i, corrected_sentence in enumerate(corrected_sentences):
        print(f'Correction {i+1}: {corrected_sentence}')


#Given an array nums of integers, return how many of them contain an even number of digits.
# Input: nums = [12,345,2,6,7896]
# Output: 2
# 偶數位數的數字有幾個?
nums = [555,901,482,1771]
digit = []
count_even = 0
for i in nums:
    count = 1
    while (i//10) != 0:
        i = i//10
        count += 1
    if count % 2 == 0:
        count_even += 1
print(count_even)


import streamlit as st
import pandas as pd
import scanpy
from SinCel_funcs import *

st.set_page_config(layout="wide")
#Navigation bar
#st.markdown('<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">', unsafe_allow_html=True)
#
#st.markdown("""
#
#  ScRNA-pipl
#  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
#
#  </button>
#

#

#

#        Home (current)
#

#

#

#
#""", unsafe_allow_html=True)

print('Running scRNA Pipeline APP')

TITLE = st.container()
#MARKDOWN = st.container()
#FILE_UPLOADER = st.container()

##st.markdown(
##    '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">',
##    unsafe_allow_html=True,
##)
##
##query_params = st.experimental_get_query_params()
##tabs = ["Home", "About", "Contact"]
##if "tab" in query_params:
##    active_tab = query_params["tab"][0]
##else:
##    active_tab = "Home"
##
##if active_tab not in tabs:
##    st.experimental_set_query_params(tab="Home")
##    active_tab = "Home"
##
##li_items = "".join(
##    f"""
##

##        {t}
##

##    """
##    for t in tabs
##)
##tabs_html = f"""
##

##    {li_items}
##

##"""
##st.markdown(tabs_html, unsafe_allow_html=True)
##st.markdown("
", unsafe_allow_html=True)

with TITLE:
    st.title('Single Cell Analysis Tool Kit')
    st.markdown('
Catalogue of tools for analysing single-cell sequencing data to identifying biomarkers with added exploratory data analysis tools and visualization tools.This tool also supports between the cell types and within the cell conditions
', \
                unsafe_allow_html = True)

def file_uploader():
    col1, col2, col3 = st.columns([3, 1, 1])
    with open('apps/STYLE.css') as f:
        st.markdown(f'', unsafe_allow_html=True)
    with col1:
        uploaded_file = st.file_uploader("Choose .h5ad file")
    if uploaded_file is not None:
        dataf = scanpy.read_h5ad(uploaded_file)
        ob, va = dataf.shape
        all_celltypes, all_samples = dataf.obs['cell_type'].nunique(), dataf.obs['patient_id'].nunique()
        with col2:
            st.markdown(f'''>
Cells

{ob}
''',  unsafe_allow_html=True)
        with col2:
            st.markdown(f'''>
Genes

{va}''',  unsafe_allow_html=True)
        with col3:
            st.markdown(f'''>
Cell Types

{all_celltypes}
''',  unsafe_allow_html=True)
        with col3:
            st.markdown(f'''>
Total samples

{all_samples}
''',  unsafe_allow_html=True)
        return dataf, True
    else:
        st.markdown('
Upload your file
', \
            unsafe_allow_html = True)
        ob, va, all_celltypes, all_samples = 0,0,0,0
        with col2:
            st.markdown(f'''>
Cells

{ob}
''',  unsafe_allow_html=True)
        with col2:
            st.markdown(f'''>
Genes

{va}''',  unsafe_allow_html=True)
        with col3:
            st.markdown(f'''>
Cell Types

{all_celltypes}
''',  unsafe_allow_html=True)
        with col3:
            st.markdown(f'''>
Total samples

{all_samples}
''',  unsafe_allow_html=True)
        return False,False

menu = st.sidebar.radio(
    "",
    ("Summary", "Quality Control", "Vizualization", "Differential Gene Expression"),
)

fileup_container = st.container()

with open('apps/STYLE.css') as f:
    st.markdown(f'', unsafe_allow_html=True)

adata, upfile = file_uploader()
if upfile:
    if menu == 'Summary':
        meta_info(adata)
    elif menu == 'Quality Control':
        qc_info(adata)
    elif menu == 'Vizualization':
        viz_info(adata)
    elif menu == 'Differential Gene Expression':
        deg_info(adata)

st.sidebar.markdown('---')
st.sidebar.write('contact raghukiran812@gmail.com for suggestions')

#9603986566
#31dfa4


def count_char(text, char):
    count = 0
    for c in text:
        if c == char:
            count += 1 #count = count + 1
    return count
filename = input("Write text name: ")
with open(filename) as f:
    text = f.read()
print(count_char(text,'d')) #write any character what you need to count in ' '


__author__ = 'shrivas'
import nltk
taggedWordsList=[];
wordMap={};
class WordTagger(object):

    def postag(contentArray):
           count=0;

           for itemindex in range(len(contentArray)):
                tokenized = nltk.word_tokenize(contentArray[itemindex])
                tagged = nltk.pos_tag(tokenized)
                print("wordmap ****",itemindex,tagged);
                wordMap[itemindex] = tagged;

           return wordMap;

    def __init__(self):
       print("Post tag is working");

# contentArray =['Starbucks is not doing very well lately.',
#                'Overall, while it may seem there is already a Starbucks on every corner, Starbucks still has a lot of room to grow.',
#                'They just began expansion into food products, which has been going quite well so far for them.',
#                'I can attest that my own expenditure when going to Starbucks has increased, in lieu of these food products.',
#                'Starbucks is also indeed expanding their number of stores as well.',
#                'Starbucks still sees strong sales growth here in the united states, and intends to actually continue increasing this.',
#                'Starbucks also has one of the more successful loyalty programs, which accounts for 30%  of all transactions being loyalty-program-based.',
#                'As if news could not get any more positive for the company, Brazilian weather has become ideal for producing coffee beans.',
#                'Brazil is the world\'s #1 coffee producer, the source of about 1/3rd of the entire world\'s supply!',
#                'Given the dry weather, coffee farmers have amped up production, to take as much of an advantage as possible with the dry weather.',
#                'Increase in supply... well you know the rules...']
#
# WordTagger.postag(contentArray)


# -*- coding: utf-8 -*-
"""
Created on Wed Jan  9 15:33:29 2019

@author: mluci
"""

#-7-# Sorting and printing key value pairs #
metals_info={'iron':[2.3, '£56,000', 3], 'aluminium': [30, '£10.90', 2], 'silver': [5.8, '£37.00', 2], 'tin':[1, '7.00', 700 ]}
metals=list(metals_info.keys())
#metals.sort(key=lambda m:metals_info[m], reverse=True)#sort  dictionary by values in reverse order
#keyValue=sorted(metals_info.items(), key=lambda kv:kv[1][1], reverse=True)

for metal in metals:
    if metals_info[metal][0]>8:
        print("{0:>8}={1:5.1f}".format(metal,metals_info[metal][0]))


"""
The HD4480-A02 character table.
"""

# Character shown if no mapping was found
replacement_char = 0x20  # SPACE

# Table with 1:1 mapping
encoding_table = {

    '\u0000': 0x00,  # User defined (CGRAM)
    '\u0001': 0x01,  # User defined (CGRAM)
    '\u0002': 0x02,  # User defined (CGRAM)
    '\u0003': 0x03,  # User defined (CGRAM)
    '\u0004': 0x04,  # User defined (CGRAM)
    '\u0005': 0x05,  # User defined (CGRAM)
    '\u0006': 0x06,  # User defined (CGRAM)
    '\u0007': 0x07,  # User defined (CGRAM)

    '▶':      0x10,  # BLACK RIGHT-POINTING TRIANGLE
    '◀':      0x11,  # BLACK LEFT-POINTING TRIANGLE
    '“':      0x12,  # LEFT DOUBLE QUOTATION MARK
    '”':      0x13,  # RIGHT DOUBLE QUOTATION MARK
    '\u23EB': 0x14,  # BLACK UP-POINTING DOUBLE TRIANGLE
    '\u23EC': 0x15,  # BLACK DOWN-POINTING DOUBLE TRIANGLE
    '●':      0x16,  # BLACK CIRCLE
    '↲':      0x17,  # DOWNWARDS ARROW WITH TIP LEFTWARDS
    '↑':      0x18,  # UPWARDS ARROW
    '↓':      0x19,  # DOWNWARDS ARROW
    '→':      0x1a,  # RIGHTWARDS ARROW
    '←':      0x1b,  # LEFTWARDS ARROW
    '≤':      0x1c,  # LESS-THAN OR EQUAL TO
    '≥':      0x1d,  # GREATER-THAN OR EQUAL TO
    '▲':      0x1e,  # BLACK UP-POINTING TRIANGLE
    '▼':      0x1f,  # BLACK DOWN-POINTING TRIANGLE

    '\u0020': 0x20,  # SPACE
    '\u00A0': 0x20,  # NO-BREAK SPACE
    '!':      0x21,  # EXCLAMATION MARK
    '"':      0x22,  # QUOTATION MARK
    '#':      0x23,  # NUMBER SIGN
    '$':      0x24,  # DOLLAR SIGN
    '%':      0x25,  # PERCENT SIGN
    '&':      0x26,  # AMPERSAND
    "'":      0x27,  # APOSTROPHE
    '(':      0x28,  # LEFT PARENTHESES
    ')':      0x29,  # RIGHT PARENTHESES
    '*':      0x2a,  # ASTERISK
    '+':      0x2b,  # PLUS SIGN
    ',':      0x2c,  # COMMA
    '\u002d': 0x2d,  # HYPHEN-MINUS
    '\u2010': 0x2d,  # HYPHEN
    '\u2011': 0x2d,  # NON-BREAKING HYPHEN
    '\u2012': 0x2d,  # FIGURE DASH
    '\u2013': 0x2d,  # EN DASH
    '\u2014': 0x2d,  # EM DASH
    '\u2015': 0x2d,  # HORIZONTAL BAR
    '.':      0x2e,  # FULL STOP
    '/':      0x2f,  # SOLIDUS

    '0':      0x30,  # DIGIT ZERO
    '1':      0x31,  # DIGIT ONE
    '2':      0x32,  # DIGIT TWO
    '3':      0x33,  # DIGIT THREE
    '4':      0x34,  # DIGIT FOUR
    '5':      0x35,  # DIGIT FIVE
    '6':      0x36,  # DIGIT SIX
    '7':      0x37,  # DIGIT SEVEN
    '8':      0x38,  # DIGIT EIGHT
    '9':      0x39,  # DIGIT NINE
    ':':      0x3a,  # COLON
    ';':      0x3b,  # SEMICOLON
    '<':      0x3c,  # LESS-THAN SIGN
    '=':      0x3d,  # EQUALS SIGN
    '>':      0x3e,  # GREATER-THAN SIGN
    '?':      0x3f,  # QUESTION MARK

    '@':      0x40,  # COMMERCIAL AT
    'A':      0x41,  # LATIN CAPITAL LETTER A
    'B':      0x42,  # LATIN CAPITAL LETTER B
    'C':      0x43,  # LATIN CAPITAL LETTER C
    'D':      0x44,  # LATIN CAPITAL LETTER D
    'E':      0x45,  # LATIN CAPITAL LETTER E
    'F':      0x46,  # LATIN CAPITAL LETTER F
    'G':      0x47,  # LATIN CAPITAL LETTER G
    'H':      0x48,  # LATIN CAPITAL LETTER H
    'I':      0x49,  # LATIN CAPITAL LETTER I
    'J':      0x4a,  # LATIN CAPITAL LETTER J
    'K':      0x4b,  # LATIN CAPITAL LETTER K
    'L':      0x4c,  # LATIN CAPITAL LETTER L
    'M':      0x4d,  # LATIN CAPITAL LETTER M
    'N':      0x4e,  # LATIN CAPITAL LETTER N
    'O':      0x4f,  # LATIN CAPITAL LETTER O

    'P':      0x50,  # LATIN CAPITAL LETTER P
    'Q':      0x51,  # LATIN CAPITAL LETTER Q
    'R':      0x52,  # LATIN CAPITAL LETTER R
    'S':      0x53,  # LATIN CAPITAL LETTER S
    'T':      0x54,  # LATIN CAPITAL LETTER T
    'U':      0x55,  # LATIN CAPITAL LETTER U
    'V':      0x56,  # LATIN CAPITAL LETTER V
    'W':      0x57,  # LATIN CAPITAL LETTER W
    'X':      0x58,  # LATIN CAPITAL LETTER X
    'Y':      0x59,  # LATIN CAPITAL LETTER Y
    'Z':      0x5a,  # LATIN CAPITAL LETTER Z
    '[':      0x5b,  # LEFT SQUARE BRACKET
    '\\':     0x5c,  # REVERSE SOLIDUS
    ']':      0x5d,  # RIGHT SQUARE BRACKET
    '^':      0x5e,  # CIRCUMFLEX ACCENT
    '_':      0x5f,  # LOW LINE

    '`':      0x60,  # GRAVE ACCENT
    'a':      0x61,  # LATIN SMALL LETTER A
    'b':      0x62,  # LATIN SMALL LETTER B
    'c':      0x63,  # LATIN SMALL LETTER C
    'd':      0x64,  # LATIN SMALL LETTER D
    'e':      0x65,  # LATIN SMALL LETTER E
    'f':      0x66,  # LATIN SMALL LETTER F
    'g':      0x67,  # LATIN SMALL LETTER G
    'h':      0x68,  # LATIN SMALL LETTER H
    'i':      0x69,  # LATIN SMALL LETTER I
    'j':      0x6a,  # LATIN SMALL LETTER J
    'k':      0x6b,  # LATIN SMALL LETTER K
    'l':      0x6c,  # LATIN SMALL LETTER L
    'm':      0x6d,  # LATIN SMALL LETTER M
    'n':      0x6e,  # LATIN SMALL LETTER N
    'o':      0x6f,  # LATIN SMALL LETTER O

    'p':      0x70,  # LATIN SMALL LETTER P
    'q':      0x71,  # LATIN SMALL LETTER Q
    'r':      0x72,  # LATIN SMALL LETTER R
    's':      0x73,  # LATIN SMALL LETTER S
    't':      0x74,  # LATIN SMALL LETTER T
    'u':      0x75,  # LATIN SMALL LETTER U
    'v':      0x76,  # LATIN SMALL LETTER V
    'w':      0x77,  # LATIN SMALL LETTER W
    'x':      0x78,  # LATIN SMALL LETTER X
    'y':      0x79,  # LATIN SMALL LETTER Y
    'z':      0x7a,  # LATIN SMALL LETTER Z
    '{':      0x7b,  # LEFT CURLY BRACKET
    '|':      0x7c,  # VERTICAL LINE
    '}':      0x7d,  # RIGHT CURLY BRACKET
    '~':      0x7e,  # TILDE
    '⌂':      0x7f,  # HOUSE

    'Б':      0x80,  # CYRILLIC CAPITAL LETTER BE
    'Д':      0x81,  # CYRILLIC CAPITAL LETTER DE
    'Ж':      0x82,  # CYRILLIC CAPITAL LETTER ZHE
    'З':      0x83,  # CYRILLIC CAPITAL LETTER ZE
    'И':      0x84,  # CYRILLIC CAPITAL LETTER I
    'Й':      0x85,  # CYRILLIC CAPITAL LETTER SHORT I
    'Л':      0x86,  # CYRILLIC CAPITAL LETTER EL
    'П':      0x87,  # CYRILLIC CAPITAL LETTER PE
    'У':      0x88,  # CYRILLIC CAPITAL LETTER U
    'Ц':      0x89,  # CYRILLIC CAPITAL LETTER TSE
    'Ч':      0x8a,  # CYRILLIC CAPITAL LETTER CHE
    'Ш':      0x8b,  # CYRILLIC CAPITAL LETTER SHA
    'Щ':      0x8c,  # CYRILLIC CAPITAL LETTER SHCHA
    'Ъ':      0x8d,  # CYRILLIC CAPITAL LETTER HARD SIGN
    'Ы':      0x8e,  # CYRILLIC CAPITAL LETTER YERU
    'Э':      0x8f,  # CYRILLIC CAPITAL LETTER E

    'α':      0x90,  # GREEK SMALL LETTER ALPHA
    '♪':      0x91,  # EIGHTH NOTE
    'Γ':      0x92,  # GREEK CAPITAL LETTER GAMMA
    'π':      0x93,  # GREEK SMALL LETTER PI
    'Σ':      0x94,  # GREEK CAPITAL LETTER SIGMA
    '\u2211': 0x94,  # N-ARY SUMMATION
    'σ':      0x95,  # GREEK SMALL LETTER SIGMA
    '♬':      0x96,  # BEAMED SIXTEENTH NOTES
    'τ':      0x97,  # GREEK SMALL LETTER TAU
    '\U0001F514': 0x98,  # BELL
    'θ':      0x99,  # GREEK SMALL LETTER THETA
    '\u03A9': 0x9a,  # GREEK CAPITAL LETTER OMEGA
    '\u2126': 0x9a,  # OHM SIGN
    'δ':      0x9b,  # GREEK SMALL LETTER DELTA
    '∞':      0x9c,  # INFINITY
    '\u2661': 0x9d,  # WHITE HEART SUIT
    '\u2665': 0x9d,  # BLACK HEART SUIT
    '\u2764': 0x9d,  # HEAVY BLACK HEART
    'ε':      0x9e,  # GREEK SMALL LETTER EPSILON
    '\u2229': 0x9f,  # INTERSECTION

    '\u2016': 0xa0,  # DOUBLE VERTICAL LINE
    '¡':      0xa1,  # INVERTED EXCLAMATION MARK
    '¢':      0xa2,  # CENT SIGN
    '£':      0xa3,  # POUND SIGN
    '¤':      0xa4,  # CURRENCY SIGN
    '¥':      0xa5,  # YEN SIGN
    '¦':      0xa6,  # BROKEN BAR
    '§':      0xa7,  # SECTION SIGN
    'ƒ':      0xa8,  # LATIN SMALL LETTER F WITH HOOK
    '©':      0xa9,  # COPYRIGHT SIGN
    'ª':      0xaa,  # FEMININE ORDINAL INDICATOR
    '«':      0xab,  # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
    'Ю':      0xac,  # CYRILLIC CAPITAL LETTER YU
    'Я':      0xad,  # CYRILLIC CAPITAL LETTER YA
    '®':      0xae,  # REGISTERED SIGN
    '´':      0xaf,  # ACUTE ACCENT

    'ᴼ':      0xb0,  # MODIFIER LETTER CAPITAL O
    '±':      0xb1,  # PLUS-MINUS SIGN
    '²':      0xb2,  # SUPERSCRIPT TWO
    '³':      0xb3,  # SUPERSCRIPT THREE
    'μ':      0xb5,  # GREEK SMALL LETTER MU
    '¶':      0xb6,  # PILCROW SIGN
    '·':      0xb7,  # MIDDLE DOT
    'ω':      0xb8,  # GREEK SMALL LETTER OMEGA
    '¹':      0xb9,  # SUPERSCRIPT ONE
    'º':      0xba,  # MASCULINE ORDINAL INDICATOR
    '»':      0xbb,  # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
    '¼':      0xbc,  # VULGAR FRACTION ONE QUARTER
    '½':      0xbd,  # VULGAR FRACTION ONE HALF
    '¾':      0xbe,  # VULGAR FRACTION THREE QUARTERS
    '¿':      0xbf,  # INVERTED QUESTION MARK

    'À':      0xc0,  # LATIN CAPITAL LETTER A WITH GRAVE
    'Á':      0xc1,  # LATIN CAPITAL LETTER A WITH ACUTE
    'Â':      0xc2,  # LATIN CAPITAL LETTER A WITH CIRCUMFLEX
    'Ã':      0xc3,  # LATIN CAPITAL LETTER A WITH TILDE
    'Ä':      0xc4,  # LATIN CAPITAL LETTER A WITH DIAERESIS
    'Å':      0xc5,  # LATIN CAPITAL LETTER A WITH RING ABOVE
    'Æ':      0xc6,  # LATIN CAPITAL LETTER AE
    'Ç':      0xc7,  # LATIN CAPITAL LETTER C WITH CEDILLA
    'È':      0xc8,  # LATIN CAPITAL LETTER E WITH GRAVE
    'É':      0xc9,  # LATIN CAPITAL LETTER E WITH ACUTE
    'Ê':      0xca,  # LATIN CAPITAL LETTER E WITH CIRCUMFLEX
    'Ë':      0xcb,  # LATIN CAPITAL LETTER E WITH DIAERESIS
    'Ì':      0xcc,  # LATIN CAPITAL LETTER I WITH GRAVE
    'Í':      0xcd,  # LATIN CAPITAL LETTER I WITH ACUTE
    'Î':      0xce,  # LATIN CAPITAL LETTER I WITH CIRCUMFLEX
    'Ï':      0xcf,  # LATIN CAPITAL LETTER I WITH DIAERESIS

    'Ð':      0xd0,  # LATIN CAPITAL LETTER ETH
    'Ñ':      0xd1,  # LATIN CAPITAL LETTER N WITH TILDE
    'Ò':      0xd2,  # LATIN CAPITAL LETTER O WITH GRAVE
    'Ó':      0xd3,  # LATIN CAPITAL LETTER O WITH ACUTE
    'Ô':      0xd4,  # LATIN CAPITAL LETTER O WITH CIRCUMFLEX
    'Õ':      0xd5,  # LATIN CAPITAL LETTER O WITH TILDE
    'Ö':      0xd6,  # LATIN CAPITAL LETTER O WITH DIAERESIS
    '×':      0xd7,  # MULTIPLICATION SIGN
    'Φ':      0xd8,  # GREEK CAPITAL LETTER PHI
    'Ù':      0xd9,  # LATIN CAPITAL LETTER U WITH GRAVE
    'Ú':      0xda,  # LATIN CAPITAL LETTER U WITH ACUTE
    'Û':      0xdb,  # LATIN CAPITAL LETTER U WITH CIRCUMFLEX
    'Ü':      0xdc,  # LATIN CAPITAL LETTER U WITH DIAERESIS
    'Ý':      0xdd,  # LATIN CAPITAL LETTER Y WITH ACUTE
    'Þ':      0xde,  # LATIN CAPITAL LETTER THORN
    'ß':      0xdf,  # LATIN SMALL LETTER SHARP S

    'à':      0xe0,  # LATIN SMALL LETTER A WITH GRAVE
    'á':      0xe1,  # LATIN SMALL LETTER A WITH ACUTE
    'â':      0xe2,  # LATIN SMALL LETTER A WITH CIRCUMFLEX
    'ã':      0xe3,  # LATIN SMALL LETTER A WITH TILDE
    'ä':      0xe4,  # LATIN SMALL LETTER A WITH DIAERESIS
    'å':      0xe5,  # LATIN SMALL LETTER A WITH RING ABOVE
    'æ':      0xe6,  # LATIN SMALL LETTER AE
    'ç':      0xe7,  # LATIN SMALL LETTER C WITH CEDILLA
    'è':      0xe8,  # LATIN SMALL LETTER E WITH GRAVE
    'é':      0xe9,  # LATIN SMALL LETTER E WITH ACUTE
    'ê':      0xea,  # LATIN SMALL LETTER E WITH CIRCUMFLEX
    'ë':      0xeb,  # LATIN SMALL LETTER E WITH DIAERESIS
    'ì':      0xec,  # LATIN SMALL LETTER I WITH GRAVE
    'í':      0xed,  # LATIN SMALL LETTER I WITH ACUTE
    'î':      0xee,  # LATIN SMALL LETTER I WITH CIRCUMFLEX
    'ï':      0xef,  # LATIN SMALL LETTER I WITH DIAERESIS

    'ð':      0xf0,  # LATIN SMALL LETTER ETH
    'ñ':      0xf1,  # LATIN SMALL LETTER N WITH TILDE
    'ò':      0xf2,  # LATIN SMALL LETTER O WITH GRAVE
    'ó':      0xf3,  # LATIN SMALL LETTER O WITH ACUTE
    'ô':      0xf4,  # LATIN SMALL LETTER O WITH CIRCUMFLEX
    'õ':      0xf5,  # LATIN SMALL LETTER O WITH TILDE
    'ö':      0xf6,  # LATIN SMALL LETTER O WITH DIAERESIS
    '÷':      0xf7,  # DIVISION SIGN
    'ø':      0xf8,  # LATIN SMALL LETTER O WITH STROKE
    'ù':      0xf9,  # LATIN SMALL LETTER U WITH GRAVE
    'ú':      0xfa,  # LATIN SMALL LETTER U WITH ACUTE
    'û':      0xfb,  # LATIN SMALL LETTER U WITH CIRCUMFLEX
    'ü':      0xfc,  # LATIN SMALL LETTER U WITH DIAERESIS
    'ý':      0xfd,  # LATIN SMALL LETTER Y WITH ACUTE
    'þ':      0xfe,  # LATIN SMALL LETTER THORN
    'ÿ':      0xff,  # LATIN SMALL LETTER Y WITH DIAERESIS

}

# Table with combined mappings
combined_chars_lookahead = 0
combined_chars = {}


import numpy as np
import pickle as pkl

with open('results.pkl', 'rb') as f:
    [control_results,patient_results] = pkl.load(f)
f.close()

def calculate_mean_std(group_results):
    group_results_np = np.array(group_results)
    mean_params = np.mean(group_results_np, axis=0)
    std_params = np.std(group_results_np, axis=0)
    return mean_params, std_params

def calculate_z_scores(patient_results, mean_params, std_params):
    patient_results_np = np.array(patient_results)
    z_scores = (patient_results_np - mean_params) / std_params
    return z_scores

mean_control_params, std_control_params = calculate_mean_std(control_results)
z_scores = calculate_z_scores(patient_results, mean_control_params, std_control_params)

# Define a threshold for abnormality (e.g., 1.96 for a 95% confidence interval)
threshold = 1.96

# Find the abnormal voxels
abnormal_voxels = np.abs(z_scores) > threshold

print("Z-scores:", z_scores)
print("Abnormal voxels:", abnormal_voxels)


#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial

In this example, we create three toggle buttons.
They will control the background color of a
QtGui.QFrame.

author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""

import sys
import serial
from PyQt4 import QtGui, QtCore

class CommandInterface:
    def open(self, aport='/dev/ttyAMA0', abaudrate=115200) :
        self.sp = serial.Serial(
            port=aport,
            baudrate=abaudrate,     # baudrate
            bytesize=8,             # number of databits
            parity=serial.PARITY_EVEN,
            stopbits=1,
            xonxoff=0,              # enable software flow control
            rtscts=0,               # disable RTS/CTS flow control
            timeout=5               # set a timeout value, None for waiting forever
        )

    def write(self, cmd):
        self.sp.write(chr(cmd))

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        conf = {
                'port': '/dev/ttyAMA0',
                'baud': 115200,
                'address': 0x08000000,
                'erase': 0,
                'write': 0,
                'verify': 0,
                'read': 0,
            }

        self.col = QtGui.QColor(0, 0, 0)
        self.uart = CommandInterface()
        self.uart.open(conf['port'], conf['baud'])

        RedLabel=QtGui.QLabel("Red",self)
        RedLabel.setGeometry(60, 20, 30, 10)

        BlueLabel=QtGui.QLabel("Blue",self)
        BlueLabel.setGeometry(55, 60, 40, 10)

        GreenLabel=QtGui.QLabel("Green",self)
        GreenLabel.setGeometry(50, 100, 50, 10)

        Redsld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        Redsld.setFocusPolicy(QtCore.Qt.NoFocus)
        Redsld.setGeometry(100, 20, 260, 30)
        Redsld.valueChanged[int].connect(self.RedchangeValue)

        Bluesld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        Bluesld.setFocusPolicy(QtCore.Qt.NoFocus)
        Bluesld.setGeometry(100, 60, 260, 30)
        Bluesld.valueChanged[int].connect(self.BluechangeValue)

        Greensld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        Greensld.setFocusPolicy(QtCore.Qt.NoFocus)
        Greensld.setGeometry(100, 100, 260, 30)
        Greensld.valueChanged[int].connect(self.GreenchangeValue)

        Redsld.setRange(0,255)
        Bluesld.setRange(0,255)
        Greensld.setRange(0,255)

        Redsld.setObjectName("Red")
        Bluesld.setObjectName("Blue")
        Greensld.setObjectName("Green")

        GreenLabel=QtGui.QLabel("Color show below:",self)
        GreenLabel.setGeometry(100, 180, 200, 10)

        self.square = QtGui.QFrame(self)
        self.square.setGeometry(100, 200, 250, 250)
        self.square.setStyleSheet("QWidget { background-color: %s }" %
            self.col.name())

        self.setGeometry(500, 500, 500, 500)
        self.setWindowTitle('color set')
        self.show()

    def RedchangeValue(self, value):
        if value >255:
            value =0
        print("Red value = %(value)d " % {'value': value})
        self.col.setRed(value)
        self.uart.write(165)
        self.uart.write(64)
        self.uart.write(5)
        self.uart.write(1)
        self.uart.write(1)
        self.uart.write(value)
        self.uart.write(90)
        self.square.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def BluechangeValue(self, value):
        if value >255:
            value =0
        print("Blue value = %(value)d " % {'value': value})
        self.col.setBlue(value)
        self.uart.write(165)
        self.uart.write(64)
        self.uart.write(5)
        self.uart.write(3)
        self.uart.write(1)
        self.uart.write(value)
        self.uart.write(90)
        self.square.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def GreenchangeValue(self, value):
        if value >255:
            value =0
        print("Green value = %(value)d " % {'value': value})
        self.col.setGreen(value)
        self.uart.write(165)
        self.uart.write(64)
        self.uart.write(5)
        self.uart.write(2)
        self.uart.write(1)
        self.uart.write(value)
        self.uart.write(90)
        self.square.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

def main():

    app = QtGui.QApplication(sys.argv)

    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


from cnn import *

class AlexNet(Network):

	"""
	def __init__(self, insize = None, model_json = None, weights_h5 = None, **kwargs):
 		super(AlexNet, self).__init__(insize, model_json, weights_h5, **kwargs)
	"""

	def build_architecture(self, insize, **kwargs):

		try:
			self.drop_conv = float(kwargs['drop_conv'])
			self.drop_dense = float(kwargs['drop_dense'])
		except KeyError as e:
			raise(TypeError('build_architecture: Missing argument: %s' % e))

		#super(ClassName, self).__init__()

		self.classifier = Sequential()
		self.classifier.add(ZeroPadding2D(input_shape = (insize[0], insize[1], 3), padding = 2))
		self.classifier.add(Conv2D(32, (5, 5), kernel_initializer = RandomNormal(0, 0.0001), activation = 'relu'))
		self.classifier.add(Dropout(self.drop_conv))
		self.classifier.add(MaxPooling2D(pool_size = (3, 3), strides = 2))

		self.classifier.add(ZeroPadding2D(padding = 2))
		self.classifier.add(Conv2D(32, (5, 5), kernel_initializer = RandomNormal(0, 0.01), activation = 'relu'))
		self.classifier.add(Dropout(self.drop_conv))
		self.classifier.add(AveragePooling2D(pool_size = (3, 3), strides = 2))

		self.classifier.add(ZeroPadding2D(padding = 2))
		self.classifier.add(Conv2D(64, (5, 5), kernel_initializer = RandomNormal(0, 0.0001), activation = 'relu'))
		self.classifier.add(Dropout(self.drop_conv))
		self.classifier.add(AveragePooling2D(pool_size = (3, 3), strides = 2))

		self.classifier.add(Flatten())

		self.classifier.add(Dense(units = 64, activation = 'relu'))
		self.classifier.add(Dropout(self.drop_dense))
		self.classifier.add(Dense(units = 2, activation = 'softmax'))

	"""
	# Command line parameters
	parser = argparse.ArgumentParser( description = 'Training utilities for the cancer dataset' )
	parser.add_argument( '-t', dest = 'training', metavar = 'Training set', required = True, help = 'Location of the training set' )
	parser.add_argument( '-v', dest = 'test', metavar = 'Test set', required = True, help = 'Location of the test set' )
	parser.add_argument( '-e', dest = 'epochs', metavar = 'Epochs', type = int, default = 1, help = 'Number of epochs' )
	parser.add_argument( '-b', dest = 'batch_size', metavar = 'Batch size', type = int, default = 1, help = 'Size of batch' )
	parser.add_argument( '-s', dest = 'img_size', metavar = 'Image size', type = int, default = 32, help = 'Dimensions of image' )
	parser.add_argument( '-lr', dest = 'lr', metavar = 'Learning rate', type = float, default = 0.0001, help = 'Learning rate of the network' )
	parser.add_argument( '-m', dest = 'momentum', metavar = 'Momentum', type = float, default = 0.9, help = 'Momentum of SGD' )
	parser.add_argument( '-dr', dest = 'decay_rate', metavar = 'Decay rate', type = float, default = 4**(-5), help = 'Dacay rate of SGD' )
	parser.add_argument( '--val', dest = 'validate', action = 'store_true', help = 'Use validation during training' )

	args = parser.parse_args()

	training = args.training
	test = args.test
	epochs = args.epochs
	batch_size = args.batch_size
	img_size = args.img_size
	lr = args.lr
	momentum = args.momentum
	decay_rate = args.decay_rate
	validate = args.validate
	"""

	"""
	insize = 32
	classifier = Sequential()

	classifier.add(ZeroPadding2D(input_shape = (insize, insize, 3), padding = 2))
	classifier.add(Conv2D(32, (5, 5), kernel_initializer = RandomNormal(0, 0.0001), activation = 'relu'))
	classifier.add(MaxPooling2D(pool_size = (3, 3), strides = 2))

	classifier.add(ZeroPadding2D(padding = 2))
	classifier.add(Conv2D(32, (5, 5), kernel_initializer = RandomNormal(0, 0.01), activation = 'relu'))
	classifier.add(AveragePooling2D(pool_size = (3, 3), strides = 2))

	classifier.add(ZeroPadding2D(padding = 2))
	classifier.add(Conv2D(64, (5, 5), kernel_initializer = RandomNormal(0, 0.0001), activation = 'relu'))
	classifier.add(AveragePooling2D(pool_size = (3, 3), strides = 2))

	classifier.add(Flatten())

	classifier.add(Dense(units = 64, activation = 'relu'))
	classifier.add(Dense(units = 2, activation = 'softmax'))
	"""

	#print(np.count_nonzero(preds))
	#a= list(map(lambda x: 0 if 'SOB_B' in x else 1, os.listdir(test+'/benign')))
	#print(a)

	"""
	# load json and create model
	json_file = open('model.json', 'r')
	loaded_model_json = json_file.read()
	json_file.close()
	loaded_model = model_from_json(loaded_model_json)
	# load weights into new model
	loaded_model.load_weights("model.h5")
	print("Loaded model from disk")

	loaded_model.compile(optimizer = SGD(lr = 10**(-6), momentum = 0.9, decay = 4**(-5)), loss = 'categorical_crossentropy', metrics = ['accuracy'])

	print(loaded_model.evaluate_generator(training_set, 6518/128))
	"""

	"""
	test_set = test_datagen.flow_from_directory(test,
    												target_size = (32, 32),
    												batch_size = 54,
    												class_mode = 'categorical',
    												shuffle = False)
    """


def test():
    N,K = list(map(int, input().split()))
    nums = list(map(int, input().split()))
    for i in range(0,N,K):
        if i+K >= len(nums):
            nums = nums[:i] + nums[i:][::-1]
        else:
            nums = nums[:i] + nums[i:i+K][::-1] + nums[i+K:]
    result.append(nums)

result = []
for i in range(int(input())):
    test()

for i in result:
    print(' '.join(list(map(str, i))), end=' \n')


def point_in_polygon(point, polygon):
    x, y = point
    inside = False
    n = len(polygon)
    p1x, p1y = polygon[0]
    for i in range(1, n + 1):
        if point[0] == p1x and point[1] == p1y:
            return True
        p2x, p2y = polygon[i % n]
        if y > min(p1y, p2y):
            if y <= max(p1y, p2y):
                if x <= max(p1x, p2x):
                    if p1y != p2y:
                        xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x, p1y = p2x, p2y
    return inside


import sys
import os
from vm_parser import Parser
from vm_code_writer import code_writer

#Si es un directorio
if len(sys.argv)==2 and '.vm' not in sys.argv[1]:
    #Si le falta el último slash se lo agrego para evitar errores en dirección
    if sys.argv[1][-1] != '/':
        sys.argv[1]=sys.argv[1]+'/'
    #El nombre del archivo .asm a generar es el mismo del directorio
    outname= sys.argv[1][:-1]+'/'+sys.argv[1].split('/')[-2]
    dirs = []
    # Voy por cada f (file) en el directorio y lo agrego a la lista de archivos a traducir
    for r, d, f in os.walk(sys.argv[1]):
        for file in f:
            #Solo tomo los .vm
            if '.vm' in file:
                dirs.append(os.path.join(r, file))
#Si es un archivo .vm lo tomo solito
else:
    dirs=sys.argv
    del dirs[0]
    outname=dirs[0].split('.vm')[0]
#Creo el codewriter con el nombre del archivo en el cual voy a escribir
cw = code_writer(outname)
#Si es un directorio escribo el llamado a Sys.init
if len(dirs)>1:
    cw.writeInit()
#Itero sobre cada file
for file_path in dirs:
    #Creo parser y  pongo el codewriter con el file que estoy analizando
    parser = Parser(file_path)
    cw.setFileName(file_path)
    # Itero por cada linea
    while parser.hasMoreCommands():
        parser.advance()
        if parser.commandType() == 'C_PUSH':
            cw.writePushPop('C_PUSH', parser.arg1(), parser.arg2())
        elif parser.commandType() == 'C_POP':
            cw.writePushPop('C_POP', parser.arg1(), parser.arg2())
        elif parser.commandType() == 'C_ARITHMETIC':
            cw.writeArithmetic(parser.arg1())
        elif parser.commandType() == 'C_LABEL':
            cw.writeLabel(parser.arg1())
        elif parser.commandType() == 'C_IF':
            cw.writeIf(parser.arg1())
        elif parser.commandType() == 'C_GOTO':
            cw.writeGoto(parser.arg1())
        elif parser.commandType() == 'C_CALL':
            cw.writeCall(parser.arg1(), parser.arg2())
        elif parser.commandType() == 'C_FUNCTION':
            cw.writeFunction(parser.arg1(), parser.arg2())
        elif parser.commandType() == 'C_RETURN':
            cw.writeReturn()
cw.closeAll()


from matplotlib.ft2font import BOLD
from src.utils import (
    get_model_dir,
    ham10000_metadata,
    short_to_full_name_dict,
    full_name_to_short_dict,
    bening_or_malignant_dict,
    get_image_path,
    calculate_metrics,
)
from PIL import Image
from src.config import only_lesion_id, resnet_mixup_id
from sklearn.metrics import confusion_matrix
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import scipy.stats as stats
from fastai.interpret import ClassificationInterpretation

def build_segmented_prediction_strength():
    print("Building segmented prediction strength...")

    # Read the validation results
    predictions = pd.read_csv(f"{get_model_dir(only_lesion_id)}/predictions.csv")
    only_lesion_predictions = pd.read_csv(
        f"{get_model_dir(only_lesion_id)}/only_lesions_predictions.csv"
    )

    # Merge with the metadata
    predictions = predictions.merge(ham10000_metadata, on="image_id", how="left")
    only_lesion_predictions = only_lesion_predictions.merge(
        ham10000_metadata, on="image_id", how="left"
    )

    predictions["real_class"] = predictions.dx.map(lambda x: short_to_full_name_dict[x])
    only_lesion_predictions["real_class"] = only_lesion_predictions.dx.map(
        lambda x: short_to_full_name_dict[x]
    )

    predictions["correct"] = predictions.classification == predictions.real_class
    only_lesion_predictions["correct"] = (
        only_lesion_predictions.classification == only_lesion_predictions.real_class
    )

    # Make a confusion matrix
    confusion_matrix = (
        predictions.groupby(["real_class", "classification"]).size().unstack()
    )
    only_lesion_confusion_matrix = (
        only_lesion_predictions.groupby(["real_class", "classification"])
        .size()
        .unstack()
    )

    # Normalize over the x axis
    confusion_matrix_normalized = confusion_matrix.div(
        confusion_matrix.sum(axis=1), axis=0
    )
    only_lesion_confusion_matrix_normalized = only_lesion_confusion_matrix.div(
        only_lesion_confusion_matrix.sum(axis=1), axis=0
    )

    confusion_matrix_normalized.columns = confusion_matrix_normalized.columns.map(
        lambda x: full_name_to_short_dict[x]
    )
    only_lesion_confusion_matrix_normalized.columns = (
        only_lesion_confusion_matrix_normalized.columns.map(
            lambda x: full_name_to_short_dict[x]
        )
    )

    confusion_matrix_normalized.index = confusion_matrix_normalized.index.map(
        lambda x: full_name_to_short_dict[x]
    )
    only_lesion_confusion_matrix_normalized.index = (
        only_lesion_confusion_matrix_normalized.index.map(
            lambda x: full_name_to_short_dict[x]
        )
    )

    # Plot the confusion matrix using seaborn
    plt.figure(figsize=(8, 8))
    p = sns.heatmap(
        confusion_matrix_normalized, annot=True, cmap="Blues", annot_kws={"size": 10}
    )
    p.set_xlabel("Predicted label")
    p.set_ylabel("True label")
    plt.savefig("only_lesion_on_original_confusion_matrix.png")

    # Plot the confusion matrix using seaborn
    plt.figure(figsize=(8, 8))
    p = sns.heatmap(
        only_lesion_confusion_matrix_normalized,
        annot=True,
        cmap="Blues",
        annot_kws={"size": 10},
    )
    p.set_xlabel("Predicted label")
    p.set_ylabel("True label")
    plt.savefig("only_lesion_on_segmented_confusion_matrix.png")

    # Calculate precision, recall and f1 score on each of the two datasets

    # With recall we think malignant recall
    # With precision we calculate both malignant precision and general class precision
    segmented_on_normal_metrics = calculate_metrics(only_lesion_id, "normal")
    segmented_on_only_lesion_metrics = calculate_metrics(only_lesion_id, "only_lesions")
    normal_on_normal_metrics = calculate_metrics(resnet_mixup_id, "normal")
    normal_on_segmented_metrics = calculate_metrics(resnet_mixup_id, "only_lesions")

    full_image_label = "Full images"
    segmented_image_label = "Segmented"
    index = pd.MultiIndex.from_tuples(
        [
            (full_image_label, full_image_label),
            (full_image_label, segmented_image_label),
            (segmented_image_label, full_image_label),
            (segmented_image_label, segmented_image_label),
        ],
        names=["Training set", "Evaluation set"],
    )

    score_table = pd.DataFrame(
        {
            "Multi-class precision": [
                normal_on_normal_metrics["mc-precision"],
                normal_on_segmented_metrics["mc-precision"],
                segmented_on_normal_metrics["mc-precision"],
                segmented_on_only_lesion_metrics["mc-precision"],
            ],
            "Multi-class F1 score": [
                normal_on_normal_metrics["mc-f1"],
                normal_on_segmented_metrics["mc-f1"],
                segmented_on_normal_metrics["mc-f1"],
                segmented_on_only_lesion_metrics["mc-f1"],
            ],
            "Binary precision": [
                normal_on_normal_metrics["b-precision"],
                normal_on_segmented_metrics["b-precision"],
                segmented_on_normal_metrics["b-precision"],
                segmented_on_only_lesion_metrics["b-precision"],
            ],
            "Malignant F1 score": [
                normal_on_normal_metrics["b-f1"],
                normal_on_segmented_metrics["b-f1"],
                segmented_on_normal_metrics["b-f1"],
                segmented_on_only_lesion_metrics["b-f1"],
            ],
            "Malignant recall": [
                normal_on_normal_metrics["b-recall"],
                normal_on_segmented_metrics["b-recall"],
                segmented_on_normal_metrics["b-recall"],
                segmented_on_only_lesion_metrics["b-recall"],
            ],
        },
        index=index,
    )

    score_table.transpose().to_latex(
        "score_table.tex",
        bold_rows=True,
        multicolumn=True,
        # column_format="l|rr|rr|",
    )

    # Make a table containing just the metrics from the original model
    metrics_table = pd.DataFrame(
        {
            "Multi-class precision": [
                normal_on_normal_metrics["mc-precision"],
            ],
            "Multi-class F1 score": [
                normal_on_normal_metrics["mc-f1"],
            ],
            "Binary precision": [
                normal_on_normal_metrics["b-precision"],
            ],
            "Malignant F1 score": [
                normal_on_normal_metrics["b-f1"],
            ],
            "Malignant recall": [
                normal_on_normal_metrics["b-recall"],
            ],
        },
        index=pd.Index(
            [
                "Model metrics"
            ],
            name="",
        ),
    ).transpose()

    metrics_table.to_latex("metrics_table.tex", bold_rows=True)


import re
from copy import deepcopy

def annoying_building(w, x, y=0, z=0):
    if z >= len(x):
        return []
    y = w[y]
    if type(y) is str:
        if x[z] == y:
            return [z + 1]
        return []
    matches = []
    for i in y:
        better_matches = [z]
        for better_rule in i:
            new_match = []
            for index in better_matches:
                new_match += annoying_building(w, x, better_rule, index)
            better_matches = new_match
        matches += better_matches
    return matches

rules = {}
inputting = open('input.txt')
for line in map(str.rstrip, inputting):
    if line == '':
        break
    rule_id, options = line.split(': ')
    rule_id = int(rule_id)

    if '"' in options:
        rule = options[1:-1]
    else:
        rule = []
        for option in options.split('|'):
            rule.append(tuple(map(int, option.split())))

    rules[rule_id] = rule
rules2 = deepcopy(rules)
rules2[8] = [(42,), (42, 8)]
rules2[11] = [(42, 31), (42, 11, 31)]
print(rules)
valid = 0
for msg in map(str.rstrip, inputting):
    if len(msg) in annoying_building(rules2, msg):
        valid += 1
print(valid)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 10 17:17:43 2022

@author: harshmanishpatidar
"""

fn= input("Enter Filename: ")

f = fn.split(".")

print ("Extension of the file is : " + f[-1])


import logging
from typing import Optional

from core import db
from player import PlayerApp
from ui.components.tabs_layout import Tab

from .models import Playlist
from .views import PlaylistsComponent, PlaylistTracksComponent

logger = logging.getLogger("plugins.playlist")

class PlaylistController:
    def __init__(self):
        self.app: PlayerApp = PlayerApp.get_instance()
        self.playlist_container = self.app.ui.top_layout

        self.playlists_view: Optional[PlaylistsComponent] = None

        self.app.injector.provide(PlaylistController, lambda: self)

    def toggle_playlists(self):
        if self.playlists_view:
            self.app.window.blur_active_component()
            self.playlists_view.detach()
            self.playlists_view = None
            if self.subscription:
                self.subscription.dispose()
                self.subscription = None
        else:
            self.playlists_view = PlaylistsComponent(size=40)
            self.playlist_container.insert(0, self.playlists_view)
            self.app.window.focus(self.playlists_view)

            self.subscription = self.playlists_view.selected_item.subscribe(
                self.open_playlist
            )

    def open_playlist(self, playlist_name: str):
        playlist = (
            db.get_session()
            .query(Playlist)
            .filter(Playlist.name == playlist_name)
            .one()
        )

        if not playlist:
            logger.error(f"Unable to open playlist {playlist_name}")
            return

        tabs_layout = self.app.ui.tabs_layout
        tab = tabs_layout.get_tab(playlist.name)
        if tab:
            self.remove_current_tab_from_stack()
            tabs_layout.switch_to_tab(tab)
            self.app.window.focus(tab.component)
        else:
            tracks_view = PlaylistTracksComponent(playlist)
            self.remove_current_tab_from_stack()
            self.app.ui.tabs_layout.add_tab(
                Tab(title=playlist.name, component=tracks_view)
            )
            self.app.window.focus(tracks_view)

    def remove_current_tab_from_stack(self):
        component = self.app.ui.tabs_layout.displayed_tab.component
        if component in self.app.window.active_component_stack:
            self.app.window.active_component_stack.remove(component)


from math import fabs
import torch
import torch.nn as nn
import torchvision

def dconv_bn_relu(in_dim, out_dim):
    """_summary_

    Args:
        in_dim (int): input channel
        out_dim (int): output channel

    Returns:
        nn.Model: Sequential model ConvTranspos2d -> BN -> Relu()

    """
    return nn.Sequential(
        nn.ConvTranspose2d(in_dim, out_dim, kernel_size = 5, stride = 2,
                                   padding=2, output_padding=1, bias=False),
        nn.BatchNorm2d(out_dim),
        nn.ReLU())

class Generator(torch.nn.Module):
    def __init__(self, channels,z_dim = 100):
        super().__init__()
        k = 5 # 4 5
        p = 2 # 1 2
        op = 1 # 0 1
        self.z_dim=z_dim
        self.main_module = nn.Sequential(
            # Z latent vector 100
            nn.ConvTranspose2d(in_channels=z_dim, out_channels=1024, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(num_features=1024),
            nn.ReLU(True),

            # State (1024x4x4)
            nn.ConvTranspose2d(in_channels=1024, out_channels=512, kernel_size=k, stride=2, padding=p,output_padding=op),
            nn.BatchNorm2d(num_features=512),
            nn.ReLU(True),

            # State (512x8x8)
            nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=k, stride=2, padding=p,output_padding=op),
            nn.BatchNorm2d(num_features=256),
            nn.ReLU(True),

            # State (256x16x16)
            nn.ConvTranspose2d(in_channels=256, out_channels=channels, kernel_size=k, stride=2, padding=p, output_padding=op))

            # output of main module --> Image (Cx32x32)

        self.output = nn.Tanh()

    def forward(self, x):
        x = self.main_module(x)
        return self.output(x)

class Discriminator(torch.nn.Module):
    def __init__(self, channels=3,z_dim = 100):
        """
        Args:
            channels (int): channel of the input image
        Return:
            output (tensor): B 1 H/8 W/8 (128,256)->(16,32)
        """
        super().__init__()
        # Filters [256, 512, 1024]
        self.z_dim = z_dim #(Cx64x64)
        k = 5 # 4 5
        p = 2 # 1 2
        op = 1 # 0 1
        # Output_dim = 1
        self.main_module = nn.Sequential(
            # Omitting batch normalization in critic because our new penalized training objective (WGAN with gradient penalty) is no longer valid
            # in this setting, since we penalize the norm of the critic's gradient with respect to each input independently and not the enitre batch.
            # There is not good & fast implementation of layer normalization --> using per instance normalization nn.InstanceNorm2d()
            # Image (Cx32x32)
            nn.Conv2d(in_channels=channels, out_channels=256, kernel_size=k, stride=2, padding=p),
            nn.InstanceNorm2d(256, affine=True),
            nn.LeakyReLU(0.2, inplace=True),

            # State (256x16x16)
            nn.Conv2d(in_channels=256, out_channels=512, kernel_size=k, stride=2, padding=p),
            nn.InstanceNorm2d(512, affine=True),
            nn.LeakyReLU(0.2, inplace=True),

            # State (512x8x8)
            nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=k, stride=2, padding=p),
            nn.InstanceNorm2d(1024, affine=True),
            nn.LeakyReLU(0.2, inplace=True))
            # output of main module --> State (1024x4x4)

        self.output = nn.Sequential(
            # The output of D is no longer a probability, we do not apply sigmoid at the output of D.
            nn.Conv2d(in_channels=1024, out_channels=1, kernel_size=k, stride=1, padding=p))

    def forward(self, x):
        x = self.main_module(x)
        return self.output(x)

    def feature_extraction(self, x):
        # Use discriminator for feature extraction then flatten to vector of 16384
        x = self.main_module(x)
        return x.vie

if __name__ == "__main__":
    x = torch.randn(2,100,16,32) # 2x100
    G = Generator(3) # output channels
    fake = G(x) # 2,3, 32 ,32
    print(fake.size())
    D = Discriminator(3)
    r_logit = D(fake)
    print(r_logit.size())


#takes a list with numbers and uses iteration and recursion to return the product of all elements in the list
#iterative method
def iteration(x):
    i= 1;
    element =x[0]
    if len(x)==0:
        return 0

    while i < len(x):
        element = element * x[i];
        i= i+1;
    return element

print(iteration([1,2,3,4]))

# In[18]:

#recursive method
def recursion(x):
    if len(x)==1:
        return x[0]
    return recursion([x[0]]) * recursion(x[1:])
print(recursion([1,2,3,4]))


import discord, asyncio
from discord.ext import commands

class Misc(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def magisk(self, ctx, links="asdf"):
        if links == "asdf":
            whatismagisk = discord.Embed(title = "__Magisk: The magic mask of Android__", color = 0x301c24, url = "https://github.com/topjohnwu/Magisk")

            whatismagisk.add_field(name = "What is Magisk?", value = "In simple terms, Magisk is a way to root your phone systemlessly and install *modules* on it. It also allows you to bypass Safetynet checks while you're rooted.", inline = False)
            whatismagisk.add_field(name = "Should I use it compared to SuperSU and others?", value = "YES! SuperSU is quite outdated nowadays and others range from not-well-reputable to downright spyware.", inline = False)
            whatismagisk.add_field(name = "How do I install it on my phone?", value = "Make sure you have bootloader unlocked, then check out the installation guide for more info\n", inline = False)
            whatismagisk.set_thumbnail(url = "https://cdn.discordapp.com/attachments/867824004072210452/868167290628210739/download.jpg")
            await ctx.send(embed = whatismagisk)
        else:
            embed = discord.Embed(title = "__Magisk related links:__", color = 0x301c24)

            embed.add_field(name = "Download Link", value = "https://github.com/topjohnwu/Magisk/releases", inline = False)
            embed.add_field(name = "Official Installation Guide", value = "https://topjohnwu.github.io/Magisk/install.html", inline = False)
            embed.add_field(name = "Magisk Documentation (Users and Devs)", value = "https://topjohnwu.github.io/Magisk/", inline = False)
            await ctx.send(embed = embed)

    @commands.command()
    async def remind(self, ctx, time, *msg):
        """Reminds you of something after a certain amount of time"""
        uid = ctx.author.id
        await ctx.send("Reminding you in {} seconds".format(time))
        await asyncio.sleep(int(time))
        await ctx.send(f'<@{uid}> Reminder: {" ".join(msg)}')

    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f"Pong! {round(self.client.latency*1000)}ms")

def setup(client):
    client.add_cog(Misc(client))


import sys

def get_diagonal(arr, mode, n):
    result = []

    if mode == 0:
        for i in range(n):
            # print('%i %d'%(i, arr[i][i]))
            result.append(arr[i][i])
    if mode == 1:
        for i in range(n):
            result.append(arr[i][n-i-1])
    return result

if __name__ == '__main__':
    n = int(raw_input())
    arr = []
    for i in range(n):
        tmp = raw_input().split()
        tmp = map(int, tmp)
        arr.append(tmp)
    a = arr
    # print (a)

    d1 = get_diagonal(a, 0, n)
    d2 = get_diagonal(a, 1, n)
    s1 = sum(d1)
    s2 = sum(d2)
    print(abs(s1 - s2))


# 421. Maximum XOR of Two Numbers in an Array

# Refer to https://www.youtube.com/watch?v=wSgrc98d2lI for solution with tries.
# Brute force solution correct but exceeds time limit.

class Trie:
    def __init__(self):
        self.children = {}

class Solution:
    def __init__(self):
        self.root = Trie()

    def insertBit(self, num):
        bit_num = bin(num)[2:].zfill(32)
        node = self.root
        for bit in bit_num:
            if bit not in node.children:
                node.children[bit] = Trie()
            node = node.children[bit]

    def find_max_xor(self, num):
        bit_num = bin(num)[2:].zfill(32)
        node = self.root
        max_xor = ''
        for bit in bit_num:
            if bit == '0':
                oppo_bit = '1'
            elif bit == '1':
                oppo_bit = '0'

            if oppo_bit in node.children:
                max_xor += oppo_bit
                node = node.children[oppo_bit]
            else:
                max_xor += bit
                node = node.children[bit]
        return int(max_xor, 2)^num

    def findMaximumXOR(self, nums: List[int]) -> int:
        for num in nums:
            self.insertBit(num)

        max_xor = 0
        for num in nums:
            max_xor = max(max_xor, self.find_max_xor(num))

        return max_xor

# class Solution:
#     def findMaximumXOR(self, nums: List[int]) -> int:
#         max_xor = 0

#         # [3,10,5,25,2,8]

#         for i in range(len(nums)-1):
#             for j in range(i+1, len(nums)):
#                 xor = nums[i]^nums[j]
#                 if(xor>max_xor):
#                     max_xor = xor
#         return max_xor


from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from app.gui.newObject import UiNewObjectWindow
from app.openMF.Scene import Scene
from app.openMF.Shapes.MFObject import MFObject

class NewObjectWindow(QtWidgets.QMainWindow):
    def __init__(self, scene: Scene):
        super(NewObjectWindow, self).__init__()
        self.ui = UiNewObjectWindow()
        self.ui.setupUi(self)
        self.scene = scene
        self.ui.columns_count.valueChanged.connect(self.value_changed)
        self.ui.hats_count.valueChanged.connect(self.value_changed)
        self.ui.make_button.clicked.connect(self.make_object)
        self.ui.top_tower_size.valueChanged.connect(self.value_changed)

    def value_changed(self):
        self.ui.column_height.setEnabled(self.ui.columns_count.value())
        self.ui.tower_hat_size.setEnabled(self.ui.hats_count.value())
        self.ui.tower_hat_size.setMinimum(self.ui.top_tower_size.value() + 1)

    def make_object(self):
        params = self.check_params()
        if params:
            obj = MFObject.ra_gates(**params)
            if obj:
                new_name, name, i = 'RaGates', 'RaGates', 1
                while not self.scene.objects.get(new_name) is None:
                    new_name = name + str(i)
                    i += 1
                self.scene.objects[new_name] = obj
            self.close()

    def check_params(self):
        width, height, length = self.ui.base_width.value(), self.ui.base_height.value(), self.ui.base_length.value()
        c_count = self.ui.columns_count.value()
        c_height = self.ui.column_height.value()
        tower_top_size, tower_bot_size = self.ui.top_tower_size.value(), self.ui.bottom_tower_size.value()
        tower_height = self.ui.tower_height.value()
        hat_count, hat_size = self.ui.hats_count.value(), self.ui.tower_hat_size.value()
        if tower_top_size >= tower_bot_size:
            self.message('Размер верхнего основания башни, должно быть меньше размеров нижнего основания башни!')
            return False
        if hat_count > 0 and hat_size < tower_top_size:
            self.message('Размер блока верхушки башни, должен быть больше размера верхнего основания башни!')
            return False
        if tower_bot_size > width * (2/3) or tower_bot_size > length * (2/3):
            self.message('Размер нижнего основания башни, должен быть меньше ширины и длины основания!')
            return False
        return {'width': width, 'height': height, 'length': length, 'c_count': c_count, 'c_height': c_height,
                'tower_top_size': tower_top_size, 'tower_bot_size': tower_bot_size, 'tower_height': tower_height,
                'hat_count': hat_count, 'hat_size': hat_size}

    def message(self, msg: str):
        QMessageBox.information(self, 'Неверные данные!', msg)