# program of a terminal calculator

a = int(input("Enter first number : "))
b = int(input("Enter second number : "))

print(
    "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
ch = input()
while True:
    if ch == "1":
        print("Sum is :", a + b)
        a = int(input("Enter first number : "))
        b = int(input("Enter second number : "))

        print(
            "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
        ch = input()
    elif ch == "2":
        print("Difference is : ", a - b)
        a = int(input("Enter first number : "))
        b = int(input("Enter second number : "))

        print(
            "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
        ch = input()
    elif ch == "3":
        print("Product is : ", a * b)
        a = int(input("Enter first number : "))
        b = int(input("Enter second number : "))

        print(
            "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
        ch = input()
    elif ch == "4":
        print("Division is : ", a / b)
        a = int(input("Enter first number : "))
        b = int(input("Enter second number : "))

        print(
            "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
        ch = input()
    elif ch =="q":
        print("Quitting calculator")
        break
    else:
        print("Not a valid option")
        print(
            "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting")
        ch = input()

# program to find if a year is leap or not

a = int(input("Enter the year : "))
if a % 4 == 0:
    print(a, "is a leap year")
else:
    print(a, "is not a leap year")

# program that checks if a form is valid

name = input("Enter your name : ")
age = input("Enter your age : ")
mob_num = input("Enter mobile number : ")

while True:
    if name =="":
        name = input("Name cannot be empty, enter your name again : ")
    elif name.isalpha() == False:
        name = input("Name can contain only alphabets, enter your name again : ")
    else:
        if age =="":
            age= input("age cannot be empty, enter your age again : ")
        elif age.isdigit() == False:
            age = input("Age can contain only numbers, enter your age again : ")
        elif int(age) < 19:
            age = input("Age can only be over 18, enter your age again : ")
        else:
            if mob_num =="":
                mob_num = input("Mobile number cannot be empty, enter your number again : ")
            elif mob_num.isdigit() == False:
                mob_num = input("Mobile Number can contain only numbers, enter your number again : ")
            else:
                print("Name = ", name , "\nAge = ", age, "\nMobile Number = ", mob_num)
                break

# program to print multiplication table

a = int(input("Enter number for which the table is required : "))

for i in range(1,11):
    print(a ,"*", i, "=", a*i )

# program to add 10 numbers using only one input statement to a list

list = []
i=1
while i <=10:
    a = input("Enter #" + str(i))
    if a.isnumeric():
        list.append(a)
        i = i+1
    else:
        print(a, "is not a number")

print("List of numbers = ", list)

# program to display only even number among a list

list_num = [12,4,35,98,99,13,52,67,1,22,76]
list_even =[]
for x in list_num:
    if x%2 == 0:
        list_even.append(x)

print("List of numbers = ", list_num)
print("List of even numbers = ", list_even)

# program to arrange data in list into different list according to their data type
list = ["a",12,1.89, 66,"rahul", 4.22, "rojan", "himalaya", 44,1.87]
list_int=[]
list_float=[]
list_string=[]
for x in list:
    if isinstance(x, int):
        list_int.append(x)
    elif isinstance(x,str):
        list_string.append(x)
    else:
        list_float.append(x)

print("The list with int :", list_int)
print("The list with float :", list_float)
print("The list with string :", list_string)

# program to remove a user desired number from a list
list = [23, 11, 69, 12, 34, 2, 6, 23, 43, 1233, 23, 222, 69, 23]
print("Old list is ", list)

num = int(input("Enter number to be removed"))

for x in list:
    if x == num:
        list.remove(x)
print("New list is", list)


import cv2
import numpy as np
from deepface import DeepFace
import matplotlib as plt

def detect_emotions(frame, face_cascade):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    for (x, y, w, h) in faces:
        face_roi = frame[y:y + h, x:x + w]
        face = cv2.resize(face_roi, (152, 152))  # Resize to match the input shape of the model
        face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
        face = cv2.cvtColor(face, cv2.COLOR_GRAY2RGB)  # Convert grayscale to RGB
        face = np.expand_dims(face, axis=0)
        face = face.astype('float32') / 255.0

        # emotion_predictions = model.predict(face)[0, :]
        # emotion_index = np.argmax(emotion_predictions)
        # # emotion_label = emotion_labels[emotion_index]
        # print(emotion_index)
        # print("dekh")
        # print(emotion_predictions)

        # Perform race and gender detection
        detection = DeepFace.analyze(face_roi, actions=['race', 'gender', 'emotion'], enforce_detection=False)

        if len(detection) > 0:
            detection = detection[0]  # Access the first item in the list

            race_label = detection['dominant_race']
            gender_label = detection['dominant_gender']
            emotion = detection['dominant_emotion']
            print(detection)

            # Format the labels to display on the screen
            labels = f"A {gender_label} showing {emotion} emotion"

            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(frame, labels, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2, cv2.LINE_AA)

    return frame


import matplotlib.pyplot as plt
import numpy as np

def plot_chains(chain, fileout=None, tracers=0, labels=None, delay=0, ymax=200000, thin=100, num_xticks=7, truths=None):

    if chain.ndim < 3:
        print("You must include a multiple chains")
        return

    n_chains, length, n_var = chain.shape
    print(n_chains, length, n_var)

    if (labels is not None) and (len(labels) != n_var):
        print("You must provide the correct number of variable labels.")
        return

    if (truths is not None) and (len(truths) != n_var):
        print("You must provide the correct number of truths.")
        return

    fig, ax = plt.subplots(int(n_var/2) + n_var%2, 2, figsize=(8, 0.8*n_var))
    plt.subplots_adjust(left=0.09, bottom=0.07, right=0.96, top=0.96, hspace=0)

    color = np.empty(n_chains, dtype=str)
    color[:] = 'k'
    alpha = 0.01 * np.ones(n_chains)
    zorder = np.ones(n_chains)
    if tracers > 0:
        idx = np.random.choice(n_chains, tracers, replace=False)
        color[idx] = 'r'
        alpha[idx] = 1.0
        zorder[idx] = 2.0

    for i in range(n_var):
        ix = int(i/2)
        iy = i%2

        for j in range(n_chains):

            xvals = (np.arange(length)*thin - delay) / 1000.0
            ax[ix,iy].plot(xvals, chain[j,:,i], color=color[j], alpha=alpha[j], rasterized=True, zorder=zorder[j])

        if ymax is None: ymax = (length*thin-delay)

        ax[ix,iy].set_xlim(-delay/1000.0, ymax/1000.0)
        ax[ix,iy].set_xticks(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks))
        ax[ix,iy].set_xticklabels([])

        # Add y-axis labels if provided by use
        if labels is not None: ax[ix,iy].set_ylabel(labels[i])

        if delay != 0: ax[ix,iy].axvline(0, color='k', linestyle='dashed', linewidth=2.0, zorder=9)

        if truths is not None: ax[ix,iy].axhline(truths[i], color='C0', linestyle='dashed', linewidth=2.0, zorder=10)

    # plt.tight_layout()

    ax[-1,0].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U'))
    ax[-1,1].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U'))

    ax[-1,0].set_xlabel(r'Steps ($\times$1000)')
    ax[-1,1].set_xlabel(r'Steps ($\times$1000)')

    if fileout is None:
        plt.show()
    else:
        plt.savefig(fileout, rasterized=True)

    return

# from dart_board import plotting
# import numpy as np
# import pickle
# chains = pickle.load(open("../data/HMXB_chain.obj", "rb"))
# plotting.plot_chains(chains)


#!/usr/bin/env python3
"""
Author: Ken Chen
Email: chenkenbio@gmail.com
"""

import os
import torch
import warnings
import numpy as np
import gzip
from tqdm import tqdm
from collections import defaultdict
from transformers import BertForMaskedLM, BertTokenizer
from torch.utils.data import DataLoader, Dataset
from torch.cuda.amp.autocast_mode import autocast

from utils import get_reverse_strand, load_fasta, distance, fast_seq_to_kmer_list
from config import hg19 as HG19_FASTA
from config import VEXSEQ, MFASS

CHROM2INT = {
    "chr1": 0,
    "chr2": 1,
    "chr3": 2,
    "chr4": 3,
    "chr5": 4,
    "chr6": 5,
    "chr7": 6,
    "chr8": 7,
    "chr9": 8,
    "chr10": 9,
    "chr11": 10,
    "chr12": 11,
    "chr13": 12,
    "chr14": 13,
    "chr15": 14,
    "chr16": 15,
    "chr17": 16,
    "chr18": 17,
    "chr19": 18,
    "chr20": 19,
    "chr21": 20,
    "chr22": 21,
    "chrX": 22,
    "chrY": 23
}
INT2CHROM = {v:k for k, v in CHROM2INT.items()}

def kl_divergence(ref, alt):
    return (alt * np.log(alt / ref)).sum(axis=-1)

class ExonCenterVariant(Dataset):
    def __init__(self, vcf, size: int, genome: str, tokenizer: BertTokenizer, k=1, exon_zero_start=True):
        super().__init__()
        self.k = k
        self.exon_zero_start = exon_zero_start
        self.size = size
        self.genome = load_fasta(genome, cache=True)
        self.samples = list()
        self.tokenizer = tokenizer
        self.distances = list()
        self.mutation_ids = list()
        self.groups = list()
        with gzip.open(vcf, 'rt') as infile:
            for l in infile:
                if l.startswith('#'):
                    continue
                chrom, pos, name, ref, alt = l.strip().split('\t')[:5]
                if ref == '.' or alt == '.':
                    warnings.warn("unsupported allele '.'")
                    continue
                if len(ref) > 1 or len(alt) > 1:
                    warnings.warn("skip indels")
                    continue
                pos = int(pos) - 1
                mut_id, _, e_start, e_end, strand, ref_psi, dpsi, label = name.split('|')
                if not self.exon_zero_start:
                    e_start = int(e_start) - 1
                self.mutation_ids.append(mut_id)
                label = 1 if label == "True" else 0
                self.groups.append(mut_id.split('_')[0])
                self.samples.append((
                    chrom, pos, ref, alt, e_start, e_end, strand, ref_psi, dpsi, label
                ))
                self.distances.append(
                    min(
                        distance(int(e_start) - 2, int(e_start), pos, pos + 1),
                        distance(int(e_end), int(e_end) + 2, pos, pos + 1)
                    )
                )
        self.groups = np.asarray(self.groups)
        self.samples = np.asarray(self.samples)
        self.distances = np.asarray(self.distances)
        self.labels = np.asarray([int(x[-1]) for x in self.samples])
        self.refpsi = np.asarray([float(x[-3]) for x in self.samples])
        self.dpsi = np.asarray([float(x[-2]) for x in self.samples])

        self.is_exonic = list()
        for x in self.samples:
            _, pos, _, _, e1, e2 = x[:6]
            pos, e1, e2 = int(pos), int(e1), int(e2)
            if pos >= e1 and pos < e2:
                self.is_exonic.append(1)
            else:
                self.is_exonic.append(0)
        self.is_exonic = np.asarray(self.is_exonic)

        self.repr_string = "{}(vcf={},genome={}, seq_size={},vocab_size/k={}/{})".format(
            self.__class__.__name__,
            vcf,
            genome,
            size,
            self.tokenizer.vocab_size,
            k
        )

    def __repr__(self) -> str:
        return self.repr_string

    def __getitem__(self, index, get_seq: bool=False):
        chrom, position, ref, alt, e_start, e_end, strand, _, _, label = self.samples[index]
        position, e_start, e_end, label = int(position), int(e_start), int(e_end), int(label)
        left = (e_start + e_end) // 2 - self.size // 2
        seq_wt = self.genome[chrom][left:left + self.size].upper()
        e_start, e_end = e_start - left, e_end - left
        d_start, d_end = e_end, e_end + 2
        a_start, a_end = e_start - 2, e_start

        pos = position - left
        assert seq_wt[pos] == ref, "{}".format((index))
        seq_wt = list(seq_wt)
        seq_mt = seq_wt.copy()
        seq_mt[pos] = alt
        if strand == '-':
            seq_wt = get_reverse_strand(seq_wt, join=False)
            seq_mt = get_reverse_strand(seq_mt, join=False)

            e_start, e_end = len(seq_wt) - e_end, len(seq_wt) - e_start
            d_start, d_end = e_end, e_end + 2
            a_start, a_end = e_start - 2, e_start
            pos = len(seq_wt) - 1 - pos
        if self.k == 1:
            ids_wt = self.tokenizer.encode(' '.join(seq_wt))
            ids_mt = self.tokenizer.encode(' '.join(seq_mt))
        else:
            seq_wt = ' '.join(fast_seq_to_kmer_list(''.join(seq_wt), k=self.k, pad=True))
            seq_mt = ' '.join(fast_seq_to_kmer_list(''.join(seq_mt), k=self.k, pad=True))
            ids_wt = self.tokenizer.encode(seq_wt)
            ids_mt = self.tokenizer.encode(seq_mt)
        ids_wt = torch.as_tensor(ids_wt).long()
        ids_mt = torch.as_tensor(ids_mt).long()
        if get_seq:
            return ids_wt, ids_mt, pos, d_start, d_end, a_start, a_end, int(label), seq_wt, seq_mt
        else:
            return ids_wt, ids_mt, pos, d_start, d_end, a_start, a_end, int(label), CHROM2INT[chrom], position
    def __len__(self):
        return len(self.samples)

    def check_dataset(self):
        d_counts = defaultdict(int)
        a_counts = defaultdict(int)
        noncanonical = list()
        unmatched = list()
        for idx in tqdm(range(len(self.samples))):
            ids_wt, ids_mt, pos, d_start, d_end, a_start, a_end, label, seq_wt, seq_mt = self.__getitem__(idx, get_seq=True)
            d_counts["{}{}".format(*ids_wt[d_start + 1:d_end + 1].numpy())] += 1
            d_counts[''.join(seq_wt[d_start:d_end])] += 1
            a_counts["{}{}".format(*ids_wt[a_start + 1:a_end + 1].numpy())] += 1
            a_counts[''.join(seq_wt[a_start:a_end])] += 1
            if seq_wt[d_start:d_end] != "GT" or seq_wt[a_start:a_end] != "AG":
                noncanonical.append((idx, self.mutation_ids[idx], seq_wt[d_start:d_end], seq_wt[a_start:a_end], self.samples[idx]))
            if ids_wt[pos + 1] == ids_mt[pos + 1] or seq_wt[pos] == seq_mt[pos]:
                unmatched.append(idx)
        return dict(d_counts=d_counts, a_counts=a_counts, unmatched=unmatched, noncanonical=noncanonical)

    @classmethod
    def load_mfass(self, tokenizer, size=510, k=1):
        return self(vcf=MFASS, size=size, genome=HG19_FASTA, tokenizer=tokenizer, k=k)

    @classmethod
    def load_vexseq(self, tokenizer, size=510, k=1):
        return self(vcf=VEXSEQ, size=size, genome=HG19_FASTA, tokenizer=tokenizer, k=k, exon_zero_start=False)

@autocast()
@torch.no_grad()
def evaluate_mutation(model: BertForMaskedLM, ds: Dataset, batch_size: int=16, num_workers=8):
    loader = DataLoader(ds, batch_size=batch_size, num_workers=num_workers)
    all_wt_logits = list()
    all_mt_logits = list()
    all_positions = list()
    all_labels = list()
    all_donors = list()
    all_acceptors = list()
    device = next(model.parameters()).device
    for ids_wt, ids_mt, pos, d_start, d_end, a_start, a_end, label in tqdm(loader):
        ids_wt, ids_mt = ids_wt.to(device), ids_mt.to(device)
        logits_wt = model.forward(ids_wt).logits[:, 1:-1, 5:].detach()
        logits_mt = model.forward(ids_mt).logits[:, 1:-1, 5:].detach()
        logits_wt = torch.softmax(logits_wt, dim=-1).cpu().numpy()
        logits_mt = torch.softmax(logits_mt, dim=-1).cpu().numpy()
        all_wt_logits.append(logits_wt)
        all_mt_logits.append(logits_mt)
        all_labels.append(label.numpy())
        all_positions.append(pos.numpy())
        all_donors.append(np.asarray([(a, b) for a, b in zip(d_start.numpy(), d_end.numpy())]))
        all_acceptors.append(np.asarray([(a, b) for a, b in zip(a_start.numpy(), a_end.numpy())]))
    all_wt_logits = np.concatenate(all_wt_logits)
    all_mt_logits = np.concatenate(all_mt_logits)
    all_positions = np.concatenate(all_positions)
    all_donors = np.concatenate(all_donors)
    all_acceptors = np.concatenate(all_acceptors)
    all_labels = np.concatenate(all_labels)
    return all_wt_logits, all_mt_logits, all_positions, all_donors, all_acceptors, all_labels

# def get_args():
#     p = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#     p.add_argument("--model-path", default="../pretrained/mlm_on_tx", required=True)
#     p.add_argument("--mask-ss", action="store_true")
#     p.add_argument("--mask-mut", action="store_true")
#     p.add_argument('-o', "--outdir", required=True)
#     # p.add_argument('--seed', type=int, default=2020)
#     return p

if __name__ == "__main__":
    pass

#     args = get_args().parse_args()
#     args.outdir = make_directory(args.outdir)
#     logger = make_logger(filename=os.path.join(args.outdir, "train.log"))
#     logger.info(get_run_info(argv=sys.argv, args=args))

#     ds = ExonCenterVariant(
#         vcf="../data/mfass/MFASS_mmsplice.vcf",
#         size=510,
#         genome=HG19_FASTA,
#         # mask_mut=args.mask_mut,
#         # mask_ss=args.mask_ss
#     )
#     pickle.dump(ds.labels, open("{}/labels.pkl".format(args.outdir), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)

#     NN2INT = {
#         'N': 0,
#         'A': 1,
#         'C': 2,
#         'G': 3,
#         'T': 4
#     }

#     fn_logits = "{}/logits.pt".format(args.outdir)
#     if os.path.exists(fn_logits):
#         logger.info("- use {}".format(fn_logits))
#         all_wt_logits, all_mt_logits, all_positions, all_donors, all_acceptors, all_labels = pickle.load(open(fn_logits, 'rb'))
#     else:
#         device = torch.device("cuda")
#         bert = BertForMaskedLM.from_pretrained(args.model_path).to(device)

#         all_wt_logits, all_mt_logits, all_positions, all_donors, all_acceptors, all_labels = evaluate_mutation(bert.to(device), ds, batch_size=24, num_workers=12)

#         pickle.dump(
#             (all_wt_logits, all_mt_logits, all_positions, all_donors, all_acceptors, all_labels),
#             open(fn_logits, 'wb'),
#             protocol=pickle.HIGHEST_PROTOCOL
#         )

#     if args.mask_mut:
#         all_mut_scores = list()
#         for idx in tqdm(range(all_wt_logits.shape[0])):
#             ref, alt = ds.samples[idx][2:4]
#             p = all_positions[idx]
#             ar = all_wt_logits[idx, p]
#             mut_score = min(max(ar[NN2INT[alt]], 1E-6), 1 - 1E-6) / min(max(ar[NN2INT[ref]], 1E-6), 1 - 1E-6)
#             all_mut_scores.append(mut_score)
#         all_mut_scores = np.asarray(all_mut_scores)
#         pickle.dump(all_mut_scores, open("{}/all_mut_scores.pkl".format(args.outdir), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
#     else:
#         all_ss_scores = list()
#         for idx in tqdm(range(all_wt_logits.shape[0])):
#             d1, d2 = all_donors[idx]
#             a1, a2 = all_acceptors[idx]
#             ss_score = max(
#                 kl_divergence(all_wt_logits[idx, d1], all_mt_logits[idx, d1]) + \
#                     kl_divergence(all_wt_logits[idx, d1 + 1], all_mt_logits[idx, d1 + 1]),
#                 kl_divergence(all_wt_logits[idx, a1], all_mt_logits[idx, a1]) + \
#                     kl_divergence(all_wt_logits[idx, a1 + 1], all_mt_logits[idx, a1 + 1])
#             )
#             all_ss_scores.append(ss_score)
#         all_ss_scores = np.asarray(all_ss_scores)
#         if args.mask_ss:
#             pickle.dump(all_ss_scores, open("{}/all_ss_scores.mask_ss.pkl".format(args.outdir), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
#         else:
#             pickle.dump(all_ss_scores, open("{}/all_ss_scores.pkl".format(args.outdir), 'wb'), protocol=pickle.HIGHEST_PROTOCOL)

# #         average_precision_score(all_labels, all_scores), roc_auc_score(all_labels, all_scores)
# #
# #
# #
# #
# #         average_precision_score(all_labels, all_ss_scores_mask_ss), roc_auc_score(all_labels, all_ss_scores_mask_ss)
# #
# #
# #
# #
# #         p, r, _ = precision_recall_curve(all_labels, all_scores)
# #         f, t, _ = roc_curve(all_labels, all_scores)
# #
# #
# #
# #
# #         ax = plt.subplot(121)
# #         ax.plot(r, p)
# #         ax = plt.subplot(122)
# #         ax.plot(f, t)
# #
# #
# #
# #
# #         all_dpsi = np.asarray([float(x[-2]) for x in ds.samples])
# #         all_refpsi = np.asarray([float(x[-3]) for x in ds.samples])
# #
# #
# #
# #
# #         average_precision_score(np.abs(all_dpsi) > 0.4, all_scores),     average_precision_score(all_labels, all_scores),     average_precision_score(all_dpsi < 0, all_scores)
# #
# #
# #
# #
# #         import pyBigWig
# #
# #
# #
# #
# #         bw.values('chrX', 48837917, 48837917+1)
# #
# #
# #
# #
# #         phast46_scores = list()
# #         bw = pyBigWig.open("/bigdat1/pub/UCSC/hg19/vertebrate.phastCons46way.bw")
# #         for s in tqdm(ds.samples):
# #             chrom, position = s[:2]
# #             phast46_scores.append(
# #                 bw.values(chrom, int(position), int(position) + 1)[0]
# #             )
# #         bw.close()
# #
# #         phast100_scores = list()
# #         bw = pyBigWig.open("/bigdat1/pub/UCSC/hg19/hg19.100way.phastCons.bw")
# #         for s in tqdm(ds.samples):
# #             chrom, position = s[:2]
# #             phast100_scores.append(
# #                 bw.values(chrom, int(position), int(position) + 1)[0]
# #             )
# #         bw.close()
# #
# #
# #
# #
# #         # phast46_scores = np.asarray(phast46_scores)
# #         phast100_scores = np.asarray(phast100_scores)
# #
# #
# #
# #
# #         average_precision_score(all_labels, phast46_scores), roc_auc_score(all_labels, phast46_scores)
# #
# #
# #
# #
# #         average_precision_score(all_labels, phast100_scores), roc_auc_score(all_labels, phast100_scores)
# #
# #
# #
# #
# #         torch.save(phast46_scores, "phast46_scores.pt")
# #         torch.save(phast100_scores, "phast100_scores.pt")
# #
# #
# #
# #
# #         phast100_scores = torch.load("./phast100_scores.pt")
# #
# #
# #
# #
# #         phast100_scores
# #
# #
# #
# #
# #         X = np.stack([phast100_scores, all_scores, ds.distances]).T
# #
# #
# #
# #
# #         lr.fit(X, y=ds.labels)
# #
# #
# #
# #
# #         y = lr.predict_log_proba(X).T[1]
# #
# #
# #
# #
# #         average_precision_score(ds.labels, all_scores), roc_auc_score(ds.labels, all_scores)
# #
# #
# #
# #
# #         average_precision_score(ds.labels, y), roc_auc_score(ds.labels, y)
# #
# #
# #
# #
# #         average_precision_score(ds.labels, y), roc_auc_score(ds.labels, y)
# #
# #
# #
# #
# #
# #
# #


import numpy as np
import tensorflow as tf
import tensorflow.logging as logging
import random

class Model:
    def __init__(self, num_states, num_actions, batch_size):
        self._num_states = num_states
        self._num_actions = num_actions
        self._batch_size = batch_size
        # define the placeholders
        self._states = None
        self._actions = None
        # the output operations
        self._logits = None
        self._optimizer = None
        self._var_init = None
        # now setup the model
        self._define_model()

    def _define_model(self):
        # input layer
        self._states = tf.placeholder(shape=[None, self._num_states], dtype=tf.float32)
        # output layer
        self._q_s_a = tf.placeholder(shape=[None, self._num_actions], dtype=tf.float32)
        # hidden layer
        fc1 = tf.layers.dense(self._states, 50, activation=tf.nn.relu)
        fc2 = tf.layers.dense(fc1, 50, activation=tf.nn.relu)
        self._logits = tf.layers.dense(fc2, self._num_actions)
        # loss function
        loss = tf.losses.mean_squared_error(self._q_s_a, self._logits)
        # back propagation
        self._optimizer = tf.train.AdamOptimizer().minimize(loss)
        self._var_init = tf.global_variables_initializer()
    # simply returns the output of the networ
    def predict_one(self, state, sess):
        return sess.run(self._logits, feed_dict={
            self._states: state.reshape(1, self._num_states)
        })

    def predict_batch(self, states, sess):
        return sess.run(self._logits, feed_dict={self._states: states})

    def train_batch(self, sess, x_batch, y_batch):
        sess.run(self._optimizer, feed_dict={self._states: x_batch, self._q_s_a: y_batch})

    def print_num_of_total_parameters(self):
        pass

class Memory:
    def __init__(self, max_memory):
        self._max_memory = max_memory
        self._samples = []

    def add_sample(self,sample):
        self._samples.append(sample)
        if len(self._samples) > self._max_memory:
            self._samples.pop(0)
    # sample returns a random selection of no_samples in length
    def sample(self, no_samples):
        if no_samples > len(self._samples):
            return random.sample(self._samples, len(self._samples))
        else:
            return random.sample(self._samples, no_samples)


"""unmatched-halos.pu
Plotting unmatched halos
"""

import numpy as np
from mytools.visualization.myplot import MyPlot
from mytools.visualization.mycolordict import CDICT

MYPLOT = MyPlot(figsize=(15, 15))

class UnmatchedHalos(object):
    """Plotiing unmatched halos"""

    def __init__(self, headerpath):
        """Initializing UnmatchedHalos object by load the header file"""
        self.header = {}

        with open(headerpath) as _headerfile:
            for line in _headerfile:
                kv = line.split(':')
                self.header[kv[0]] = _2number(kv[1].strip('\n').strip())

        self.halo = []
        self.particles, self.halos = [], []
        self.targetIds = []

        self.pDtype = [
            ('id', np.int),
            ('x', np.float),
            ('y', np.float),
            ('z', np.float)]

        self.hDtype = [
            ('id', np.int),
            ('x', np.float),
            ('y', np.float),
            ('z', np.float),
            ('r', np.float)]

    def load(self):
        """Loading halos and particles"""

        self.halo = np.genfromtxt(
            self.header['halo_output_addr'],
            skip_header=1,
            max_rows=self.header['halo_num_p'],
            dtype=self.pDtype)

        for tag in ['x', 'y', 'z']:
            self.halo[tag] /= 1000 # kpc -> Mpc

        res = ['256', '512', '1024']
        for i in range(3):
            self.halos.append(np.genfromtxt(
                self.header['halos%s_output_addr' % res[i]],
                skip_header=1,
                max_rows=self.header['halos%s_found' % res[i]],
                dtype=self.hDtype))

            # self.halos[-1]['r'] /= 1000 # kpc -> Mpc

            self.particles.append(np.genfromtxt(
                self.header['particles%s_output_addr' % res[i]],
                skip_header=1,
                max_rows=self.header['particles%s_found' % res[i]],
                dtype=self.pDtype))

            for tag in ['x', 'y', 'z']:
                self.particles[-1][tag] /= 1000 # kpc -> Mpc

            self.halos[-1]['r'] /= 1000 # kpc -> Mpc

        # Finding target particles ids in higher resolutions
        positions = [2 * _1_to_3(hid, 256) for hid in self.halo['id']]
        self.targetIds.append([_3_to_1(p, 512) for p in positions])

        positions = [4 * _1_to_3(hid, 256) for hid in self.halo['id']]
        self.targetIds.append([_3_to_1(p, 1024) for p in positions])

    def plot(self):
        """Plotting the halo and it's environment in 3 different resolutions"""
        self._plot_column(tags=['x', 'y'], colnum=1)
        self._plot_column(tags=['x', 'z'], colnum=2)
        self._plot_column(tags=['y', 'z'], colnum=3)

    def _plot_column(self, tags=['x', 'y'], colnum=1):
        """Plotting each column of figure"""
        kws = {
            'xscale': 'linear',
            'yscale': 'linear',
            'silent': True
        }

        kws['xlabel'] = tags[0] + r" [$h^{-1}$ Mpc]"
        kws['ylabel'] = tags[1] + r" [$h^{-1}$ Mpc]"
        kws['xmin'] = self.header[tags[0] + 'min'] / 1000
        kws['xmax'] = self.header[tags[0] + 'max'] / 1000
        kws['ymin'] = self.header[tags[1] + 'min'] / 1000
        kws['ymax'] = self.header[tags[1] + 'max'] / 1000

        for i in range(3):
            pos = '33%d' % (colnum + i*3)
            ax = MYPLOT.new2daxes(pos=pos)
            dotsize = 2**(3 * (2 - i))

            # Plotting particles
            kws['color'] = "#888888"
            MYPLOT.scatter(
                self.particles[i][tags[0]],
                self.particles[i][tags[1]],
                ax=ax, s=dotsize, **dict(kws))

            if i is 0:
                # Plotting particles of the halo
                kws['color'] = "#000000"
                MYPLOT.scatter(
                    self.halo[tags[0]],
                    self.halo[tags[1]],
                    ax=ax, s=dotsize, **dict(kws))
            else:
                # Plotting similar particles
                particles = [p for p in self.particles[i] if p['id'] in self.targetIds[i-1]]
                particles = np.array(particles, dtype=self.pDtype)

                kws['color'] = CDICT['RAINBOW']['primary_colors'][0]
                MYPLOT.scatter(
                    particles[tags[0]],
                    particles[tags[1]],
                    ax=ax, s=32, **dict(kws))

            # Plotting halos
            circles = []
            for h in self.halos[i]:
                MYPLOT.plt.gca().add_artist(
                    MYPLOT.plt.Circle(
                        (h[tags[0]], h[tags[1]]), h['r'],
                        color=CDICT['RAINBOW']['primary_colors'][1],
                        fill=False))

    def save(self, path):
            """Saving the generated plot"""
            MYPLOT.plt.tight_layout()
            MYPLOT.save(path, dpi=120, transparent=False)
            MYPLOT.plt.clf()

def _1_to_3(index, res):
    """Converting a row-major 3D id to its components"""
    index %= res**3
    x = int(index / res**2)
    index -= (x * res**2)
    y = int(index / res)
    z = index - (y * res)
    return np.array([x, y, z])

def _3_to_1(pos, res):
    """Converting a 3D coordinate to a row-major id"""
    return (pos[0] % res) * res**2 + (pos[1] % res) * res + (pos[2] % res)

def _2number(string):
    """Converting a string to int or float

    Parameters
    ----------
    string : str
        A string for converting to int or float

    Returns
    -------
    int or float
    """

    try:
        return int(string)
    except ValueError:
        try:
            return float(string)
        except ValueError:
            return string


from tkinter import *

#Application Window (Main Window)
root = Tk()
root.title("Simple Calculator")

#fg or bg for colour
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)

#columnspan- how many columns will be there beneath
#e.get()- takes input from Entry
#e.insert(0, "Hello")- for default text

def button_click(number):

    current = e.get()
    e.delete(0, END)
    e.insert(0, str(current) + str(number))

def button_clear():
    e.delete(0, END)

def button_add():
    first_number = e.get()
    global f_num
    global math
    math = "addition"
    f_num = int(first_number)
    e.delete(0, END)

def button_equal():
    second_number = e.get()
    e.delete(0, END)

    if math == "addition":
        e.insert(0, f_num + int(second_number))

    if math == "subtraction":
        e.insert(0, f_num - int(second_number))

    if math == "multiplication":
        e.insert(0, f_num * int(second_number))

    if math == "division":
        e.insert(0, f_num / int(second_number))

def button_subtract():
    first_number = e.get()
    global f_num
    global math
    math = "subtraction"
    f_num = int(first_number)
    e.delete(0, END)

def button_multiply():
    first_number = e.get()
    global f_num
    global math
    math = "multiplication"
    f_num = int(first_number)
    e.delete(0, END)

def button_divide():
    first_number = e.get()
    global f_num
    global math
    math = "division"
    f_num = int(first_number)
    e.delete(0, END)

# Define Buttons

#state- for DISABLED, fg or bg for colour
#The lambda function allows us to send specific data to the callback function
button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0))
button_add = Button(root, text="+", padx=39, pady=20, command=button_add)
button_equal = Button(root, text="=", padx=91, pady=20, command=button_equal)
button_clear = Button(root, text="Clear", padx=79, pady=20, command=button_clear)

button_subtract = Button(root, text="-", padx=41, pady=20, command=button_subtract)
button_multiply = Button(root, text="*", padx=40, pady=20, command=button_multiply)
button_divide = Button(root, text="/", padx=41, pady=20, command=button_divide)

# Put the buttons on the screen

button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)

button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)

button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)

button_0.grid(row=4, column=0)
button_clear.grid(row=4, column=1, columnspan=2)
button_add.grid(row=5, column=0)
button_equal.grid(row=5, column=1, columnspan=2)

button_subtract.grid(row=6, column=0)
button_multiply.grid(row=6, column=1)
button_divide.grid(row=6, column=2)

#Keep the program running until we exit
root.mainloop()


"""
299. Bulls and Cows
Medium

You are playing the Bulls and Cows game with your friend.

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you
provide a hint with the following info:

    The number of "bulls", which are digits in the guess that are in the correct position.
    The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong
    position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.

The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both
secret and guess may contain duplicate digits.

Example 1:
    Input: secret = "1807", guess = "7810"
    Output: "1A3B"
    Explanation: Bulls are connected with a '|' and cows are underlined:
    "1807"
      |
    "7810"

Example 2:
    Input: secret = "1123", guess = "0111"
    Output: "1A1B"
    Explanation: Bulls are connected with a '|' and cows are underlined:
    "1123"        "1123"
      |      or     |
    "0111"        "0111"
    Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to
    allow one 1 to be a bull.

Constraints:
    1 <= secret.length, guess.length <= 1000
    secret.length == guess.length
    secret and guess consist of digits only.
"""

class Solution:
    # first attempt: naive
    # time complexity: O(n+m) -> O(n)
    # space complexity:
    def getHint(self, secret: str, guess: str) -> str:  # noqa
        matches, out_of_order = 0, 0  # "bulls", "cows"
        guess_digits, secret_digits = {}, {}

        for i in range(len(guess)):  # note: len(guess) == len(secret)
            guess_digit = guess[i]
            secret_digit = secret[i]

            # check digits for match
            if guess_digit == secret_digit:
                matches += 1
                continue

            # add digits to hash
            if guess_digit in guess_digits:
                guess_digits[guess_digit] += 1
            else:
                guess_digits[guess_digit] = 1
            if secret_digit in secret_digits:
                secret_digits[secret_digit] += 1
            else:
                secret_digits[secret_digit] = 1

            # check digits for order: guess -?> secret
            if guess_digit in secret_digits:
                out_of_order += 1
                # update guess hash
                guess_digits[guess_digit] -= 1
                if guess_digits[guess_digit] == 0:
                    guess_digits.pop(guess_digit)
                # update secret hash
                secret_digits[guess_digit] -= 1
                if secret_digits[guess_digit] == 0:
                    secret_digits.pop(guess_digit)

            # check digits for order: secret -?> guess
            # compensates for multiple iterations
            if secret_digit in guess_digits:
                out_of_order += 1
                # update guess hash
                guess_digits[secret_digit] -= 1
                if guess_digits[secret_digit] == 0:
                    guess_digits.pop(secret_digit)
                # update secret hash
                secret_digits[secret_digit] -= 1
                if secret_digits[secret_digit] == 0:
                    secret_digits.pop(secret_digit)

        return f"{matches}A{out_of_order}B"

class Test(Solution):
    # format: (input: secret, input: guess, output)
    tests: list[
        tuple[
            str, str, str
        ]
    ]

    tests = [
        # provided
        (
            "1807", "7810", "1A3B"
        ),
        (
            "1123", "0111", "1A1B"
        ),

        #
        (
            "111222", "222111", "0A6B"
        ),
        (
            "1", "2", "0A0B"
        ),
        (
            "1", "1", "1A0B"
        ),
        (
            "11", "11", "2A0B"
        ),
        (
            "111", "111", "3A0B"
        ),

    ]

    def test_all(self, *include):
        pass_count = 0
        tests_failed = []
        for i, each_test in enumerate(self.tests):
            if len(include) > 0 and i not in include:
                continue
            test_input = each_test[:-1]
            expected_output = each_test[2]
            actual_output = self.getHint(test_input[0], test_input[1])
            try:
                assert actual_output == expected_output
                print("PASS", end="")
                pass_count += 1
            except AssertionError:
                print("FAIL", end="")
                tests_failed.append(i)
            finally:

                print(f"  \t test_{i:03d}: {each_test}\n"
                      f"\t\t expd_out: {expected_output}\n"
                      f"\t\t test_out: {actual_output}\n")

        tested = len(include) if len(include) > 0 else len(self.tests)
        print(f'SUMMARY: TESTED {tested} | PASSED {pass_count} | FAILED {len(tests_failed)}')
        print(f'FAILED TESTS: {[f"test_{i:03d}" for i in tests_failed]}') if len(tests_failed) > 0 else print(end='')

Test().test_all()

leetcode_solutions/0299. Bulls and Cows.py


__author__ = 'Giovanni Tenorio'
#Python implementation of hangman
import sys

def get_secret_word():
	word = input("Please enter a word to be guessed \nthat does not contain ? or white space: ")
	return word

def is_game_over(guess_num):
	if guess_num > 6:
		return True
	else:
		return False

def display_hangman(hangman):
	hangman_s = "".join(hangman)
	print(hangman_s)

def display_guesses(guesses):
	print("So far you have guessed: ", end = '')
	for g in sorted(guesses):
		print(g, end = '')
	print()

def get_guess():
	cur_guess = input("Please enter your next guess: ")
	return cur_guess

while True:
	hasSpace = False
	s_word = get_secret_word()
	for s in s_word:
		if s == ' ' or s == '?':
			hasSpace = True
	if hasSpace == False:
		break

board_word = []
for i in s_word:
	board_word.append('?')

hangman = []

guess_num = 0
correct_guess_num = 0

total_guesses = []

while is_game_over(guess_num) == False:
	isCorrect = False
	display_hangman(hangman)

	for i in board_word:
		print(i, end = '')
	print()

	display_guesses(total_guesses)

	while True:
		badGuess = False
		cur_guess = get_guess()
		cur_guess.strip(' ')
		if len(cur_guess) > 1:
			print("You can only guess a single character")
			continue
		for t in total_guesses:
			if cur_guess == t:
				badGuess = True
		if badGuess == True:
			print("You already guessed the character: ", cur_guess)
		else:
			break

	count = 0
	for s in s_word:
		if cur_guess == s:
			isCorrect = True
			board_word[count] = s_word[count]
			correct_guess_num += 1
		count += 1

	total_guesses.append(cur_guess)
	if isCorrect == False:
		if guess_num == 0:
			hangman.append(' ')
			hangman.append('|')
			hangman.append(' \n')
		elif guess_num == 1:
			hangman.append(' ')
			hangman.append('0')
			hangman.append(' \n')
		elif guess_num == 2:
			hangman.append(' ')
			hangman.append('|')
			hangman.append(' \n')
		elif guess_num == 3:
			hangman[6] = '/'
		elif guess_num == 4:
			hangman[8] = '\\ \n'
		elif guess_num == 5:
			hangman.append('/')
			hangman.append(' ')
			hangman.append(' \n')
		elif guess_num == 6:
			hangman[11] = '\\ \n'
			display_hangman(hangman)
			print("You failed to guess the secret word: ", s_word)
		guess_num += 1

	#end if

	if correct_guess_num == len(s_word):
		guess_num = 999

		print("YOU GUESSED THE SECRET WORD GG!!!!")
#end big while


import math as m
import numpy as np

def dlugosc(matrix):
    return m.sqrt(np.dot(matrix.T,matrix))

def projekcja(matrix_u, matrix_v):
    matrix_u_v = np.dot(matrix_u.T,matrix_v)
    matrix_u_u = np.dot(matrix_u.T,matrix_u)
    if matrix_u_u == 0:
        return matrix_u
    return (matrix_u_v/matrix_u_u)*matrix_u

def q_dekompozycja(matrix_a):
    matrix_v = matrix_a.T
    matrix_u = []
    matrix_q = []
    for vector_v in matrix_v:
        suma = 0
        for vector_u in matrix_u:
            suma += projekcja(vector_u, vector_v)
        vector_u = vector_v - suma #Suma projekcji na macierz v, dla 1 u jest równa 0 dlatego v1=u1, dla większych macierzy sumuje wszsytkie projekcję na dany vektor
        matrix_u.append(vector_u)
        if dlugosc(vector_u) == 1:
            vector_e = vector_u
        else:
            vector_e = vector_u * (1 / dlugosc(vector_u))
        matrix_q.append(vector_e)
    Q = np.array(matrix_q).T
    R = np.dot(Q.T,matrix_a)
    return Q, R

def macierz_k(matrix_a):
    matrix_q, r = q_dekompozycja(matrix_a)
    matrix_a_new = np.dot(np.dot(matrix_q.T, matrix_a), matrix_q)
    return matrix_a_new

def matrix_wartosci_wlasne(matrix_a):
    matrix_a_new = matrix_a
    while (np.diag(matrix_a_new)-np.dot(matrix_a_new, np.ones((matrix_a_new.shape[0],1))).T).all()>0.0001:
        matrix_a_new = macierz_k(matrix_a_new)
    return matrix_a_new

def gauss(matrix):
    column_len = len(matrix.T[0])

    for x in range(column_len):
        if matrix[x][x] == 0:
            raise ZeroDivisionError()

        for y in range(column_len):
            if x != y:
                factor = matrix[y][x]/matrix[x][x]

                for z in range(column_len + 1):
                    matrix[y][z] = matrix[y][z] - factor * matrix[x][z]
    return [matrix[i][column_len]/matrix[i][i] for i in range(column_len)]

a=np.array([[1.,3.,5.,7.,9.],
            [3.,3.,3.,5.,7.],
            [5.,3.,5.,7.,9.],
            [7.,5.,7.,7.,9.],
            [9.,7.,9.,9.,9.]
])

np.set_printoptions(formatter={'float_kind':"{:.5f}".format})
print(a)
wartosci_wlasne = np.diag(matrix_wartosci_wlasne(a))
print(wartosci_wlasne)

b= np.array([[1, 3, 4],
            [2, 5, 8]
])

print(gauss(b))


from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import pytest
from versioningit.basics import basic_write
from versioningit.errors import ConfigError

@pytest.mark.parametrize(
    "filename,params,content",
    [
        ("foo/bar.txt", {}, "1.2.3\n"),
        ("foo/bar.py", {}, '__version__ = "1.2.3"\n'),
        ("foo/bar", {}, "1.2.3\n"),
        (
            "foo/bar.py",
            {"template": "__version__ = {version!r}"},
            "__version__ = '1.2.3'\n",
        ),
        ("foo/bar.tex", {"template": r"$v = {version}$\bye"}, "$v = 1.2.3$\\bye\n"),
        (
            "foo/bar.py",
            {
                "template": (
                    "__version__ = {version!r}\n"
                    '__build_date__ = "{build_date:%Y-%m-%dT%H:%M:%SZ}"'
                )
            },
            "__version__ = '1.2.3'\n__build_date__ = \"2038-01-19T03:14:07Z\"\n",
        ),
    ],
)
def test_basic_write(
    filename: str, params: dict[str, Any], content: str, tmp_path: Path
) -> None:
    basic_write(
        project_dir=tmp_path,
        template_fields={
            "version": "1.2.3",
            "build_date": datetime(2038, 1, 19, 3, 14, 7, tzinfo=timezone.utc),
        },
        params={"file": filename, **params},
    )
    assert (tmp_path / filename).read_text(encoding="utf-8") == content

def test_basic_write_no_file(tmp_path: Path) -> None:
    with pytest.raises(ConfigError) as excinfo:
        basic_write(
            project_dir=tmp_path, template_fields={"version": "1.2.3"}, params={}
        )
    assert str(excinfo.value) == "tool.versioningit.write.file must be set to a string"

def test_basic_write_bad_ext(tmp_path: Path) -> None:
    with pytest.raises(ConfigError) as excinfo:
        basic_write(
            project_dir=tmp_path,
            template_fields={"version": "1.2.3"},
            params={"file": "foo/bar.tex"},
        )
    assert str(excinfo.value) == (
        "tool.versioningit.write.template not specified and file has unknown"
        " suffix '.tex'"
    )
    assert list(tmp_path.iterdir()) == []


#! /usr/bin/env python

import rospy

from nav_msgs.msg import Odometry
from sensor_msgs.msg import NavSatFix
import csv

def gps_fused_callback(msg):
    myData = [[msg.latitude, msg.longitude]]
    with open('./fused.csv', 'a') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerows(myData)

def gps_raw_callback(msg):
    myData = [[msg.latitude, msg.longitude]]
    with open('./raw.csv', 'a') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerows(myData)

# def imu_callback(msg):
#     msg.yaw = msg.yaw * 180 / math.pi
#     fusionEKF.process_IMU(msg)

if __name__ == '__main__':
    rospy.init_node('ros_sub', anonymous=True)
    rospy.Subscriber('/gps/filtered', NavSatFix, gps_fused_callback)
    rospy.Subscriber('/fix', NavSatFix, gps_raw_callback)
    # rospy.Subscriber('/CustomPub', rpy, imu_callback)

    # create FusionEKF object here
    # fusionEKF = FusionEKF()
    rospy.spin()


from django.shortcuts import render
from django.http import HttpResponse
from bs4 import BeautifulSoup
import requests

def index(request):

    url = 'https://abiturient.manas.edu.kg/page/index.php?r=site%2Fmonitoring-all-deps'
    req = requests.get(url)
    src = req.text

    soup = BeautifulSoup(src, 'lxml')

    links = soup.find_all('div', class_='col-xl-2 col-lg-3 col-md-4 col-sm-12 hoverDiv')

    lst = []

    for i in links:

        url1 = i.find('a').get('href')
        url1 = 'https://abiturient.manas.edu.kg/' + url1
        req1 = requests.get(url1)
        src1 = req1.text

        soup1 = BeautifulSoup(src1, 'lxml')

        kvota = soup1.find('p').text[33:35]
        reg = soup1.find_all('tr', class_='bg-success')
        reg1 = len(reg) + len(soup1.find_all('tr', {'class': 'bg-light'}))

        min = 1000.0
        max = 0.0
        med = 0.0

        for m in reg:
            m = m.find_all('td')
            m = float(m[2].text)

            if m < min:
                min = m
            if m > max:
                max = m

            med += m

        if len(reg) == 0:
            min = 0
            max = 0
            med = 0
        else:
            med = round(med/len(reg), 2)

        lst.append({'name': i.find('a').text, 'количествомест': int(kvota), 'конкуренция': reg1, 'минимальныйбалл': min, 'максимальныйбалл': max, 'среднийбалл': med})

    return render(request, 'index.html', {'lst': lst})


# Write a program that prompts the user for a word
# and then calculates how many points that word would
# be worth in scrabble (points for each letter can
# need not check to see if the entry is a valid word
# nor account for point bonuses (a dictionary may be useful).

#dictionary to map letters to point values
points = {"a": 1 , "b": 3 , "c": 3 , "d": 2 ,
         "e": 1 , "f": 4 , "g": 2 , "h": 4 ,
         "i": 1 , "j": 8 , "k": 5 , "l": 1 ,
         "m": 3 , "n": 1 , "o": 1 , "p": 3 ,
         "q": 10, "r": 1 , "s": 1 , "t": 1 ,
         "u": 1 , "v": 4 , "w": 4 , "x": 8 ,
         "y": 4 , "z": 10}

#get user input
scrab_word = input("Enter a single word to score: ")
score = 0       #initialize score variable
for char in scrab_word.lower():     #loop over lowercase version of input
    score += points[char]           #add points for each letter

print('Your score is:',score)       #report score


# https://leetcode.com/problems/coin-change/submissions/

class Solution:
    def __init__(self):
        self.mem = {0: 0}
        self.coins = []

    def coinChange(self, coins: List[int], amount: int) -> int:
        self.coins = coins
        result = self.minCoin(amount)
        if result == int(1e9):
            return -1
        else:
            return result

    def minCoin(self, money):
        minN = int(1e9)
        # 최소값을 구하는 문제 --> recursive 과정에서 money가 minus가 되면 maxint를 리턴해줘서,
        # 유효하게 count 처리 되는 것을 방지한다
        if money < 0:
            return minN
        if money in self.mem:
            return self.mem[money]
        for coin in self.coins:
            if coin > money:
                continue
            minN = min(minN, self.minCoin(money - coin) + 1)
        self.mem[money] = minN
        return minN


"""Functions to parse the formula terms and prepare arrays."""

from collections import OrderedDict

import netCDF4

def get_formula_terms(var):
    """
    Return a `formula_terms` dict mapping var_names to variables.

    The input can be a netCDF variable (`var`) holding the `formula_terms`
    attribute or the attribute itself.

    """
    formula_terms = OrderedDict()
    if isinstance(var, netCDF4.Variable):
        var = var.formula_terms
    terms = [x.strip(":") for x in var.split()]
    for k, v in zip(terms[::2], terms[1::2]):
        formula_terms.update({k: v})
    return formula_terms

def get_formula_terms_variables(nc):
    """Return a list with all variables that holds the formula_terms attribute."""

    def func(v):
        return v is not None

    var = nc.get_variables_by_attributes(formula_terms=func)
    if not var:
        msg = (
            "Could not find the attribute `formula_terms` in any of the "
            "{!r} variables."
        ).format
        raise ValueError(msg(nc))
    return var

def get_formula_terms_dims(nc, formula_terms):
    """Return an OrderedDict object `dims` holding the `formula_terms` dimensions."""
    dims = OrderedDict()
    for k, v in formula_terms.items():
        dims.update({k: nc[v].dimensions})
    return dims

def z_shape(nc, dims):
    """Return the vertical coordinate `shape` based on the formula_terms `dims`."""
    all_dims = (
        dims.get("eta"),
        dims.get("depth"),
        dims.get("sigma"),
        dims.get("s"),
    )
    all_dims = _filter_none(all_dims)
    all_dims = _flatten(all_dims)
    all_dims = _remove_duplicate(all_dims)
    if len(all_dims) > 1:
        z_dims = all_dims[:]
        z_dims.insert(1, z_dims.pop(-1))

    shape = []
    for dim in z_dims:
        try:
            shape.append(len(nc.dimensions.get(dim)))
        except TypeError:
            msg = "Could not get dimension size for dim {!r}".format
            raise ValueError(msg(dim))

    return tuple(shape)

def _reshape(arr, new_shape):
    """Reshape arrays according to the expected dimensions."""
    shape = arr.shape
    dims = [k for k in shape]
    slicer = slice(None, None, None)

    def select(dim):
        return slicer if dim in dims else None

    keys = tuple(select(k) for k in new_shape)

    return arr.__getitem__(keys)

def prepare_arrays(nc, formula_terms, new_shape):
    """Prepare arrays for formulas."""
    import dask.array as da

    arrays = {}
    for term, var in formula_terms.items():
        var = nc[var]
        if var.ndim == 0:
            arr = var[:]
        else:
            if var.ndim > 2:
                chunks = (1,) + var.shape[1:]
            else:
                chunks = var.shape
            if term == "sigma" and var.ndim == 2:
                chunks = var.shape
            if term == "eta" and var.ndim == 2:
                chunks = (1,) + var.shape[1:]
            arr = da.from_array(var, chunks=chunks)
            arr = _reshape(arr, new_shape)
        arrays.update({term: arr})
    return arrays

def _filter_none(seq):
    """Filter out None in a list."""
    return [x for x in seq if x is not None]

def _flatten(seq):
    """Flatten a list."""
    return [item for sublista in seq for item in sublista]

def _remove_duplicate(seq):
    """Drop duplicated from a list."""
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]


from channels import Channels
from functions import read_json

CHANNEL_SUPPORT_CW = ["ChannelWebWidget", "ChannelApi"]
CW_MSG_TYPE = ["input_select", "form", "cards", "article"]

CHANNEL_SUPPORT_RASA = ["ChannelTelegram"]
RASA_MSG_TYPE = ["rasa_button"]

class Responses:
    def __init__(self, channel, user_title, user_name) -> None:
        self.channel = channel
        self.title = user_title
        self.user_name = user_name

        self.emojis = read_json("emojis.json")

    def generate_response_skeleton(self):
        channel = self.channel
        if channel in CHANNEL_SUPPORT_CW:
            return {"content": "", "content_type": "", "content_attributes": {"items": []}, "private": False}
        elif channel in CHANNEL_SUPPORT_RASA:
            return {"text": "", "buttons": []}
        return None

    def get_channel_data(self):
        channel = self.channel
        json = Channels(self.title, self.user_name)
        if channel is None:
            return "missing channel"
        if channel in CHANNEL_SUPPORT_CW:
            return json.ChannelSupportCW()
        elif channel in CHANNEL_SUPPORT_RASA:
            return json.ChannelSupportRasa()
        # data = eval(
        #     f"__import__('{DATA_FILE_NAME}').Channels('{self.title}').{self.channel}()")
        return None

    def get_response_by_intent(self, intent):
        skeleton = self.generate_response_skeleton()
        if skeleton is None:
            return "missing skeleton"

        raw = self.get_channel_data()
        if raw is None:
            return "missing data"

        data = raw.get(intent)
        if not data:
            return "cannot get data from intent"

        message = data.get("message")
        message_type = data.get("message_type")
        payload = data.get("payload")

        if not message_type:
            return "missing message_type"

        channel = self.channel
        if channel in CHANNEL_SUPPORT_CW and message_type in CW_MSG_TYPE:
            skeleton["content"] = message
            skeleton["content_type"] = message_type
            skeleton["content_attributes"]["items"] = payload
            return skeleton
        elif channel in CHANNEL_SUPPORT_RASA and message_type in RASA_MSG_TYPE:
            skeleton["text"] = message
            skeleton["buttons"] = payload
            return skeleton

        if message_type == "no_payload":
            return message

        elif message_type == "full_of_text":
            text_menu = ""
            for val in payload:
                title = val.get("title")
                text_menu += f"{self.emojis.get('check_mark_button')} {title}\n"
            if isinstance(message, str):
                new_msg = []
                new_msg.append(message)
                new_msg.append(text_menu.strip())
                return new_msg

            message.append(text_menu.strip())
            return message

        return "Tham số message_type không phù hợp với kênh hiện tại"

    def get_bot_responses(self, dispatcher, intent):
        bot_response = self.get_response_by_intent(intent)
        # print(bot_response)
        if bot_response is None:
            dispatcher.utter_message(text=f"Lỗi không có phản hồi từ bot")

        if isinstance(bot_response, list):
            for val in bot_response:
                dispatcher.utter_message(text=val)
        elif isinstance(bot_response, dict):
            msg = bot_response.get("content")
            type = bot_response.get("content_type")

            if isinstance(msg, list):
                for val in msg[:-1]:
                    dispatcher.utter_message(text=val)
                if type == "cards":
                    bot_response["content_attributes"]["items"][0]["description"] = msg.pop()
                bot_response["content"] = msg.pop()

            dispatcher.utter_message(json_message=bot_response)
            if type == "cards":
                dispatcher.utter_message(text=f"Mai rất sẵn lòng trả lời nếu {self.title} muốn biết thêm điều gì khác ^^. Và vui lòng nói cho em nghe luôn ý muốn của {self.title}")
        else:
            dispatcher.utter_message(text=f"Lỗi định dạng ({type(bot_response)})")


test_list1 = list(map(int, input().split()))
test_list2 = list(map(int, input().split()))

test_list1.sort()
test_list2.sort()

# to combine two sorted lists
size_1 = len(test_list1)
size_2 = len(test_list2)

res1 = []
i, j = 0, 0

while i < size_1 and j < size_2:
    if test_list1[i] < test_list2[j]:
      res1.append(test_list1[i])
      i += 1

    else:
      res1.append(test_list2[j])
      j += 1

res1 = res1 + test_list1[i:] + test_list2[j:]

# printing result
print ("The Ascending sorted list is : " + str(res1))

print ("The Descending sorted list is : " + str(sorted(res1, reverse=True)))


import krpc, math
import numpy
import time
import Global
conn = Global.conn
vessel = Global.vessel
target = Global.target

#change these as desired
global target_apoapsis
global target_inclination
global ftarget_apoapsis
target_apoapsis = 262#first target orbital apoapsis
ftarget_apoapsis = 262#second target orbital apoapsis
target_inclination = 28.6085
target_const = 900#velocity at which pitch angle should be 45 degrees from horizon

global b_ref
b_ref = vessel.orbit.body.reference_frame

global r2d
global d2r
r2d = 180.0/numpy.pi
d2r = numpy.pi/180.0

ns = 0

global mode
mode = 0

if mode==0:
    #calculation of launch azimuth

    rot = numpy.arcsin(numpy.cos(target_inclination*d2r)/numpy.cos(vessel.flight(b_ref).latitude*d2r))
    if ns == 0:
        rot = rot
    elif ns == 1:
        rot = numpy.pi-rot
    rot *= r2d

    print("Launch Azimuth: %f" % (rot))

    print("Desired inclination: %f" % target_inclination)

    time.sleep(10)

vessel.control.throttle = 1.0
time.sleep(5)
vessel.control.activate_next_stage()
time.sleep(5)
vessel.control.activate_next_stage()

vessel.auto_pilot.engage()

def launch_steering(check ,rot, target_const):
    while vessel.orbit.apoapsis_altitude<target_apoapsis*1000:
        v_surf_count = vessel.flight(vessel.orbit.body.reference_frame).speed
        #gravity turn
        pitch_ang = numpy.arctan(target_const/v_surf_count)*180.0/numpy.pi
        #mode 1 should never be necessary provided the landing platform is positioned in line with launch_azimuth
        if mode==1:
            vlat = vessel.flight(b_ref).latitude*numpy.pi/180.0
            vlon = vessel.flight(b_ref).longitude*numpy.pi/180.0

            tlat = target.flight(b_ref).latitude*numpy.pi/180.0
            tlon = target.flight(b_ref).longitude*numpy.pi/180.0

            rot = numpy.arctan2(numpy.sin(tlon-vlon)*numpy.cos(tlat),numpy.cos(vlat)*numpy.sin(tlat) - numpy.sin(vlat)*numpy.cos(tlat)*numpy.cos(tlon-vlon))
            rot*=r2d

        #MECO-1
        if check == 0:
            if v_surf_count<=2300:
                vessel.auto_pilot.target_pitch_and_heading(pitch_ang, rot)
            else:
                vessel.control.throttle = 0.0
                break
        elif check == 1:
            vessel.auto_pilot.target_pitch_and_heading(pitch_ang, rot)
        time.sleep(0.01)

launch_steering(0, rot, target_const)
time.sleep(2)
vessel.control.rcs = True
vessel.control.set_action_group(1, True)
vessel.control.activate_next_stage()
time.sleep(2)
vessel.control.activate_next_stage()
time.sleep(2)
vessel.control.throttle = 1.0
launch_steering(1, rot, target_const+500)

vessel.auto_pilot.disengage()
import Final_stage
Final_stage.Final_stage(target_apoapsis, rot, ftarget_apoapsis)
conn.close()


#
# @lc app=leetcode.cn id=167 lang=python3
#
# [167] 两数之和 II - 输入有序数组
#
from typing import List
# @lc code=start

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        dic = {}
        for i, num in enumerate(numbers):
            if(target-num) in dic:
                return [dic[target-num]+1, i+1]
            dic[num] = i
        # @lc code=end
so = Solution()

print(so.twoSum([2, 5, 7, 8], 9))


from django.urls import path
from . import views

urlpatterns = [
    path('', views.start_page, name='start_page'),
    path('gallery', views.start_page, name='start_page_redirect'),
    path('gallery/images', views.images_festival_page, name='images_festival_page'),
    path('gallery/stories', views.stories_festival_page, name='stories_festival_page'),
    path('gallery/add_comment/<str:TYPE>_<int:ID>', views.new_comment_page,
         name='images_new_comment'),
    path('gallery/view_comments/<str:TYPE>_<int:ID>', views.view_comments_page,
         name='images_new_comment')
]


import argparse
import os
import torch
import torch.nn.functional as F
import datetime

from torch.utils.data import DataLoader
from datasets.samplers import CategoriesSampler
from datasets.mini_imagenet import MiniImageNet
from datasets.tiered_imagenet import TieredImageNet
from datasets.cifarfs import CIFAR_FS
from resnet import resnet12
from util import str2bool, set_gpu, count_acc, seed_torch, compute_confidence_interval
from model import SFTAttn

def get_dataset(args):
    if args.dataset == 'mini':
        testset = MiniImageNet('test', args.size)
        n_cls = 64
        print("=> MiniImageNet...")
    elif args.dataset == 'tiered':
        testset = TieredImageNet('test', args.size)
        n_cls = 351
        print("=> TieredImageNet...")
    elif args.dataset == 'cifarfs':
        testset = CIFAR_FS('test', args.size)
        n_cls = 64
        print("=> CIFAR-FS...")
    else:
        print("Invalid dataset...")
        exit()

    test_sampler = CategoriesSampler(testset.label, args.test_batch,
                                    args.test_way, args.shot + args.test_query)
    test_loader = DataLoader(dataset=testset, batch_sampler=test_sampler,
                            num_workers=args.worker, pin_memory=True)
    return test_loader, n_cls

def main(args):
    loader, n_cls = get_dataset(args)

    if args.dataset in ['mini', 'tiered']:
        encoder1 = resnet12(avg_pool=True, drop_rate=0.1, dropblock_size=5, num_classes=n_cls).cuda()
        encoder2 = resnet12(avg_pool=True, drop_rate=0.1, dropblock_size=5, num_classes=n_cls).cuda()
    elif args.dataset in ['cifarfs']:
        encoder1 = resnet12(avg_pool=True, drop_rate=0.1, dropblock_size=2, num_classes=n_cls).cuda()
        encoder2 = resnet12(avg_pool=True, drop_rate=0.1, dropblock_size=2, num_classes=n_cls).cuda()
    else:
        print("Invalid dataset...")
        exit()

    if args.pretrain_path_1:
        checkpoint_file = os.path.join(args.pretrain_path_1, 'max-acc.pth.tar')
        if not os.path.isfile(checkpoint_file):
            print("=> Pretrain model 1 not found...")
            exit()
        checkpoint = torch.load(checkpoint_file)
        encoder1.load_state_dict(checkpoint['model'])
        print("=> Pretrain encoder 1 loaded...")

    if args.pretrain_path_2:
        checkpoint_file = os.path.join(args.pretrain_path_2, 'max-acc.pth.tar')
        if not os.path.isfile(checkpoint_file):
            print("=> Pretrain model 2 not found...")
            exit()
        checkpoint = torch.load(checkpoint_file)
        encoder2.load_state_dict(checkpoint['model'])
        print("=> Pretrain encoder 2 loaded...")

    model = SFTAttn(args).cuda()

    # check save point
    checkpoint_file = os.path.join(args.save_path, 'max-acc.pth.tar')
    if not os.path.isfile(checkpoint_file):
        print("=> Model not found...")
        exit()
    checkpoint = torch.load(checkpoint_file)
    model.load_state_dict(checkpoint['model'])
    print("=> Model loaded from best epoch", checkpoint['best_epoch'], "...")

    encoder1.eval()
    encoder2.eval()
    model.eval()

    acc_list = []

    with torch.no_grad():
        for _, batch in enumerate(loader, 1):
            data, _ = [_.cuda() for _ in batch]
            label = torch.arange(args.test_way).repeat(args.test_query)
            label = label.type(torch.cuda.LongTensor)

            with torch.no_grad():
                data1 = encoder1(data, is_feat=args.is_feat)
                data2 = encoder2(data, is_feat=args.is_feat)

            logits = model(data1, data2)
            acc = count_acc(logits, label)
            acc_list.append(acc*100)

    a, b = compute_confidence_interval(acc_list)
    print("{}-way {}-shot accuracy with 95% interval : {:.2f}±{:.2f}".format(args.test_way, args.shot, a, b))

if __name__ == '__main__':
    start_time = datetime.datetime.now()

    # settings
    parser = argparse.ArgumentParser()
    parser.add_argument('--save-path', default='./save/mini_final')
    parser.add_argument('--pretrain-path-1', default='./save/mini_rot')
    parser.add_argument('--pretrain-path-2', default='./save/mini_dist')
    parser.add_argument('--gpu', default='0')
    parser.add_argument('--seed', type=int, default=1)
    # fusion
    parser.add_argument('--beta', type=float, default=0.5)
    parser.add_argument('--gamma', type=float, default=0.5)
    # network
    parser.add_argument('--h-dim', type=int, default=640)
    parser.add_argument('--dropout', type=float, default=0.4)
    parser.add_argument('--temperature', type=float, default=1.0)
    # dataset
    parser.add_argument('--dataset', default='mini', choices=['mini','tiered','cifarfs'])
    parser.add_argument('--size', type=int, default=84)
    parser.add_argument('--worker', type=int, default=8)
    # few-shot
    parser.add_argument('--shot', type=int, default=1)
    parser.add_argument('--test-way', type=int, default=5)
    parser.add_argument('--test-query', type=int, default=15)
    parser.add_argument('--test-batch', type=int, default=2000)
    parser.add_argument('--norm', type=str2bool, nargs='?', default=True)
    parser.add_argument('--is-feat', type=str2bool, nargs='?', default=True)
    parser.add_argument('--distance', type=str, default='euc', choices=['cos', 'euc'])
    args = parser.parse_args()

    if args.dataset in ['mini', 'tiered']:
        args.size = 84
    elif args.dataset in ['cifarfs']:
        args.size = 32
        args.worker = 0
    else:
        args.size = 28
    # fix seed
    seed_torch(args.seed)
    set_gpu(args.gpu)

    main(args)

    end_time = datetime.datetime.now()
    print("End time :{} total ({})".format(end_time, end_time - start_time))


def cfg_to_args(config):
    """Compatibility helper to use setup.cfg in setup.py."""
    kwargs = {}
    opts_to_args = {
        'metadata': [
            ('name', 'name'),
            ('author', 'author'),
            ('author-email', 'author_email'),
            ('maintainer', 'maintainer'),
            ('maintainer-email', 'maintainer_email'),
            ('home-page', 'url'),
            ('summary', 'description'),
            ('description', 'long_description'),
            ('download-url', 'download_url'),
            ('classifier', 'classifiers'),
            ('platform', 'platforms'),
            ('license', 'license'),
            ('keywords', 'keywords'),
        ],
        'files': [
            ('packages_root', 'package_dir'),
            ('packages', 'packages'),
            ('modules', 'py_modules'),
            ('scripts', 'scripts'),
            ('package_data', 'package_data'),
            ('data_files', 'data_files'),
        ],
    }

    opts_to_args['metadata'].append(('requires-dist', 'install_requires'))
    if IS_PY2K and not which('3to2'):
        kwargs['setup_requires'] = ['3to2']
    kwargs['zip_safe'] = False

    for section in opts_to_args:
        for option, argname in opts_to_args[section]:
            value = get_cfg_value(config, section, option)
            if value:
                kwargs[argname] = value

    if 'long_description' not in kwargs:
        kwargs['long_description'] = read_description_file(config)

    if 'package_dir' in kwargs:
        kwargs['package_dir'] = {'': kwargs['package_dir']}

    if 'keywords' in kwargs:
        kwargs['keywords'] = split_elements(kwargs['keywords'])

    if 'package_data' in kwargs:
        kwargs['package_data'] = get_package_data(kwargs['package_data'])

    if 'data_files' in kwargs:
        kwargs['data_files'] = get_data_files(kwargs['data_files'])

    kwargs['version'] = get_version()

    if not IS_PY2K:
        kwargs['test_suite'] = 'test'

    return kwargs


#
# Postprocessing and unifying output from AggregaThor
#
# Developers:
#   - Grigori Fursin, cTuning foundation / dividiti, 2019
#

import json
import os
import re
import sys

def ck_postprocess(i):
    ck=i['ck_kernel']

    rt=i['run_time']
    deps=i['deps']

    d={}

    env=i.get('env',{})

    rf1=rt.get('run_cmd_out1','') # stdout
    rf2=rt.get('run_cmd_out2','') # stderr

    lst=[]

    if os.path.isfile(rf2):
       r=ck.load_text_file({'text_file':rf1,'split_to_list':'yes'})
       if r['return']>0: return r
       lst+=r['lst']

    # Finding and unifying different characteristics
    vars=[{"text":"speed:", "key":"speed"},
          {"text":" accuracy=", "key":"accuracy"},
          {"text":"Train-accuracy=", "key":"train-accuracy"},
          {"text":"Time cost=", "key":"time-cost"},
          {"text":"Total arg_params size =", "key":"total-size"},
          {"text":"Validation-accuracy=", "key":"validation-accuracy"}]
    for q in lst:
        for v in vars:
            t=v['text']
            k=v['key']

            j=q.find(t)
            if j>=0:
               j1=q.find(" ",j+len(t))
               j2=len(q)
               j3=min(j1,j2)

               d[k]=q[j1+len(t):j2]

               d['post_processed']='yes'

    # Embedding to the CK pipeline

    rr={}
    rr['return']=0
    if d.get('post_processed','')=='yes':
        ck.out('  Success!)')
        # Save to file.
        r=ck.save_json_to_file({'json_file':'tmp-ck-timer.json', 'dict':d})
        if r['return']>0: return r
    else:
        rr['return']=1
        rr['error']='failed to post-process results - some key strings are not found'

    return rr

# Do not add anything here!


from sbb_b import sbb_b
from sbb_b.core.managers import edit_delete, edit_or_reply
from sbb_b.helpers.utils import mentionuser
from telethon import functions
from telethon.errors import ChatAdminRequiredError, UserAlreadyInvitedError
from telethon.tl.types import Channel, Chat, User

async def get_group_call(chat):
    if isinstance(chat, Channel):
        result = await catub(functions.channels.GetFullChannelRequest(channel=chat))
    elif isinstance(chat, Chat):
        result = await catub(functions.messages.GetFullChatRequest(chat_id=chat.id))
    return result.full_chat.call

async def chat_vc_checker(event, chat, edits=True):
    if isinstance(chat, User):
        await edit_delete(event, "- المكالمة الصوتية غير متاحة في المجموعة الخاصة")
        return None
    result = await get_group_call(chat)
    if not result:
        if edits:
            await edit_delete(event, "**- لا توجد دردشة صوتية في هذه المجموعة**")
        return None
    return result

async def parse_entity(entity):
    if entity.isnumeric():
        entity = int(entity)
    return await catub.get_entity(entity)

@sbb_b.ar_cmd(pattern="تشغيل المكالمة")
async def start_vc(event):
    vc_chat = await sbb_b.get_entity(event.chat_id)
    gc_call = await chat_vc_checker(event, vc_chat, False)
    if gc_call:
        return await edit_delete(event, "**- المكالمة الصوتية بالأصل موجودة**")
    try:
        await sbb_b(
            functions.phone.CreateGroupCallRequest(
                peer=vc_chat,
                title="مكالمة جمثون",
            )
        )
        await edit_delete(event, "**- تم بنجاح تشغيل المكالمة الصوتية**")
    except ChatAdminRequiredError:
        await edit_delete(event, "- عليك أن تكون مشرف اولا", time=20)

@sbb_b.ar_cmd(pattern="انهاء المكالمة")
async def end_vc(event):
    vc_chat = await sbb_b.get_entity(event.chat_id)
    gc_call = await chat_vc_checker(event, vc_chat)
    if not gc_call:
        return
    try:
        await sbb_b(functions.phone.DiscardGroupCallRequest(call=gc_call))
        await edit_delete(event, "**- تم بنجاح الغاء المكالمة الصوتية**")
    except ChatAdminRequiredError:
        await edit_delete(event, "- عليك أن تكون مشرف اولا", time=20)

@sbb_b.ar_cmd(pattern="دعوة ?(.*)?")
async def inv_vc(event):
    users = event.pattern_match.group(1)
    reply = await event.get_reply_message()
    vc_chat = await sbb_b.get_entity(event.chat_id)
    gc_call = await chat_vc_checker(event, vc_chat)
    if not gc_call:
        return
    if not users:
        if not reply:
            return await edit_delete(
                "**يجب عليك الرد على المستخدم او وضع معرفه مع الامر**"
            )
        users = reply.from_id
    await edit_or_reply(event, "**- تم دعوة المستخدم الى المكالمة**")
    entities = str(users).split(" ")
    user_list = []
    for entity in entities:
        cc = await parse_entity(entity)
        if isinstance(cc, User):
            user_list.append(cc)
    try:
        await sbb_b(
            functions.phone.InviteToGroupCallRequest(call=gc_call, users=user_list)
        )
        await edit_delete(event, "**- تم دعوة المستخدمين الى المكالمة**")
    except UserAlreadyInvitedError:
        return await edit_delete(
            event, "**- المستحدم بالأصل مدعو لهذه المكالمة**", time=20
        )

@sbb_b.ar_cmd(pattern="معلومات المكالمة")
async def info_vc(event):
    vc_chat = await sbb_b.get_entity(event.chat_id)
    gc_call = await chat_vc_checker(event, vc_chat)
    if not gc_call:
        return
    await edit_or_reply(event, "**- جار الحصول على معلومات المكالمة**")
    call_details = await sbb_b(
        functions.phone.GetGroupCallRequest(call=gc_call, limit=1)
    )
    grp_call = "**معلومات المكالمة الصوتية:**\n\n"
    grp_call += f"**العنوان :** {call_details.call.title}\n"
    grp_call += f"**عدد المشاركين :** {call_details.call.participants_count}\n\n"

    if call_details.call.participants_count > 0:
        grp_call += "**المشاركين**\n"
        for user in call_details.users:
            nam = f"{user.first_name or ''} {user.last_name or ''}"
            grp_call += f"  ● {mentionuser(nam,user.id)} - `{user.id}`\n"
    await edit_or_reply(event, grp_call)

@sbb_b.ar_cmd(pattern="عنوان?(.*)?")
async def title_vc(event):
    title = event.pattern_match.group(1)
    vc_chat = await sbb_b.get_entity(event.chat_id)
    gc_call = await chat_vc_checker(event, vc_chat)
    if not gc_call:
        return
    if not title:
        return await edit_delete("**- عليك وضع اسم مع الامر اولا**")
    await sbb_b(functions.phone.EditGroupCallTitleRequest(call=gc_call, title=title))
    await edit_delete(event, f"-تم بنجاح تغيير اسم المكالمة الصوتية الى **{title}**")


'''
Author: Jeffrey Sultan
Date: 8/4/22
Dataset: Uber Fares Data csv
App URL: ###############
Description: This interactive application containing Uber ride data from 2009 to 2015.
            The data is depicted in a series of visualizations to illustrate various metrics that
            were found. The original data table was updated to remove unneeded information. Date,
            time and straight-line calculated distance between pickup and drop-off location was
            also added to the data table.

'''
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import geopy.distance
import seaborn as sns
import matplotlib.pyplot as plt

# Set constants
ARRIVAL_DATE_COLUMN = 'pickup_datetime'
DATA = "UberData.csv"
#---------------------------------------------------------------------
# Code checklist: Function: function w/ defualt parameter, two parameters, returns value
def getData(key, dict='m'):
    monthDict = {1:"January",2:"February",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October",11:"November",12:"Decemeber"}
    weekTpl = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

    if dict == 'm':
        return monthDict[key]
    elif dict == 'w':
        return weekTpl[key]
#---------------------------------------------------------------------
# Set page layout and create header
st.set_page_config(layout='wide')

# Initialize application with title, header and descriptive information
# st cols(#1, #2) where #1 = width of col1 and #2 = width of col2
row0_1, row0_2 = st.columns((3,1))
with row0_1:
    st.title('Uber pickups in NYC')
with row0_2:
    st.text("")
    st.subheader('Streamlit App created by:')
    st.text("Jeffrey Sultan")
# col1 spacer = 0.1 padding, col2 width, col3 spacer = 0.1 padding
row3_spacer1, row3_1, row3_spacer2 = st.columns((0.1, 1, 0.1))
with row3_1:
    st.markdown("This interactive application containing Uber ride data from 2009 to 2015. The data is depicted in a series of visualizations to illustrate various metrics that were found. ")
    st.markdown("The original data table was updated to remove unneeded information. ")
    st.markdown("Date, time and straight-line calculated distance between pickup and drop-off location was also added to the data table. ")
st.title('')

# creating a sidebar to display additional project information
# Code checklist - At least one function that does not return a value
def load_sidebar():
    st.sidebar.title("About")
    st.sidebar.info(
        """
        This application uses the following charts to visualize the data collected:
        \n1) A map of the pickup location
        \n2) A scatter plot of fare vs distance
        \n3) A pie chart of the date/time distribution
        \n4) A line chart of the pickup time distribution
        \n5) A scatter plot with linear prediction
        """
    )
    st.sidebar.title("Author - Date:")
    st.sidebar.info("Author: Jeffrey Sultan")
    st.sidebar.info("Date: 04Aug2022")
    st.sidebar.info("Dataset: Uber Fares Data CSV")
load_sidebar()
#------------------------------------------------------------------------
# Section 0 - Start with loading data from the CSV

def load_data():
    data = pd.read_csv(DATA)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)

    return data

# Loading bar used to work but for some reason i no longer see it
data_load_state = st.text('Loading data...')
data = load_data()
data_load_state.text("")
#------------------------------------------------------------------------
# Section 1 - Reframe the data provided to be more accessible and removing outliers

# The line below reframes the pickup and dropoff locations:
# Latitude should be 40 to 41. Longitude should be -73 to -75
data = data[(data.pickup_latitude<41) & (data.dropoff_latitude<41) &
        (data.pickup_latitude>40) & (data.dropoff_latitude>40) &
        (data.pickup_longitude<-73) & (data.dropoff_longitude<-73) &
        (data.pickup_longitude>-75) & (data.dropoff_longitude>-75)]

# Renaming the pickup latitude and longitude to work with map utility
data = data.rename({'pickup_longitude': 'longitude', 'pickup_latitude': 'latitude'}, axis=1)
data[ARRIVAL_DATE_COLUMN] = pd.to_datetime(data[ARRIVAL_DATE_COLUMN])

# Remove unnecessary columns (Unnamed and key columns)
# Code checklist: dataframe: drop columns
data.drop(['unnamed: 0', 'key'], axis=1, inplace=True)

# Create new columns to split the arrival date column from date/time conversion
# Code checklist: dataframe: add columns
data['year'] = data.pickup_datetime.dt.year
data['month'] = data.pickup_datetime.dt.month
data['weekday'] = data.pickup_datetime.dt.weekday
data['hour'] = data.pickup_datetime.dt.hour

# Using the geopy module, we can create a new column that evaluates the distance between pickup and drop off locations.
# Note that the pickup lat/long columns were renamed above from 'pickup_latitude' to 'latitude' and same for longitude
# geopy.distance.distance uses the geodesic distance which is the shortest distance on the surface of an ellipsoidal model of the earth (Karney 2013)
# The calculated distance is in meters, rounded to 2 decimal places and placed in a new column titled 'distance'
data['distance']=[round(geopy.distance.distance((data.latitude[i], data.longitude[i]),(data.dropoff_latitude[i], data.dropoff_longitude[i])).m,2) for i in data.index]

# Reframe the data set to exclude fare_amount outliers more than $100 and distance outliers less than 1000 meters
data = data[(data.fare_amount<=100)]
data = data[(data.distance > 1000)]

#------------------------------------------------------------------------
# Section 2 - Option to show the reframed data from above + stats

# Checkbox to show raw data
# Code checklist: pandas: sort column asc/desc
if st.checkbox('Show data table'):
    st.subheader('Reframed data with added columns')
    fare_median = data['fare_amount'].median()
    dist_median = data['distance'].median()
    st.text(f'{len(data)} Entries\t ${fare_median} Median of Ride Fares\t {dist_median}m Median of Distances Travelled')
    st.write(data.sort_values('distance', ascending=False))
#------------------------------------------------------------------------
# Section 3 - Visualize the pickup locations by hour on a map of NYC
# Separation bar html copied from streamlit discussion bar - see references
st.markdown("""
 """, unsafe_allow_html=True)
st.subheader('| VISUALIZING MAP OF ALL PICKUP LOCATIONS DEPENDENT ON MONTH OR HOUR')
map_option = st.radio(
     "How to filter the data appearing on the map?",
     ('Pickup Hour', 'Pickup Month', 'Pickup Weekday'))

# Code checklist: Data structures: Dictionary & Streamlit UI Controls: Slider
# Code checklist: At least one function that is called twice
if map_option == 'Pickup Month':
    # Sliding bar for mapping feature: min = (1-Jan), max = (12-Dec)
    month_to_filter = st.slider('MONTH OF THE YEAR', 1, 12)
    selected_month = getDict(month_to_filter, 'm')
    filtered_data = data[data[ARRIVAL_DATE_COLUMN].dt.month == month_to_filter]
    st.subheader(f"Map of all pickups in {selected_month}")
    st.text(f"Showing {len(filtered_data)} pickups")
    st.map(filtered_data)
elif map_option == 'Pickup Weekday':
    # Sliding bar for mapping feature: min = 0hr, max = 23hr, default = 17hr
    weekday_to_filter = st.slider('DAY OF WEEK', 0, 6)
    selected_weekday = getData(weekday_to_filter, 'w')
    filtered_data = data[data[ARRIVAL_DATE_COLUMN].dt.weekday == weekday_to_filter]
    st.subheader(f'Map of all pickups on {selected_weekday}')
    st.text(f"Showing {len(filtered_data)} pickups")
    st.map(filtered_data)
elif map_option == 'Pickup Hour':
    # Sliding bar for mapping feature: min = 0hr, max = 23hr, default = 17hr
    hour_to_filter = st.slider('HOUR OF THE DAY', 0, 23, 17)
    filtered_data = data[data[ARRIVAL_DATE_COLUMN].dt.hour == hour_to_filter]
    st.subheader('Map of all pickups at %s:00' % hour_to_filter)
    st.text(f"Showing {len(filtered_data)} pickups")
    st.map(filtered_data)

#------------------------------------------------------------------------
# Section 4 - Scatter Plot visualization of fares vs distance with optional filters
st.markdown("""
 """, unsafe_allow_html=True)
st.subheader('| VISUALIZING SCATTERPLOT OF FARES VS DISTANCE AND VARIABLE HUE')

fig4_option = st.selectbox('USE VARIABLE TO SET HUE',('month', 'year', 'weekday', 'hour'))
fig4 = plt.figure()
# next line somehow controls grid lines in my graph. Copied from a seaborn discussion on stack exchange. see refs
sns.set(rc={'figure.figsize':(8,6)})
plt.ylim(0, 100)

plt.title('Fares vs Distance')
plt.xlabel('Straight-line Distance (meters)')
plt.ylabel('Fare ($)')

# Scatter plot created using the seaborn module
sns.scatterplot(data=data, x='distance',y='fare_amount',hue=fig4_option, s=10)
st.pyplot(fig4)

# Next create a pie chart to illustrate the percentage of entries found for each hue option selected above
if fig4_option == 'year':
    ind1 = pd.DataFrame(data.groupby('year').year.count()).rename(columns={'year': 'count'}).reset_index()
    g1 = px.pie(ind1,
                values='count',
                names='year',
                color='year',
                color_discrete_map={'2009': 'red', '2010': 'blue', '2011': 'green', '2012': 'yellow', '2013': 'orange',
                                    '2014': 'purple', '2015': 'brown'},
                title='| PERCENTAGE OF DATA RECORDED FROM EACH YEAR')
    g1.update_traces(textposition='inside',
                     textinfo='percent+label',
                     showlegend=False)
    st.plotly_chart(g1, use_container_width=True)
elif fig4_option == 'month':
    ind1 = pd.DataFrame(data.groupby('month').month.count()).rename(columns={'month': 'count'}).reset_index()
    g1 = px.pie(ind1,
                values='count',
                names='month',
                color='month',
                title='| PERCENTAGE OF DATA RECORDED FROM EACH MONTH')
    g1.update_traces(textposition='inside',
                     textinfo='percent+label',
                     showlegend=False)
    st.plotly_chart(g1, use_container_width=True)
elif fig4_option == 'weekday':
    ind1 = pd.DataFrame(data.groupby('weekday').weekday.count()).rename(columns={'weekday': 'count'}).reset_index()
    g1 = px.pie(ind1,
                values='count',
                names='weekday',
                color='weekday',
                title='| PERCENTAGE OF DATA RECORDED FROM EACH WEEKDAY')
    g1.update_traces(textposition='inside',
                     textinfo='percent+label',
                     showlegend=False)
    st.plotly_chart(g1, use_container_width=True)
elif fig4_option == 'hour':
    ind1 = pd.DataFrame(data.groupby('hour').hour.count()).rename(columns={'hour': 'count'}).reset_index()
    g1 = px.pie(ind1,
                values='count',
                names='hour',
                color='hour',
                title='| PERCENTAGE OF DATA RECORDED FROM EACH HOUR')
    g1.update_traces(textposition='inside',
                     textinfo='percent+label',
                     showlegend=False)
    st.plotly_chart(g1, use_container_width=True)

#------------------------------------------------------------------------
# Section 5 - Chart representing the data from each year and time of day
st.markdown("""
 """, unsafe_allow_html=True)
st.subheader('| VISUALIZING DATA OF RELATED TO DATE & TIME INFORMATION')

# Bar chart that illustrates the amount of data recorded from each time of day
fig5_2_option = st.selectbox('USE VARIABLE TO FILTER DATA', ('year', 'month'))
if fig5_2_option == 'year':
    fig5_year_to_filter = st.slider('YEAR', 2009, 2015)
    filtered_data = data[data[ARRIVAL_DATE_COLUMN].dt.year == fig5_year_to_filter]
elif fig5_2_option == 'month':
    fig5_month_to_filter = st.slider('MONTH', 1, 12)
    filtered_data = data[data[ARRIVAL_DATE_COLUMN].dt.month == fig5_month_to_filter]
ind2 = pd.DataFrame(filtered_data.groupby('hour').hour.count()).rename(columns={'hour':'count'}).reset_index()
g3 = px.line(ind2,
            x='hour',
            y='count',
            title='| POPULAR PICKUP TIMES EACH DAY')
st.plotly_chart(g3, use_container_width=True)
#------------------------------------------------------------------------
# Section 6 - Scatter plot of distance vs fare amount and prediction of fare based on distance
st.markdown("""
 """, unsafe_allow_html=True)
st.subheader('| LINEAR REGRESSION OF DISTANCE VS FARE AMOUNT')

# Manual calculation of Y-estimate using Ordinary Least Squares (could not get stats package to work correctly)
x = filtered_data['distance']
y = filtered_data['fare_amount']

# Calculate the mean of X and y
xmean = np.mean(x)
ymean = np.mean(y)

# Calculate the terms needed for the numerator and denominator of beta
df_temp = pd.DataFrame()
df_temp['xycov'] = (x - xmean) * (y - ymean)
df_temp['xvar'] = (y - xmean)**2

# Calculate beta and alpha
beta = df_temp['xycov'].sum() / df_temp['xvar'].sum()
alpha = ymean - (beta * xmean)

# Integrate user interaction to predict fare amount vs distance
selected_distance = st.slider("DISTANCE IN METERS", 0, 50000, 10000)
y_prediction_from_selected = alpha + beta * selected_distance
st.write('Estimated Fare for Selected Distance = \\$', round(y_prediction_from_selected, 2))

# Plot manual calculation against actual data
ypred = alpha + beta * x
fig7 = plt.figure(figsize=(12, 6))
plt.plot(x, ypred)     # regression line
plt.plot(x, y, 'ro')   # scatter plot showing actual data
plt.plot(selected_distance, y_prediction_from_selected, marker="o", markersize=15, markerfacecolor="blue")
plt.title('Linear Regression Based on Distance')
plt.xlabel('Distance (meters)')
plt.ylabel('Fare Amount ($)')

# Plot the regression line against actual distance vs fare data
st.pyplot(fig7)
#-----------------------------------------------------------------------------------
st.markdown("""
 """, unsafe_allow_html=True)
st.subheader('| ONLINE EXAMPLES REFERENCED')

st.write("https://towardsdatascience.com/introduction-to-linear-regression-in-python-c12a072bedf0")
st.write("https://www.kaggle.com/code/yasserh/uber-fare-prediction-comparing-best-ml-models")
st.write("https://pythonwife.com/pie-chart-with-plotly/")
st.write("https://seaborn.pydata.org/tutorial/regression.html")
st.write("https://github.com/tdenzl/BuLiAn")
st.write("https://discuss.streamlit.io/t/horizontal-separator-line/11788")
st.write("https://stackoverflow.com/questions/31594549/how-to-change-the-figure-size-of-a-seaborn-axes-or-figure-level-plot")


#!/home/zkfr/.local/share/virtualenvs/xf-5EfV3Nly/bin/python
#-*- coding:utf-8 -*-
# @author : MaLei
# @datetime : 2018-11-29 12:05
# @file : dianping.py
# @software : PyCharm

from datetime import datetime as dt
from dianping import *

def create_db():
    cursor, conn = connect_mysql()
    sql = 'CREATE TABLE IF NOT EXISTS food_rank(' \
          'id INT UNSIGNED AUTO_INCREMENT,' \
          'tip VARCHAR(100) NOT NULL,' \
          'tip_id INT(100) NULL,' \
          'classifi VARCHAR(100) NULL,' \
          'rank_num INT(100) NULL,' \
          'shopId VARCHAR(100) NOT NULL,' \
          'shopName VARCHAR(100) NOT NULL,' \
          'mainRegionName VARCHAR(100) NULL,' \
          'taste FLOAT(10) NULL,' \
          'environment FLOAT(10) NULL,' \
          'service FLOAT(10) NULL,' \
          'avgPrice INT(255) NULL,' \
          'city_id INT(100) NULL,' \
          'address VARCHAR(100) NULL,' \
          'update_time DATE NULL,' \
          'PRIMARY KEY (id))ENGINE=InnoDB DEFAULT CHARSET=utf8;'
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()

def insert_db(classifi,class_name):
    cursor, conn = connect_mysql()
    update_time = dt.now().date()

    for i in range(0, len(classifi)):
        # print(classifi[i],class_name[i])
        num = 1
        # 获取分类排行榜的信息
        data = requests.get(url=classifi[i], headers=headers).json()
        shopdata = data['shopBeans']
        cityid = data['cityId']
        try:
            # 保存每个商铺的信息
            for each in shopdata:
                mainCategoryName = each['mainCategoryName']
                shopName = each['shopName']
                branchName = each['branchName']
                if len(branchName) != 0:
                    shopName = shopName + '(' + branchName + ')'
                shopId = each['shopId']
                mainRegionName = each['mainRegionName']
                taste = each['refinedScore1']
                environment = each['refinedScore2']
                service = each['refinedScore3']
                avgPrice = each['avgPrice']
                address = each['address']
                sql = 'INSERT INTO food_rank(tip,tip_id,classifi,rank_num,shopId,shopName,mainRegionName,taste,environment,service,avgPrice,city_id,address,update_time) ' \
                      'VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
                cursor.execute(sql, (class_name[i],
                                     i,
                                     mainCategoryName,
                                     num,
                                     shopId,
                                     shopName,
                                     mainRegionName,
                                     taste,
                                     environment,
                                     service,
                                     avgPrice,
                                     cityid,
                                     address,
                                     update_time))
                conn.commit()
                num += 1
            print('爬取{}排行榜成功'.format(class_name[i]))
        except:
            print('获取商铺信息出错')
    # 去重
    a = 'delete from food_rank where id in (select id from (select id from food_rank where id not in (select min(id) from food_rank group by class,shopName,rank_num)) as temple)'
    cursor.execute(a)
    conn.commit()
    cursor.close()
    conn.close()

def get_rank_info():
    create_db()
    base_url = 'http://www.dianping.com'
    start_url = 'http://www.dianping.com/beijing/food'
    try:
        res = requests.get(start_url, headers=headers).text
        response = etree.HTML(res)
        hot_url = response.xpath('//div[@class="item news_list current"]/a[@class="more"]/@href')
        # print(hot_url)
        classifi_res = requests.get((base_url + hot_url[0]), headers).text
        response = etree.HTML(classifi_res)
        # 第一行标签
        classifi1 = hot_url + response.xpath('//div[@class="box shopRankNav"]/p[1]//a/@href')
        class_name1 = ['热门'] + response.xpath('//div[@class="box shopRankNav"]/p[1]//a/text()')
        # 第二行标签
        classifi2 = response.xpath('//div[@class="box shopRankNav"]/p[2]//a/@href')
        class_name2 = response.xpath('//div[@class="box shopRankNav"]/p[2]//a/text()')
        # 所有标签和名称
        class_name = class_name1 + class_name2
        classifi = classifi1 + classifi2
        ajax_base_url = 'http://www.dianping.com/mylist/ajax/shoprank?rankId='
        for each in classifi[:]:
            classifi.append(ajax_base_url + each.split('=')[1])
            classifi.remove(each)
        insert_db(classifi,class_name)
    except:
        print('爬取榜单出错')

get_rank_info()