#!/usr/bin/env python3

import re
import sys

inputfilename = sys.argv[1]
outputfilename = inputfilename.rsplit('.', 1)[0] + '.hack'
are = re.compile(r'^\s*@([a-zA-Z0-9_.$]+)')

# first part allows whitespace, second part allows 1-3 letters(the dest field),
# after that an = sign, the comp field, the rest allows for a comment
cre = re.compile(r'^\s*(?:(\w{0,3})=)?([0-9A-Z+\|&\-!]{1,3})(?:;(\w{0,3}))?')
lre = re.compile(r'^\s*\((.*)\)')
adre = re.compile(r'^\d*$')

addressymboltable = {
    'SP': 0,
    'LCL': 1,
    'ARG': 2,
    'THIS': 3,
    'THAT': 4,
    'R0': 0,
    'R1': 1,
    'R2': 2,
    'R3': 3,
    'R4': 4,
    'R5': 5,
    'R6': 6,
    'R7': 7,
    'R8': 8,
    'R9': 9,
    'R10': 10,
    'R11': 11,
    'R12': 12,
    'R13': 13,
    'R14': 14,
    'R15': 15,
    'SCREEN': 16384,
    'KBD': 24676
}
compdict = {
    '0': '0101010',
    '1': '0111111',
    '-1': '0111010',
    'D': '0001100',
    'A': '0110000',
    'M': '1110000',
    '!D': '1001101',
    '!A': '0110001',
    '!M': '1110001',
    '-D': '0001111',
    '-A': '0110011',
    '-M': '1110011',
    'D+1': '0011111',
    'A+1': '0110111',
    'M+1': '1110111',
    'D-1': '0001110',
    'A-1': '0110010',
    'M-1': '1110010',
    'D+A': '0000010',
    'D+M': '1000010',
    'D-A': '0010011',
    'D-M': '1010011',
    'A-D': '0000111',
    'M-D': '1000111',
    'D&A': '0000000',
    'D&M': '1000000',
    'D|A': '0010101',
    'D|M': '1010101'
}
destdict = {
    None: '000',
    'M': '001',
    'D': '010',
    'MD': '011',
    'A': '100',
    'AM': '101',
    'AD': '110',
    'AMD': '111'
}
jumpdict = {
    None: '000',
    'JGT': '001',
    'JEQ': '010',
    'JGE': '011',
    'JLT': '100',
    'JNE': '101',
    'JLE': '110',
    'JMP': '111'
}

undefinedsymboltable = []
labelsymboltable = {}
nextvar = 16

def parser(line):
    '''Encapsulates access to teh input code. Reads an assembly language
    command, parses it, and provides convenient access to teh command's
    components (fields and symbols). In addition, skips all white space and
    comments.'''

    global undefinedsymboltable
    global addressymboltable
    global nextvar
    global labelsymboltable

    # differentiates between a, l and c instructions
    # if c instruction, find comp, dest and jump
    m = cre.match(line)
    if m:
        comp = m.group(2)
        dest = m.group(1)
        jump = m.group(3)
        output = '111'

        output += compdict[comp]
        output += destdict[dest]
        output += jumpdict[jump]
        output += '\n'
        return output
    m = are.match(line)
    if m:
        address = m.group(1)
        if adre.match(address):
            output = '0'
            output += format(int(address), 'b')
            filler = ''
            for i in range(16-len(output)):
                filler += '0'
            filler += output
            filler += '\n'
            return filler
        elif address not in undefinedsymboltable:
            if address not in labelsymboltable:
                if address not in addressymboltable:
                    undefinedsymboltable.append(address)
        return address
    m = lre.match(line)
    if m:
        symbol = m.group(1)
        if symbol not in labelsymboltable:
            labelsymboltable[symbol] = linecounter
        if symbol in undefinedsymboltable:
            undefinedsymboltable.remove(symbol)
        return 'l'
    else:
        return 'w'

with open(inputfilename, 'r') as fileToTranslate:
    cmdlist = []
    linecounter = 0
    for line in fileToTranslate:
        parsout = parser(line)
        if parsout != 'w' and parsout != 'l':
            cmdlist.append(parsout)
            linecounter += 1
with open(outputfilename, 'w') as outputFile:
    for symbol in undefinedsymboltable:
        addressymboltable[symbol] = nextvar
        nextvar += 1
    for cmd in cmdlist:
        if cmd in addressymboltable:
            output = format(addressymboltable[cmd], 'b')
            filler = ''
            for i in range(16-len(output)):
                filler += '0'
            filler += output
            filler += '\n'
            outputFile.write(filler)
        elif cmd in labelsymboltable:
            output = format(labelsymboltable[cmd], 'b')
            filler = ''
            for i in range(16-len(output)):
                filler += '0'
            filler += output
            filler += '\n'
            outputFile.write(filler)
        else:
            outputFile.write(cmd)


import random
import json
import requests
import asyncio

async def func():
	while True:
		temp = random.randint(18,25)
		wet = random.randint(40,60)
		print("temperature: ", temp, "℃")
		print("humidity: ", wet, "%")
		data = {
			'temperature' : temp,
			'humidity' : wet
		}
		url = 'http://140.116.82.100:1880/sensor'

		requests.post(url, data=json.dumps(data))
		print('sent')
		await asyncio.sleep(10)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(func())
print('close')
loop.close()


from fastapi import Depends, APIRouter
from starlette import status

from src.infrastructure.controllers.shot_controller import ShotController

router = APIRouter(prefix='/shot')

@router.post(
    '/{laser_id}/{target_id}',
    summary='Give nearly _target and nearest _laser',
    status_code=status.HTTP_200_OK,
)
async def shot(laser_id: str, target_id: str, shot_controller: ShotController = Depends()):
    return shot_controller.shot(laser_id, target_id)


#! /usr/bin/env python
#
# Requires Python 3
# BASIC USAGE:
#   ./file_mapper_script.py <JSON-file>
#

#import the different python libraries
import argparse
import json
import os
import shutil
import sys

#gives a description over the purpose of the program
PROG = 'File Mapper'
VERSION = '1.4.0'

program_desc = """%(prog)s v%(ver)s:
Script to make a new directory and map files from a source directory. Files
can be copied or moved, or the script can make symbolic links.
""" % {'prog': PROG, 'ver': VERSION}

def get_parser():
    #sets a variable equal to the argparse function which lets a user input
    #choices
    parser = argparse.ArgumentParser(description=program_desc, prog=PROG)

    #gives the absolute path to the json file
    parser.add_argument('jsonpath', nargs=1,
                    help="""Absolute path to the required JSON.""")

    #gives the choices as an argument that the user can pass through
    #to manipulate the path of the json file
    parser.add_argument('-a', '--action', dest='action', required=False, default='copy',
                        choices = ['copy', 'move', 'symlink', 'move+symlink'],
                        help="""Choose between moving, copying, or symlinking between
                        the source and destination. Default: copy.""")

    parser.add_argument('-o', '--overwrite', dest='overwrite', required=False,
                        default=False, action = 'store_true',
                        help="""This allows new files to be created whether or not
                        they already exist.
                        If a path already exists, and this flag was not provided, the
                        console will display a message that the path already exists
                        and the file will not be copied.
                        If a path already exists and this flag was used, the console
                        will display a message that the file was overwritten.
                        """)

    parser.add_argument('-s', '--skip-errors', dest='skip_errors',
                        required=False, default=False, action= 'store_true',
                        help="""This skips over the errors in a JSON file so
                        that the other keys/values can be properly read.
                        """)

    parser.add_argument('-sp', '--sourcepath', nargs=1, default=None, required=False,
                        help="""Provides the absolute path to the source of the file
                        being copied/moved/symlinked.
                        """)

    parser.add_argument('-dp', '--destpath', nargs=1, default=None, required=False,
                        help="""Provides the absolute path to the destination of the
                        file being copied/moved/symlinked.
                        """)

    parser.add_argument('-t', '--template', nargs=1, default=None, required=False,
                        help="""A no-spaces-allowed, comma-separated
                        list of template fill-ins to replace fields in your JSON of
                        the format: 'TEMPLATE1=REPLACEMENT1,TEMPLATE2=REPLACEMENT2,...'.
                        For example let's say you want to replace a {SUBJECT} and
                        {SESSION} template variable you would use:
                        -t 'SUBJECT=sub-01,SESSION=ses-baseline'
                        """)

    parser.add_argument('-td', '--testdebug', dest='testdebug', required=False,
                        default=False, action='store_true',
                        help="""Display what the code would do, using the other
                        options provided, without performing the actions.
                        """)

    parser.add_argument('-vb', '--verbose', dest='verbose', required=False,
                        default=False, action='store_true',
                        help="""Without this option, the program will run without
                        displaying any messages to the console, under the philosophy
                        'Succeed silently, fail loudly.'
                        """)

    parser.add_argument('-relsym', '--relative-symlink', dest='relative_symlink',
                        required=False, default=False, action='store_true',
                        help="""Allows user to chose whether or not the symlink
                        being created is a relative path so that root
                        directories can be moved without the link breaking.
                        """)

    parser.add_argument('-sc', '--sidecars', dest='sidecars',
                        required=False, default=False, action='store_true',
                        help="""Also copy/move/symlink the corresponding
                        json sidecars""")

    return parser

def map_sidecars(source, destination):
    ''' Return name of json sidecars to be copied/symlinked etc

    Args:
        source (str): full path to source file
        destination (str): full path to destination
    Returns:
        json_src (str): full path to source json file
        json_dest (str): fill path to destination json file
    '''

    replace = [".nii.gz", ".nii"]

    for repl in replace:
        if source.endswith(repl):
            json_src = source.replace(repl, ".json")
            json_dest = destination.replace(repl, ".json")
            break

    return json_src, json_dest

#big function that parses the entire JSON file
def parse_data(contents, verbose=False, testdebug=False):
    data = {}
    for source, destination in contents.items():
        if '{#}' in source and '{#}' in destination:
            for i in range(100):
                num_zeropad_1 = '{:01d}'.format(i)
                num_zeropad_2 = '{:02d}'.format(i)
                num_zeropad_3 = '{:03d}'.format(i)
                zeropads = list(set([num_zeropad_1, num_zeropad_2, num_zeropad_3]))
                for zeropad in zeropads:
                    source_temp = source.replace('{#}', zeropad)
                    destination_temp = destination.replace('{#}', zeropad)
                    data[source_temp] = destination_temp
        else:
            data[source] = destination

    #Checks for source and destination arguments in the JSON
    non_specials_list = []
    for element in data.keys():
        if element not in ['SOURCE', 'DESTINATION']:
            non_specials_list.append(element)

    if args.template != None:
        template_dict = parse_template(args.template[0])

    for key in non_specials_list:
        #If sourcepath exists the append it to the destination value and overwrite
        if args.sourcepath != None:
            if verbose:
                print("A sourcepath argument exists")
            source = os.path.join(args.sourcepath[0], key)
            if 'SOURCE' in data:
                if verbose:
                    print('Optional SOURCE argument: '+ args.sourcepath[0] +
                    ' overrules source: ' + str(data['SOURCE']))
        elif 'SOURCE' in data:
            if verbose:
                print("Source already exists in json data")
            source = os.path.join(data['SOURCE'],key)
        else:
            if verbose:
                print("No source provided. Defaulting to key from json data")
            source = key
        #If the destination path argument exists then append to the key and overwrites the pre-existing argument
        if args.destpath != None:
            if verbose:
                print("A destination path argument exists")
            destination = os.path.join(args.destpath[0], data[key])
            if 'DESTINATION' in data:
                if verbose:
                    print('Optional DESTINATION argument: '+ args.destpath[0] +
                    ' overrules destination: ' + str(data['DESTINATION']))
        #If the destination argument exists then append it to the key's value
        elif "DESTINATION" in data:
            if verbose:
                print("Destination already exists in json data")
            destination = os.path.join(data['DESTINATION'], data[key])
        else:
            #If neither exists then use pre-existing values
            if verbose:
                print("DESTINATION not provided, using pre-existing values in JSON")
            destination = data[key]

        #Replace any template values in the case of an input template argument
        if args.template != None:
            if '{' in source and '}' in source:
                for lookup in template_dict:
                    source = source.replace('{' + lookup + '}', template_dict[lookup])
            if '{' in destination and '}' in destination:
                for lookup in template_dict:
                    destination = destination.replace('{' + lookup + '}', template_dict[lookup])

        #check if the path in the json data actually exists
        if os.path.exists(source) and os.path.isfile(source):
            dirname = os.path.dirname(destination)
            # make a directory based on the key in the json file
            if os.path.isfile(destination):
                if not args.overwrite:
                    if verbose or testdebug:
                        print("Destination file already exists: " + str(destination))
                elif args.overwrite:
                    do_action(source, destination, args.action,
                    overwrite=args.overwrite, testdebug=args.testdebug, relsym=args.relative_symlink)
                    if args.sidecars:
                        json_src, json_dest = map_sidecars(source, destination)
                        do_action(json_src, json_dest, args.action,
                                  testdebug=args.testdebug,
                                  relsym=args.relative_symlink)
                    if verbose:
                        print("File has been overwritten")
                elif os.path.exists(dirname):
                    if verbose:
                        print("Path already exists: " + str(dirname))
            elif os.path.isdir(os.path.dirname(destination)):
                do_action(source, destination, args.action, testdebug=args.testdebug, relsym=args.relative_symlink)
                if args.sidecars:
                    json_src, json_dest = map_sidecars(source, destination)
                    do_action(json_src, json_dest, args.action,
                              testdebug=args.testdebug,
                              relsym=args.relative_symlink)
            else:
                os.makedirs( dirname )
                if verbose:
                    print("Path has been made: " + str(dirname))
                do_action(source, destination, args.action, testdebug=args.testdebug, relsym=args.relative_symlink)
                if args.sidecars:
                    json_src, json_dest = map_sidecars(source, destination)
                    do_action(json_src, json_dest, args.action,
                              testdebug=args.testdebug,
                              relsym=args.relative_symlink)

#Decides what to do based on the action chosen by the user
def do_action(src, dest, action, overwrite=False, testdebug=False, relsym=False):
    if relsym:
        common = os.path.commonpath([os.path.abspath(p) for p in [src,dest]])
        src_from_common = os.path.relpath(src,common)
        dest_from_common = os.path.relpath(dest,common)
        rel_src_from_dest = os.sep.join(['..' for _ in dest_from_common.split(os.sep)[:-1]] + [src_from_common])
        rel_dest_from_src = os.sep.join(['..' for _ in src_from_common.split(os.sep)[:-1]] + [dest_from_common])

    if overwrite:
        overwrite_string = 'overwrite '
    else:
        overwrite_string = ''
        #If testdebug mode is present then a string will be constructed based on the arguments provided by the user
        if testdebug:
            print(overwrite_string + action + ': ' + src + ' -> ' + str(dest))
        else:
            #copies the file from one directory to another
            if action == "copy":
                if overwrite:
                    os.remove(dest)
                shutil.copy(src, dest)
            #moves the file from one directory to another
            elif action == "move":
                if overwrite:
                    os.remove(dest)
                shutil.move(src, dest)
            #symlinks the file from one directory to another
            elif action == "symlink":
                if overwrite:
                    os.unlink(dest)
                if relsym:
                    os.symlink(rel_src_from_dest, dest)
                else:
                    os.symlink(src, dest)
            #moves the file from one directory to another AND symlinks it back to its source
            elif action == "move+symlink":
                if overwrite:
                    os.remove(dest)
                shutil.move(src, dest)
                if relsym:
                    os.symlink(rel_dest_from_src, src)
                else:
                    os.symlink(dest, src)
            elif action=="s3cmd":
                if overwrite:
                    os.remove(dest)
                cmd="s3cmd sync "+src+" "+dest
                os.system(cmd)
            else:
                sys.exit()

# data should be of the format of json
def json_validator(filename, skip_errors=False):
#Try to open an load the json file and test if it comes up with any errors
    try:
        with open(filename,'r') as f:
            data = json.load(f)
    except KeyError as error:
        print("invalid key in JSON")
        #if the json comes up with any errors, the program will exit
        if not skip_errors:
            sys.exit()
    #If everything works, the json data will be returned
    except ValueError as error:
        print("invalid value in JSON")
        if not skip_errors:
            sys.exit()
    parse_data(data, args.verbose)

    return data

# check and parse the template input argument
def parse_template(template_str, testdebug=False, verbose=False):
    template_dict = {}
    comma_count = len([character for character in template_str if character == ','])
    equal_count = len([character for character in template_str if character == '='])

    if equal_count == (comma_count + 1):
        pairs = template_str.split(',')
        for pair in pairs:
            key,value = pair.split('=')
            template_dict[key] = value
    else:
        print("There is not an even split of commas and equal signs within this template input: " + template_str)
        print("The --template argument takes its argument in the format: 'A=B,C=D,E=F'" + template_str)
        print("Exiting.")
        sys.exit()

    return template_dict

#defines variables to hold the argparse information so that
#they can be called later in the for loop
parser = get_parser()
args = parser.parse_args()

### START HERE ###
json_file = args.jsonpath[0]
json_validator(json_file, args.skip_errors)


from flask import Flask, Blueprint, render_template, request, redirect
from werkzeug.utils import secure_filename
import os

from DB import db_init
from DB.donations import *
from DB.users import *

Donation_creation_page = Blueprint('DonationCreation', __name__, template_folder='../templates')
UPLOAD_FOLDER = 'uploads'
STATIC_FOLDER = 'static_files'
ALLOWED_EXTENSIONS = {'jpg', 'png', 'jpeg'}
IMAGE = ""

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['STATIC_FOLDER'] = STATIC_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[-1].lower() in ALLOWED_EXTENSIONS

@Donation_creation_page.route('/newDonation', methods=['POST', 'GET'])
def index():
    if 'email' not in session:
        return redirect("/Login")

    return render_template("DonationCreation.html")

@Donation_creation_page.route('/createDonation', methods=['POST', 'GET'])
def createDonation():
    if request.method == 'POST':
        description = request.form.get("Description")
        quantity = request.form.get("Quantity")
        kosher = request.form.get("Kosher")
        meat = request.form.get("Meat")
        dairy = request.form.get("Dairy")
        vegan = request.form.get("Vegan")
        gluten = request.form.get("GlutenFree")
        # Checking if images were uploaded
        if 'donation_images' not in session:
            images = ["../static/images/BurgerDonation.png"]
        else:
            images = session['donation_images']

        labels = ""
        if kosher is not None:
            labels += "Kosher, "
            kosher = True
        else:
            kosher = False
        if meat is not None:
            labels += "Meat, "
            meat = True
        else:
            meat = False
        if dairy is not None:
            labels += "Dairy, "
            dairy = True
        else:
            dairy = False
        if vegan is not None:
            labels += "Vegan, "
            vegan = True
        else:
            vegan = False
        if gluten is not None:
            labels += "Gluten free"
            gluten = True
        else:
            gluten = False

        if labels != "" and labels[len(labels) - 1] == " ":
            labels = labels[:len(labels) - 2]

        try:
            images_str = list_to_string(images)
            user = get_user(session['email'])
            email = user.email
            add_new_donation(user_email=email, recipients_amount=quantity, is_predictable=False,
                             description=description, picture=images_str, start_time=None,
                             end_time=None, is_open=True, is_in_process=False,
                             is_kosher=kosher, is_vegan=vegan, is_meat=meat, is_dairy=dairy, is_gluten_free=gluten)

        except db_init.EmailExistsInDB:
            render_template("Error.html")

        return redirect('/')
    return redirect('/')

@Donation_creation_page.route('/addImage', methods=['POST', 'GET'])
def addImage():
    if 'email' not in session:
        return redirect("/Login")
    # Clean images array
    images = []
    if 'files[]' in request.files:
        files = request.files.getlist('files[]')
        for file in files:
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename != '':
                upload_folder = r'static/donations_pictures'
                if file and allowed_file(file.filename):
                    filename = secure_filename(file.filename)
                    img_path = "%s/%s" % (upload_folder, filename)
                    c = 0
                    while os.path.exists(img_path):
                        img_path = "%s_%s" % (img_path, c)
                        c += 1
                    abs_path = os.path.abspath(img_path)
                    file.save(abs_path)
                    img_path = "../" + img_path
                    images.append(img_path)

        session['donation_images'] = images
        return render_template("DonationCreation.html", images=images)

    return render_template("DonationCreation.html", images="../static/images/BurgerDonation.png")

def list_to_string(list):
    return_str = ""
    for i in range(len(list)):
        if i == len(list):
            return_str += list[i]
        else:
            return_str += list[i] + ","
    return return_str


import numpy as np
import random as rnd
from tkinter import Tk
import time as tmr

class Direction:
    """
    This can serve as our action space reference
    """
    Up = -1
    Down = 1
    Nothing = 0

class Marker:
    AGENT = 1
    BEAM = 2
    EMPTY = 0
    LASER_HIT = 3

class Laser:
    """
    Represents a laser beam on the star field
    """
    def __init__(self, init_coord):
        """
        :param init_row: this represents the start row of where a laser will be generated
        #
        """
        self.coord = init_coord # This keeps track of the row, col of the laser beam

class Environment:
    """
    This creates the main game environment
    """
    def __init__(self, p_size, int_max_lasers=3):
        """
        :param p_size: A tuple indicating size of the star field, typically (10, 10)
        :param int_max_lasers: how many lasers can appear on the field.
        """
        self.StarField = np.zeros(p_size, dtype=int)
        self.laser_array = []  # Keeps track of all the lasers in the field. These must be laser objects
        self.agent_position = ()  # Keeps track of agent (x, y)
        self.max_lasers = int_max_lasers
        self.started = False

    def spawn_laser(self):
        """
        Spawn a laser at row
        :param init_row: row where the laser will be
        :return: void
        """

        # Add a laser to the array providing it doesn't exceed the max
        if len(self.laser_array) < self.max_lasers:
            # Spawn a laser and add to the array
            mypos = self.get_random_laser_position()

            # Append only if the spot is empty
            if self.StarField[(mypos, self.StarField.shape[1] - 1)] == Marker.EMPTY:
                new_laser = Laser(mypos)
                new_laser.coord = (mypos, self.StarField.shape[1] - 1) # set the coordinate
                self.laser_array.append(new_laser)

    def get_random_laser_position(self):
        """
        Returns an integer indicating the row of the laser
        :return: int
        """
        return rnd.randint(0, self.StarField.shape[0] - 1)

    def spawn_agent(self):
        """
        randomly places agent along (row, 1) at the beginning of a game
        :return: void
        """

    def animate(self):
        """
        This goes through the laser array and animates each laser step by step, and will also
        eliminate any laser
        :return:
        """

        # spawn a laser
        self.spawn_laser()

        # First we'll place the laser in the star field
        if len(self.laser_array) > 0:
            # the laser array has at least one or more lasers in it.
            for idx, lsr in enumerate(self.laser_array):
                # Place a laser
                row, col = lsr.coord
                if col > 0:
                    self.StarField[row, col] = Marker.BEAM  # Place the beam in the matrix
                elif col == 0:
                    # delete the laser
                    self.laser_array.remove(lsr)
                    self.StarField[row, col] = Marker.EMPTY  # Clear out the beam

            # next we'll animate the lasers to the left one spot
            for index_in, lsr in enumerate(self.laser_array):
                row, col = lsr.coord
                if col > 0:
                    lsr.coord = (row, col - 1)
                    r, c = lsr.coord
                    self.StarField[r, c] = Marker.BEAM
                    self.StarField[row, col] = Marker.EMPTY # update the previous

    def check_contact(self):
        """
        This checks if a laser makes contact with the agent, garnering a negative reward,
        If it does, the contacting laser should be despawned
        :return:
        """

    def start(self):
        """
        This starts the environment and the loop
        """

def testing():
    r = Environment((10, 10), 10)
    print(r.StarField)

    while True:
        print(r.StarField)
        r.animate()
        tmr.sleep(1)

testing()


import numpy as np
import matplotlib.pyplot as plt
import collections
from matplotlib.patches import Rectangle
from PIL import Image
import glob
import SimpleITK as sitk

config_paths = {
    "luna16":"../../luna16/LUNA16/",
    "segment":"../../luna16/seg-lungs-LUNA16/",
    "annotations":"../../luna16/annotations.csv",
    "candidates":"../../luna16/candidates.csv",
    "slide_v1":"../center-coord-chunk",
    "slide_v2":"../center-coord-chunk-v2",
}

IrcTuple = collections.namedtuple('IrcTuple', ['index', 'row', 'col'])
XyzTuple = collections.namedtuple('XyzTuple', ['x', 'y', 'z'])

def irc2xyz(coord_irc, origin_xyz, vxSize_xyz, direction_a):
    cri_a = np.array(coord_irc)[::-1]
    origin_a = np.array(origin_xyz)
    vxSize_a = np.array(vxSize_xyz)
    coords_xyz = (direction_a @ (cri_a * vxSize_a)) + origin_a
    # coords_xyz = (direction_a @ (idx * vxSize_a)) + origin_a
    return XyzTuple(*coords_xyz)

def xyz2irc(coord_xyz, origin_xyz, vxSize_xyz, direction_a):
    origin_a = np.array(origin_xyz)
    vxSize_a = np.array(vxSize_xyz)
    coord_a = np.array(coord_xyz)
    cri_a = ((coord_a - origin_a) @ np.linalg.inv(direction_a)) / vxSize_a
    cri_a = np.round(cri_a)
    return IrcTuple(int(cri_a[2]), int(cri_a[1]), int(cri_a[0]))

def plot_ct(image, index):
    """
    image: np.array of iamge
    index: list index have mask value
    """
    num_fig = int(np.ceil(np.sqrt(len(index))))

    fig, axs = plt.subplots(num_fig, num_fig, figsize=(20,14))
    slide = 0
    for x in range(num_fig):
        for y in range(num_fig):
            try:
                axs[x, y].imshow(image[index[slide]])
                axs[x, y].set_title(index[slide])
                slide += 1
            except:
                pass

    plt.show()

def plot_ct_scan_bbox(image, index, center_irc, diamiter):
    """
    image: np.array of iamge
    index: list index have mask value
    """
    num_fig = int(np.ceil(np.sqrt(len(index))))

    fig, axs = plt.subplots(num_fig, num_fig, figsize=(20,14))

    slide = 0
    for x in range(num_fig):
        for y in range(num_fig):
            try:
                axs[x, y].imshow(image[index[slide]])
                axs[x, y].set_title(index[slide])
                axs[x, y].gca().add_patch(Rectangle((center_irc[2], center_irc[1]), diamiter, diamiter,
                    edgecolor='red',
                    facecolor='none',
                    lw=4))

                slide += 1
            except:
                pass

    plt.show()

def get_uids(subsets = list(range(10))):
    result = []

    for subset in subsets:
        files = glob.glob(config_paths["luna16"] + f"subset{subset}/*.mhd")

        for f in files:
            result.append(f.split("\\")[-1][:-4])

    return result

def read_sitk(path):
    ct_mhd = sitk.ReadImage(path)
    ct_a = np.array(sitk.GetArrayFromImage(ct_mhd), dtype=np.float32)

    origin = np.array(ct_mhd.GetOrigin())[::-1]
    spacing= np.array(ct_mhd.GetSpacing())[::-1]
    direction = np.array(ct_mhd.GetDirection())[::-1]

    return ct_a, origin, spacing, direction


#!/usr/bin/env python

import rospy
import math
import matplotlib.pyplot as plt
import geometry_msgs.msg
from room_categorization.msg import bestObjectInfo
from semantic_mapping.msg import SemanticObjects
from room_categorization.msg import debugInfo
from semantic_mapping.msg import SemanticRoom
import sys

class objectsInFOV(object):

    def __init__(self):

        # Variables de control de codigo
        self._debug = True
        self._newObjectFOVList = False
        self._publishRate = 10

        # Parametros del algoritmo de percepcion activa
        self._categoriaMinima = 2
        self._angle_offset = 0

        # Publishers
        self._pub = rospy.Publisher('bestObjectInfo', bestObjectInfo, queue_size=10)

        if self._debug:
            self._pubDebug = rospy.Publisher('consoleDebugInfo', debugInfo, queue_size=10)

        # Subscribers
        rospy.Subscriber('semantic_mapping/object_in_room', SemanticObjects, self._newObjectList_callback)
        rospy.Subscriber("poseRobot", geometry_msgs.msg.Vector3, self._newRobotPose_callback)
        rospy.Subscriber("semantic_mapping/room_scores", SemanticRoom, self._newRoom_callback)

        # Parametros de los sensores
        self._nCameras = 4              # Numero de camaras
        self._height = 240              # Alto de la imagen de una camara
        self._width = 240               # Ancho de la imagen de una camara
        self._FOVcamera = 180           # Campo de vision horizontal
        self._FOVcameraVertical = 58    # Campo de vision vertical
        self._distZcamera = 1.045       # Distancia entre el suelo y la camara

        # Informacion de la localizacion del robot
        self._poseRobot = [1,2,3,80]    # Pose del robot (x,y,z,orientacion(grados))
        self._currentRoom = 'NoValid'   # Habitacion actual del robot

        # Informacion del FOV del robot
        self._angmax = None             # Angulo maximo del FOV horizontal del robot
        self._angmin = None             # Angulo minimo del FOV horizontal del robot
        self._angminc = None            # Correccion del FOV horizontal

        # Constantes de interes
        self._deg2rad = math.pi/180     # Paso de grados a radianes
        self._rad2deg = 180/math.pi     # Paso de radianes a grados
        self._angle2px = self._nCameras*self._width/self._FOVcamera
        self._px2angle = self._FOVcamera/(self._nCameras*self._width)

        # Informacion del entorno
        self._mapa = {}                 # Mapa de los objetos en la habitacion actual
        self.objIn = {}                 # Objetos dentro del FOV del robot

        # Variables de control
        self._firstRoomExploration = False
        self._current_milli_time = lambda: int(round(time.time()*1000))

    def _getFOV(self):
        # Obtengo el angulo minimo del FOV
        self._angmin = (self._poseRobot[3] - self._FOVcamera / 2 + 22.5)*self._deg2rad  # Angulo minimo del FOV

        # Proceso el FOV para que siempre se cumpla que angmax >= angmin. Para ello, lo que se hace es
        # girar todos los angulos para que angmin valga 0 grados, de tal forma que se cumple siempre la condicion
        # propuesta.
        self._angmin = self.angle_range0to2pi(self._angmin) # Angmin entre 0 y 2pi
        self._angminc = 2*math.pi - self._angmin # Correccion necesaria para situar angmin en 0 grados

        # Angulo del FOV corregido
        self._angmax = self._FOVcamera*self._deg2rad                        # Angmax = FOV
        self._angmin = self.angle_range0to2pi(self._angmin + self._angminc) # Angmin = 0

    def _createList_objectsInFOV(self):
        self.objIn.clear()

        for obj in self._mapa:
            # Compruebo si el objeto esta en la misma hab que el robot
            if ((self._mapa[obj][0] == self._currentRoom) and (self._mapa[obj][2] >= self._categoriaMinima)):
                [isIn, angle] = self._checker_objectinFOV(obj)
                if(isIn == True):
                    self.objIn[obj] = self._mapa[obj] + (angle,)

        self._newObjectFOVList = True

    def _checker_objectinFOV(self, objeto):
        # Comprobacion de si un objeto esta dentro del campo de vision del robot o no.
        angle = math.atan2((self._mapa[objeto][5]-self._poseRobot[1]),(self._mapa[objeto][4]-self._poseRobot[0]))
        angle = self.angle_range0to2pi(angle + self._angminc + 30*self._deg2rad)
        if (angle >= (self._angmin + self._angle_offset*self._deg2rad) and angle <= (self._angmax - self._angle_offset*self._deg2rad)):
            # Objeto dentro del campo de vision horizontal... pero, esta dentro del campo de vision vertical?
            distObjetoRobot = math.sqrt((self._poseRobot[0]-self._mapa[objeto][4])**2 + (self._poseRobot[0]-self._mapa[objeto][5])**2)
            hZ = distObjetoRobot*math.tan(self._FOVcameraVertical/2*self._deg2rad)
            hZmin = self._distZcamera - hZ
            hZmax = self._distZcamera + hZ
            if(self._mapa[objeto][6] <= hZmax and self._mapa[objeto][6] >= hZmin):
                # Esta dentro del campo de vision del robot
                return True, angle
            else:
                return False, angle
        else:
            return False, angle

    def run(self):

        # Variables de control
        exploration = False
        listaObjIn = []
        rate = rospy.Rate(self._publishRate)

        # Constantes
        #minPx = self._width/2
        #maxPx = self._nCameras*self._width - minPx
        minPx = 0
        maxPx = self._nCameras*self._width

        # Informacion sobre el mejor objeto
        bestObj = None

        while not rospy.is_shutdown():

            if (bool(self.objIn) and self._newObjectFOVList and not(self._firstRoomExploration)):

                exploration = False
                listaObjIn = self.objIn.keys()
                bestObj = sorted(self.objIn.items(), key = lambda x: x[1][2] + x[1][3], reverse = True)
                bestObj = bestObj[0]

                px = int(round((minPx - maxPx) * bestObj[1][7] / (self._angmax - self._angmin) + maxPx))

                msg = bestObjectInfo(bestObj[1][2], px)

                if self._debug:
                    debug_msg = debugInfo(self._currentRoom, exploration, bestObj[1][1], bestObj[1][0], geometry_msgs.msg.Vector3(bestObj[1][4], bestObj[1][5], bestObj[1][6]), px, listaObjIn)

            elif (not(bool(self.objIn)) or self._firstRoomExploration):

                exploration = True

                msg = bestObjectInfo(0, 0)

                if self._firstRoomExploration:
                    msg = bestObjectInfo(-1, 0)
                    self._firstRoomExploration = False

                if self._debug:
                    debug_msg = debugInfo(self._currentRoom, exploration, 'None', 'None', geometry_msgs.msg.Vector3(), 0, [])

            self._pub.publish(msg)

            if self._debug:
                self._pubDebug.publish(debug_msg)

            rate.sleep()

    def _newRobotPose_callback(self, data):
        self._poseRobot = [data.x,data.y,0.0,self.angle_range0to2pi(data.z)*self._rad2deg]
        self._getFOV()
        self._createList_objectsInFOV()

    def _newRoom_callback(self, data):
        if data.id != self._currentRoom:
            self._currentRoom = data.id
            #self._firstRoomExploration = True

    def _newObjectList_callback(self, data):
        self._mapa.clear()
        for obj in data.semanticObjects:
            self._mapa[obj.id] = (obj.idRoom, obj.type)
            # Objetos que dan gran informacion sobre la habitacion. Categoria 4
            if(obj.type == 'microwave' or obj.type == 'oven' or obj.type == 'toaster' or obj.type == 'bed' or obj.type == 'toilet'):
                self._mapa[obj.id] = self._mapa[obj.id] + (4,)
            # Objetos que dan algo de informacion sobre la habitacion. Categoria 3
            elif(obj.type == 'dining table' or obj.type == 'sink'):
                self._mapa[obj.id] = self._mapa[obj.id] + (3,)
            # Objetos que dan poca informacion sobre la habitacion. Categoria 2
            elif(obj.type == 'tv' or obj.type == 'bench' or obj.type == 'couch'):
                self._mapa[obj.id] = self._mapa[obj.id] + (2,)
            # Objetos que dan muy poca informacion sobre la habitacion. Categoria 1
            elif(obj.type == 'chair'):
                self._mapa[obj.id] = self._mapa[obj.id] + (1,)
            else:
                self._mapa[obj.id] = self._mapa[obj.id] + (0,)
            self._mapa[obj.id] = self._mapa[obj.id] + (obj.score, obj.pose.position.x, obj.pose.position.z, obj.pose.position.y,)
            #if(self._currentRoom != obj.idRoom):
            #    self._currentRoom = obj.idRoom
        self._getFOV()
        self._createList_objectsInFOV()

    @staticmethod
    def angle_range0to2pi(angle):
        while(angle >= 2*math.pi or angle < 0):
            if(angle >= 2*math.pi):
                angle = angle - 2*math.pi
            elif(angle < 0):
                angle = 2*math.pi + angle
        return angle

def main():
    rospy.init_node('objectsInFOV', anonymous=True)
    node = objectsInFOV()
    node.run()

if __name__ == '__main__':
    try:
        main()
    except rospy.ROSInterruptException:
        pass


# Independent Alleles

from scipy.special import binom

with open("in.txt", "r") as infile, open("out.txt", "w") as outfile:
	line = infile.readline().strip("\n")
	k, N = map(int, line.split())

	total = 2**k

	prob = sum(binom(total, i) * 0.25**i * 0.75**(total-i) for i in range(N, total+1))

	outfile.write(str(round(prob, 3)))


class Solution:
    def largestDivisibleSubset(self, nums):
        if(len(nums)==1):
            return nums
        nums.sort()
        dp=[1]*(len(nums))
        index=0
        t=[i for i in range(len(nums))]
        for i in range(1,len(nums)):
            for prev in range(i):
                if((nums[i]%nums[prev])==0):
                    if(dp[i]<dp[prev]+1):
                        dp[i]=dp[prev]+1
                        t[i]=prev
        i=dp.index(max(dp))
        # print(t,dp)
        ans=[]
        ans.append(nums[i])
        while(t[i]!=i):
            i=t[i]
            ans.append(nums[i])
            # print(i)
        return ans
#intution similar longest incresing sub but instaed we use arr[i]%arr[prev]==0 and printing simiar to lis


from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.urls import reverse

import string, random

# give each Game a random string label which will be used as the url
def get_random_label():
    while True:
        new_label = ''.join(random.choices(
            string.ascii_lowercase + string.digits,
            k=12
        ))
        if not Game.objects.filter(label=new_label).exists():
            return new_label

# Create your models here.
class Game(models.Model):
    STATUS_OPTIONS = (
        ('O', 'Ongoing'),
        ('W', 'White Victory'),
        ('B', 'Black Victory')
    )
    white_player = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="white_games")
    black_player = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        blank=True, null=True,
        related_name="black_games"
    )
    status = models.CharField(max_length=1, choices=STATUS_OPTIONS, default='O')
    history = models.CharField(max_length=240, default='')
    label = models.CharField(max_length=12, unique=True, default=get_random_label)

    def add_move(self, move):
        self.history += f"x{move}"
        self.save()

    def end_game(self, winner):
        self.status = winner
        self.save()

    # parse the game's history into a list of moves
    # since each move in the history will start with 'x', the list will start
    # with an empty value, so splice it out
    @property
    def parsed_history(self):
        return self.history.split('x')[1:]

    # shorthand to check if a user is a player in a game
    @property
    def players(self):
        return [self.white_player, self.black_player]

    @property
    def single_player(self):
        return self.white_player == self.black_player

    def get_absolute_url(self):
        return reverse('game', args=[self.label])

# a model for challenges sent directly to other players
class Challenge(models.Model):
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="sent_challenges"
    )
    receiver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name="received_challenges"
    )

    def __str__(self):
        return f"Challenge from {self.sender.username} to {self.receiver.username}"


# -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 17:46:10 2015

@author: Rubén
"""

import datetime
import time
import pprint
import pandas as pd
from os import path
import csv
from Bio.SeqIO.FastaIO import SimpleFastaParser

def obtener_matriz_similitud(input_file:str) -> dict:
    """
    Obtiene los datos de similitud de un fichero y devuelve una matriz de similitud entre bases nitrogenadas.
    :Fichero_entrada: Archivo que contiene la matriz de similitud entre bases.
    """

    _, file_type = path.splitext(input_file)

    if file_type == '.xlsx':
        score_excel = pd.read_excel(input_file, index_col=0)
        return score_excel.to_dict('dict')

    elif file_type == '.csv':
        with open(input_file, 'r') as csvfile:
            dialect = csv.Sniffer().sniff(csvfile.readline())
            csv_separator = dialect.delimiter

        score_csv = pd.read_csv(input_file, index_col=0, sep = csv_separator)
        return score_csv.to_dict('dict')

    elif file_type == '.txt':
        #Obtención de la lista de bases.
        with open(input_file, "r") as f:
            documento = f.readlines()
            bases = documento[0].split()[1:]
            matriz = {}

            # Incializar la matriz a cero.
            for base in bases:
                matriz[base] = {base : 0}

            for i in range(len(bases)):
                for j in range(len(bases)):
                    linea_punt = documento[j+1]
                    linea_punt_lista = linea_punt.split(" ")
                    puntuacion = linea_punt_lista[i+1].rstrip()
                    matriz[bases[i]][linea_punt_lista[0]] = puntuacion

            # print("Score matrix")
            # pp = pprint.PrettyPrinter(indent=4)
            # pp.pprint(matriz)
            f.close()
            return matriz
    else:
        raise Exception('File format not supported')

def analizar_fasta(file) -> dict:
    """
    Obtiene las secuencias y los identificadores de un archivo en formato FASTA y los devuelve en una tabla.
    """
    sequences_dict = {}

    try:
        with open(file, 'r') as fasta_file:
            fasta_parsed = SimpleFastaParser(fasta_file)
            for values in fasta_parsed:
                sequences_dict[values[0]] = sequences_dict.get(values[0], values[1])
            fasta_file.close()
    except IOError:
        """
        Si se detecta un error de entrada por no poner correctamente el nombre del archivo, su ruta o por no estar
        este en el mismo directorio que el script, lo informará y dará la opción de introducir los datos manualmente
        """
        print ("No se puede abrir el archivo, compruebe que el nombre o la ruta sean correctos.")
        identificador1 = input("Identificador de la secuencia 1: ")
        secuencia1     = input("Secuencia 1: ")
        identificador2 = input("Identificador de la secuencia 2: ")
        secuencia2     = input("Secuencia 2: ")

        sequences_dict = {identificador1:secuencia1,identificador2:secuencia2}

    return sequences_dict
    # Trata de abrir el archivo con las secuencias
    """
    try:
        archivo_fasta = open(archivo)
        for linea in archivo_fasta:
            if linea.startswith(">"):
                secuencia = ""
                cabecera = linea.rstrip()
                # Dividimos la cadena por por el símbolo ">" y
                # tomamos la primera palabra a partir del primer carácter para eliminar el ">" inicial.
                identificador = cabecera.split(">")[1]
                tabla[identificador] = secuencia
            else:
                secuencia+=linea.rstrip()
                tabla[identificador]=secuencia

    # Si el archivo no puede ser abierto, se informa del error.
    # Se da la opción de introducir manualmente las secuencias para los casos de prueba
    except IOError:

        #Si se detecta un error de entrada por no poner correctamente el nombre del archivo, su ruta o por no estar
        #este en el mismo directorio que el script, lo informará y dará la opción de introducir los datos manualmente

        print ("No se puede abrir el archivo, compruebe que el nombre o la ruta sean correctos.")
        # secuencia1 = raw_input("Secuencia 1: ")
        # secuencia2 = raw_input("Secuencia 2: ")
        # identificador1 = raw_input("Identificador de la secuencia 1: ")
        # identificador2 = raw_input("Identificador de la secuencia 2: ")
        # tabla = {identificador1:secuencia1,identificador2:secuencia2}

    return tabla
    """

def generar_salida(tabla_secuencias,gap,matriz_similitud,archivo_salida) -> None:
    """
    Subrutina a la que se da una tabla con dos secuencias y sus identificadores, un archivo de salida y las puntuaciones para un alineamiento.
    Genera un fichero txt con los identificadores, las secuencias alineadas y la puntuación del alineamiento.
    Por defecto, sobreescribirá un archivo de salida si ya existe otro con el mismo nombre.
    """
    lista_secuencias = list(tabla_secuencias.values())
    lista_identificadores = list(tabla_secuencias.keys())
    alineamiento1,alineamiento2,puntuacion = alineamiento(lista_secuencias[0],lista_secuencias[1],gap,matriz_similitud)

    # Abrimos un fichero en el que escribiremos los alineamientos junto a los identificadores de las secuencias, así como la puntuación de ese alineamiento.
    # Cada vez que se ejecute el algoritmo, si se especica un nombre de fichero idéntico al anterior o a otro que ya exista en el mismo directorio, este será sobreescrito.
    # Para ir añadiendo alineamientos a un mismo fichero en caso de querer ejecutarlo de forma recursiva, cambiar la "w" de la siguiente línea por "a".
    with open(archivo_salida,"w") as output_file:
        output_file.write(str(lista_identificadores[0]))
        output_file.write(str("\n"))
        output_file.write(str(alineamiento1))
        output_file.write(str("\n"))
        output_file.write(str(alineamiento2))
        output_file.write(str("\n"))
        output_file.write(str(lista_identificadores[1]))
        output_file.write(str("\n"))
        output_file.write(str("Puntuación: "))
        output_file.write(str(puntuacion))
        output_file.write(str("\n\n"))
        output_file.close()

def alineamiento(secuencia1,secuencia2,gap,matriz_similitud):
    """
    Subrutina de alineamiento global de secuencias (algoritmo de Needleman-Wunsch).
    Alinea dos secuencias de la misma longitud y devuelve el alineamiento junto a la puntuación obtenida.
    La puntuación dependerá del valor que le hayamos definido a los eventos de coincidencia, error o gap.
    Devuelve cada una de las secuencias con los gaps (si los hubiera) y la puntuación de ese alineamiento.
    """

    # Tabla para asociar cada base a una posición dentro de la matriz de similitud
    bases = {'A':0,'T':1,'C':2,'G':3}

    # La matriz de similitud almacena los valores de coincidencia y error. Se pueden editar los valores para asignar puntuaciones concretas según el caso.

    # Variables para recorrer las secuencias
    I = range(len(secuencia1)+1)
    J = range(len(secuencia2)+1)

    # Generación de la matriz vacía
    F = [[0 for i in J] for j in I]

    # Generación de casos base
    for i in I:
        F[i][0] = gap*i
    for j in J:
        F[0][j] = gap*j

    # Cálculo de la matriz de puntuación
    for i in range(1, len(secuencia1)+1):
        for j in range(1, len(secuencia2)+1):
            # Bases
            base1 = secuencia1[i-1]
            base2 = secuencia2[j-1]

            # Posición en la matriz de similitud
            # posicion1 = bases[base1]
            # posicion2 = bases[base2]
            # prueba = matriz_similitud[base1][base2]
            # print "prueba:",prueba

            diagonal  = F[i-1][j-1] + int(matriz_similitud[base1][base2])
            izquierda = F[i-1][j]   + gap
            arriba    = F[i][j-1]   + gap
            F[i][j] = max(diagonal, izquierda, arriba)

    # Reconstrucción del alineamiento
    alineamiento1 = ""
    alineamiento2 = ""

    i = len(secuencia1)
    j = len(secuencia2)

    while (i > 0 and j > 0):
        # Puntuaciones
        puntuacion = F[i][j]
        punt_diagonal = F[i-1][j-1]
        punt_arriba = F[i][j-1]
        punt_izquierda = F[i-1][j]

        # Bases
        base1 = secuencia1[i-1]
        base2 = secuencia2[j-1]

        # Posición en la matriz de similitud
        # posicion1 = bases[base1]
        # posicion2 = bases[base2]

        if puntuacion == punt_diagonal + int(matriz_similitud[base1][base2]):
            alineamiento1 = secuencia1[i-1] + alineamiento1
            alineamiento2 = secuencia2[j-1] + alineamiento2
            i = i-1
            j = j-1

        elif puntuacion == punt_izquierda + gap:
            alineamiento1 = secuencia1[i-1] + alineamiento1
            alineamiento2 = "-" + alineamiento2
            i = i-1

        elif puntuacion == punt_arriba + gap:
            alineamiento1 = "-" + alineamiento1
            alineamiento2 = secuencia2[j-1] + alineamiento2
            j = j-1

    while i > 0:
        alineamiento1 = secuencia1[i-1] + alineamiento1
        alineamiento2 = "-" + alineamiento2
        i = i-1

    while j > 0:
        alineamiento1 = "-" + alineamiento1
        alineamiento2 = secuencia2[j-1] + alineamiento2
        j = j-1

    return alineamiento1, alineamiento2, F[len(secuencia1)][len(secuencia2)]

def main():

    # Definir archivos de entrada, salida y generar la tabla con cada identificador ligado a su secuencia
    archivo_fasta = input("Archivo FASTA de entrada:")
    while not archivo_fasta:
        archivo_fasta = input("Archivo FASTA de entrada:")

    archivo_similitud = input("Archivo con la matriz de similitud:")
    while not archivo_similitud:
        archivo_similitud = input("Archivo con la matriz de similitud:")

    archivo_salida_nombre = input("Archivo de salida:")
    while not archivo_salida_nombre:
        archivo_salida_nombre = input("Archivo de salida:")

    archivo_salida = archivo_salida_nombre + ".txt"
    tabla_secuencias = analizar_fasta(archivo_fasta)

    # Comprobación de las secuencias y los identificadores obtenidos
    #    for identificador in tabla_secuencias.keys():
    #        print "Identificador:",identificador,"\n","Secuencia:",tabla_secuencias[identificador],"\n"

    # Definición de las puntuaciones de coincidencia, error y gap
    # coincidencia = int(raw_input("Puntuación de coincidencia:"))
    # error = int(raw_input("Puntuación de error:"))

    gap = int(input("Puntuación de gap: "))
    matriz_similitud = obtener_matriz_similitud(archivo_similitud)

    ti=time.perf_counter() # Tiempo inicial

    # Se escribe el alineamiento, junto a los identificadores de cada secuencia y la puntuación obtenida en el archivo de salida
    generar_salida(tabla_secuencias,gap,matriz_similitud,archivo_salida)

    tf=time.perf_counter() # Tiempo final
    print ("ETA -->",tf-ti)

if __name__ == "__main__":
    main()


import math
import numpy as np
import os
from pathlib import Path
from collections import OrderedDict
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import argparse

def ens_parser(en_files):
    data = OrderedDict()
    for window in en_files:
        step_lambda = window.parts[-2]
        dVdl_np= np.array([])
        ln = 0
        with window.open() as en:
            for line in en:
                ln += 1
                if line[0:2]=="L9" and not 'dV/dlambda' in line:
                    dVdl_np = np.append(dVdl_np,float(line.split()[5]))
        try:
            mean=np.mean(dVdl_np)
            std_np=math.sqrt(((dVdl_np-np.mean(dVdl_np))**2).sum())/(dVdl_np.size-1)
            data[float(step_lambda)]=(mean, std_np, dVdl_np.size)
        except:
            print(f"There is some errors in {window}")
            os._exit(0)
    if len(data.keys()) < 12:
        print(f"only {data.keys()}")
        os._exit(0)
    return data

def out_parser(out_files):
    data = OrderedDict()
    for out in out_files:
        step_lambda = out.parts[-2]
        dVdl_np= np.array([])
        with out.open() as infos:
            try:
                info = infos.read().split("A V E R A G E S   O V E R ")[1].split("\n")
                DVDL = [float(item.split("=")[1]) for item in info if 'DV/DL' in item ]
                dVDl = [float(item.split("=")[1]) for item in info if 'dV/Dl' in item ]
                data[float(step_lambda)]=(DVDL[0]-dVDl[0], 0.0, 18)
            except:
                print(f"There is some errors in {step_lambda}")
                os._exit(0)
    return data

def extrap_polyfit(x,y):
    coeffs = np.polyfit(x, y, 6)
    if 0.0 not in x:
        x.insert(0, 0.0)
        y.insert(0, coeffs[-1])
    if 1.0 not in x:
        x.append(1.0)
        y.append(sum(coeffs))
    return (x,y)

def data_calculate(data):
    x = list(data.keys())
    x.sort()
    y = [data[l][0] for l in x]
    x,y=extrap_polyfit(x,y)
    rmse_tot = 0.0
    for i in range(1,len(x)-1):
        rmse_tot += 0.5*(x[i+1]-x[i-1])*data[x[i]][1]
    return (x,y,rmse_tot)

def res_output(outpath,data,x,y,rmse_tot):
    with open(outpath,"w") as out:
        for a, b in zip(x, y):
            if a in data:
                v = data[a]
                out.write(f"{a}\t{v[0]:> 10.4f}\t{v[1]:> 10.4f}\t{v[2]}\n")
            else:
                out.write(f"{a:0<7}\t{b:> 10.4f}\t{0.0:> 10.4f}\t{0:4}\n")
        out.write(f"#   dG = {np.trapz(y, x):> 8.4f}\n# RMSE = {rmse_tot:> 8.4f}\n")
    print(f"dG = {np.trapz(y, x):.2f}")

def TI_plot(x,y,err,outpath):
    plt.title("TI plot ")
    plt.xlabel('lambda',labelpad = -30,loc = 'right')
    plt.ylabel("<dU/dlambda>")
    ax = plt.subplots()[-1]
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')         # 将右边 上边的两条边颜色设置为空 其实就相当于抹掉这两条
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')          # 指定下边的边作为 x 轴   指定左边的边为 y 轴
    ax.spines['bottom'].set_position(('data', 0))   #指定 data  设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上
    ax.spines['left'].set_position(('data', 0))
    plt.errorbar(x,y,yerr=err,fmt='o:',ecolor='red',elinewidth=3,ms=5,mfc='wheat',mec='salmon',capsize=3)
    ix=np.array(x)
    iy=np.array(y)
    ixy=list(zip(ix,iy))
    ixy=[(0.0,0.0)]+ixy+[(1.0,0.0)]
    poly=mpatches.Polygon(ixy,facecolor='0.8',edgecolor='0.1')
    ax.add_patch(poly)
    plt.savefig(outpath)
    return(f"The TI figure is {str(outpath)}")

def dvdl_draw(dvdl,pngpath):
    x,y,err=[],[],[]
    with dvdl.open() as dat:
        for line in dat:
            if line[0] != "#":
                line = line.split()
                x.append(float(line[0]))
                y.append(float(line[1]))
                try:
                    err.append(float(line[2]))
                except:
                    err.append(float(0))
            else:
                dG = float(line.split()[-1])
    print(TI_plot(x,y,err,pngpath))
    return True

def get_dG(target_dir,ifcon):
    windows = list(target_dir.glob("**/ti001.en"))
    data = ens_parser(windows)
    x,y,rmse_tot = data_calculate(data)
    x_con,y_con = x[2:-2],y[2:-2]
    x_con,y_con = extrap_polyfit(x_con,y_con)
    dvdl_dat=target_dir/"dvdl_re.dat"
    res_output(dvdl_dat,data,x,y,rmse_tot)
    pngpath=target_dir/f"TI_plot2.png"
    dvdl_draw(dvdl_dat,pngpath)
    dG_all = np.trapz(y,x)
    dG_con = np.trapz(y_con, x_con)
    if ifcon:
        # outs = list(target_dir.glob("**/ti001.out"))
        # data_out = out_parser(outs)
        # x_out,y_out,rmse_tot = data_calculate(data_out)
        # x_con,y_con = x[2:-2],y[2:-2]
        # x_con,y_con = extrap_polyfit(x_con,y_con)
        # dG_all_res = np.trapz(y_out, x_out)
        # dG_con_res = np.trapz(y_con, x_con)
        # return (dG_all,dG_con,dG_all_res,dG_con_res,rmse_tot)
        return (dG_all,dG_con,rmse_tot)
    else:
        return (dG_all, rmse_tot)

def get_ddG(path):
    ligand_res = get_dG(path/"free_energy/ligands",False)
    complex_res = get_dG(path/"free_energy_VBA_2/complex",True)
    with open(str(path/"free_energy_VBA_2/dG_cor")) as cor:
        dG_cor = float(cor.read().split()[0])
    rmse = math.sqrt(ligand_res[-1]**2+complex_res[-1]**2)
    ddG_all = complex_res[0]+dG_cor-ligand_res[0]
    ddG_con = complex_res[1]+dG_cor-ligand_res[0]
    # ddG_all_res = complex_res[2]+dG_cor-ligand_res[0]
    # ddG_all_con = complex_res[3]+dG_cor-ligand_res[0]

    data_bio = {}
    with open("/pubhome/yjcheng02/clr_abfe/ABFE/bio.res") as bio:
        for line in bio:
            ligand, bio_info = line.split()
            data_bio[ligand] = (0.1987*3.0) * math.log(float(bio_info)*10**(-9))

    name = f"A{path.absolute().name[-2:]}"
    # info=f"{data_bio[name]:.2f}\n{ddG_all:.2f}\n{ddG_con:.2f}\n{ddG_all_res:.2f}\n{ddG_all_con:.2f}\n{rmse:.2f}\n"
    info=f"{data_bio[name]:.2f}\n{ddG_all:.2f}\n{ddG_con:.2f}\n{rmse:.2f}\n"
    with open(f"{str(path)}/VBA_res",'w') as VBA:
        VBA.write(info)
    print(info)
    return True

parser = argparse.ArgumentParser(description="Plot TI figure")
parser.add_argument(
    "--data",
    dest='data',
)

info = parser.parse_args().data
p=Path(info)
get_ddG(p)


import json
import os
import sys

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print(sys.argv)
        print('argv error, inert_op_info.py your_op_file lib_op_file')
        sys.exit(2)

    with open(sys.argv[1], 'r') as load_f:
        insert_operator = json.load(load_f)

    all_operators = {}
    if os.path.exists(sys.argv[2]):
        if os.path.getsize(sys.argv[2]) != 0:
            with open(sys.argv[2], 'r') as load_f:
                all_operators = json.load(load_f)

    for k in insert_operator.keys():
        if k in all_operators.keys():
            print('replace op:[', k, '] success')
        else:
            print('insert op:[', k, '] success')
        all_operators[k] = insert_operator[k]

    with open(sys.argv[2], 'w') as json_file:
        json_file.write(json.dumps(all_operators, indent=4))


''' Queries the ChEMBL database to find target proteins for drugs.
'''

__author__ = 'Stephen Ramsey'
__copyright__ = 'Oregon State University'
__credits__ = ['Stephen Ramsey']
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = ''
__email__ = ''
__status__ = 'Prototype'

import urllib
import requests
import sys

class QueryChEMBL:

    API_BASE_URL = 'https://www.ebi.ac.uk/chembl/api/data'
    TIMEOUT_SEC = 120

    @staticmethod
    def send_query_get(handler, url_suffix):
        url = QueryChEMBL.API_BASE_URL + '/' + handler + '?' + url_suffix
#        print(url)
        try:
            res = requests.get(url,
                               timeout=QueryChEMBL.TIMEOUT_SEC)
        except requests.exceptions.Timeout:
            print(url, file=sys.stderr)
            print('Timeout in QueryChEMBL for URL: ' + url, file=sys.stderr)
            return None
        status_code = res.status_code
        if status_code != 200:
            print(url, file=sys.stderr)
            print('Status code ' + str(status_code) + ' for url: ' + url, file=sys.stderr)
            return None
        return res.json()

    @staticmethod
    def get_chembl_ids_for_drug(drug_name):
        res = QueryChEMBL.send_query_get(handler='compound_record.json',
                                         url_suffix='compound_name__iexact=' + urllib.parse.quote(drug_name, safe=''))
        res_chembl_set = set()
        if res is not None:
            compound_records = res.get('compound_records', None)
            if compound_records is not None:
                for compound_record in compound_records:
                    chembl_id = compound_record.get('molecule_chembl_id', None)
                    if chembl_id is not None:
                        res_chembl_set.add(chembl_id)
        return res_chembl_set

    @staticmethod
    def get_target_uniprot_ids_for_chembl_id(chembl_id):
        res = QueryChEMBL.send_query_get(handler='target_prediction.json',
                                         url_suffix='molecule_chembl_id__exact=' + chembl_id + '&target_organism__exact=Homo%20sapiens')
        res_targets_set = set()
        if res is not None:
            target_predictions_list = res.get('target_predictions', None)
            if target_predictions_list is not None:
                for target_prediction in target_predictions_list:
                    target_uniprot_id = target_prediction.get('target_accession', None)
                    if target_uniprot_id is not None:
                        # need to get the gene ID for this Uniprot ID
                        res_targets_set.add(target_uniprot_id)
        return res_targets_set

    @staticmethod
    def get_target_uniprot_ids_for_drug(drug_name):
        chembl_ids_for_drug = QueryChEMBL.get_chembl_ids_for_drug(drug_name)
        res_uniprot_ids = set()
        for chembl_id in chembl_ids_for_drug:
            res_uniprot_ids |= QueryChEMBL.get_target_uniprot_ids_for_chembl_id(chembl_id)
        return res_uniprot_ids

    @staticmethod
    def test():
        print(QueryChEMBL.get_target_uniprot_ids_for_drug('clothiapine'))

if __name__ == '__main__':
    QueryChEMBL.test()


# -*- coding:utf-8 -*-
# 题目描述
# 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。
# 请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形，总共有多少种方法？
class Solution:
    def rectCover(self, number):
        # write code here
        if number == 0:
            return 0
        elif number == 1:
            return 1
        elif number == 2:
            return 2
        else:
            a=[1,2]
            for i in range(2,number):
                a.append(a[i-2]+a[i-1])
            return a[number-1]

if __name__ == '__main__':
    s=Solution
    a=s.rectCover(s,4)
    print(a)


# coding=utf8
""" CLI Module

Holds methods for doing CLI things
"""

__author__ = "Chris Nasr"
__copyright__ = "FUEL for the FIRE"
__version__ = "1.0.0"
__created__ = "2018-11-11"

# Python imports
import sys

class ProgressBar(object):
	"""Progress Bar

	Generates a progress bar for use in terminals
	"""

	def __init__(self, title="Progress Bar", total=100, sections=20, start=0):
		"""Constructor

		Initialises the instance of the object

		Arguments:
			title (str): The text before the progress bar
			total (int): The total count of items
			sections (int): The number of sections in the progress bar
			start (int): Optional, defaults to 0

		Returns:
			ProgressBar
		"""

		# If any values are invalid
		if not isinstance(total, (int,long)) or total < 1:
			raise ValueError('total must be at least 1 (one) or higher')
		if not isinstance(sections, (int,long)) or sections < 1:
			raise ValueError('sections must be at least 1 (one) or higher')
		if not isinstance(start, (int,long)) or start < 0:
			raise ValueError('start must be an unsigned integer')

		# Store the title and count
		self.title = title
		self.total = total
		self.sections = sections
		self.count = start

		# Figure out the steps from the sections
		self.steps = self.total / self.sections

		# Calculate percentage
		self.perc = round((self.count / self.total) * 100.0, 1)

		# Draw
		self.draw()

	def __add__(self, other):
		"""+ (overloaded)

		Handles adding to the count

		Arguments:
			other (uint): Should be an unsigned number

		Returns:
			None
		"""

		# Verify the other
		if not isinstance(other, (int,long)) or other < 1:
			raise ValueError('other must be 1 (one) or greater')

		# Add it to the count
		self.count += other

		# Recalculate the percentage
		self.perc = round((self.count / self.total) * 100.0, 1)

		# Update the drawing
		self.draw()

		# If we reached maximum
		if self.count >= self.total:
			print('')

	def clear(self):
		"""Clear

		Clears the screen

		Returns:
			None
		"""
		print('')

	def draw(self):
		"""Draw

		Draws the progress bar in the terminal

		Returns:
			None
		"""

		# Calculate the steps done
		iDone = int(self.count // self.steps)
		iDiff = self.count % self.steps

		# If the diff is more than half a step, add a step
		if self.steps - iDiff <= iDiff:
			iDone += 1

		# Generate the actual progress bar
		sDiff = ('\u2588' * iDone) + (' ' * (self.sections - iDone))

		# Print everything
		print("\r%s [%s] %.1f%%" % (self.title, sDiff, self.perc), end=' ')


# -*- coding: utf-8 -*-

import sys
import glob
import re
import struct
import os
from PIL import Image

# conversion
def convert_inputs(inputs, output):
    images = []
    for input in inputs:
        #
        with open(input, 'rb') as f:
            f.seek(-4, os.SEEK_END)
            count_images = struct.unpack('<I', f.read(4))[0] & 0x7FFFFFFF
            print('reading: %s (%d images)'%(input, count_images))
            f.seek(0, os.SEEK_SET)
            for i in range(count_images):
                pixels = []
                img_w, img_h, img_data_size = struct.unpack('<III', f.read(12))
                if img_w > 512 or img_h > 512 or img_data_size > 1000000:
                    print('error: invalid sprite %d: width %d, height %d, data size %d'%(i, img_w, img_h, img_data_size))
                    sys.exit(1)
                data_size = img_data_size
                while data_size > 0:
                    ipx = struct.unpack('<B', f.read(1))[0]
                    ipx |= ipx << 8
                    ipx &= 0xC03F
                    data_size -= 1

                    if ipx & 0xC000 > 0:
                        if ipx & 0xC000 == 0x4000:
                            ipx &= 0x3F
                            pixels += [0x00000000] * (img_w * ipx)
                        else:
                            ipx &= 0x3F
                            pixels += [0x00000000] * ipx
                    else:
                        ipx &= 0x3F
                        # read N bytes of color
                        for j in range(ipx):
                            byte = struct.unpack('<B', f.read(1))[0]
                            data_size -= 1

                            alpha1 = (byte & 0x0F) | ((byte & 0x0F) << 4)
                            pixels.append((alpha1<<24) | 0xFFFFFF)

                            if (j != ipx-1) or byte & 0xF0:
                                alpha2 = (byte & 0xF0) | ((byte & 0xF0) >> 4)
                                pixels.append((alpha2<<24) | 0xFFFFFF)

                images.append([img_w, img_h, pixels])

    for i in range(len(images)):
        print('writing: %s'%(output%i))
        image = images[i]
        pil_img = Image.new('RGBA', (image[0], image[1]))
        pil_img.putdata(image[2])
        pil_img.save(output%i)

# command line parsing

filenames = []
argv_begin = 2 if __name__ != '__main__' else 1
for fn in sys.argv[argv_begin:]:
    filenames += glob.glob(fn)

# make all slashes forward, remove duplicate slashes
# this is so that I can use regular split() to find out filename
def normalize_name(fn):
    fn = re.sub(r"[\/\\]+", '/', fn)
    return fn

filenames = [fn for fn in filenames]

inputs = []
for fn in filenames:
    ft = fn.split('.')[-1].lower()
    if ft == 'png': # convert inputs to this template
        convert_inputs(inputs, fn)
        inputs = []
    else:
        inputs.append(fn)

if inputs:
    for input in inputs:
        split_input = input.split('/')
        base_input = '.'.join(split_input[-1].split('.')[:-1])
        dir_input = '/'.join(split_input[:-1]) if len(split_input) > 1 else '.'
        output = '%s/%s-%%03d.png'%(dir_input, base_input)
        convert_inputs([input], output)


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

# # YOLO v3 Object Detection
#
# Let's see how to use the state of the art in object detection! Please make sure to watch the video, there is no code along here, since we can't reasonably train the YOLOv3 network ourself, instead we will use a pre-established version.
#
# CODE SOURCE: https://github.com/xiaochus/YOLOv3
#
# REFERENCE (for original YOLOv3):
#
#         @article{YOLOv3,
#               title={YOLOv3: An Incremental Improvement},
#               author={J Redmon, A Farhadi },
#               year={2018}
# --------
# ----------
# ## YOU MUST WATCH THE VIDEO LECTURE TO PROPERLY SET UP THE MODEL AND WEIGHTS. THIS NOTEBOOK WON'T WORK UNLESS YOU FOLLOW THE EXACT SET UP SHOWN IN THE VIDEO LECTURE.
# -------
# -------

# In[3]:

import os
import time
import cv2
import numpy as np
from model.yolo_model import YOLO

# In[4]:

def process_image(img):
    """Resize, reduce and expand image.

    # Argument:
        img: original image.

    # Returns
        image: ndarray(64, 64, 3), processed image.
    """
    image = cv2.resize(img, (416, 416),
                       interpolation=cv2.INTER_CUBIC)
    image = np.array(image, dtype='float32')
    image /= 255.
    image = np.expand_dims(image, axis=0)

    return image

# In[5]:

def get_classes(file):
    """Get classes name.

    # Argument:
        file: classes name for database.

    # Returns
        class_names: List, classes name.

    """
    with open(file) as f:
        class_names = f.readlines()
    class_names = [c.strip() for c in class_names]

    return class_names

# In[6]:

def draw(image, boxes, scores, classes, all_classes):
    """Draw the boxes on the image.

    # Argument:
        image: original image.
        boxes: ndarray, boxes of objects.
        classes: ndarray, classes of objects.
        scores: ndarray, scores of objects.
        all_classes: all classes name.
    """
    for box, score, cl in zip(boxes, scores, classes):
        x, y, w, h = box

        top = max(0, np.floor(x + 0.5).astype(int))
        left = max(0, np.floor(y + 0.5).astype(int))
        right = min(image.shape[1], np.floor(x + w + 0.5).astype(int))
        bottom = min(image.shape[0], np.floor(y + h + 0.5).astype(int))

        cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 2)
        cv2.putText(image, '{0} {1:.2f}'.format(all_classes[cl], score),
                    (top, left - 6),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    2 ,(0, 0, 255), 3,
                    cv2.LINE_AA)

       # print('class: {0}, score: {1:.2f}'.format(all_classes[cl], score))
        #print('box coordinate x,y,w,h: {0}'.format(box))

    print()

# In[7]:

# function to find if
# given point lies inside
# a given rectangle or not.
def FindPoint2(left, bottom, right, top, x, y,w,h) :
    px1, py1, px2, py2 = left, top, right, bottom
    hx1, hy1, hx2, hy2 = x,y,x+w,y+h
    if (hx1 >= px1 and hy1 >= py1) or (hx2 <= px2 and hy2 <=py2):
        print("True!")
        return True
    else:
        return False

def FindPoint(left, bottom, right, top, x, y,w,h) :
    try:
        cat_x=int((2*x+w)/2)
        cat_y=int((2*y+h)/2)
        if cat_x>left and cat_y<top and cat_x<right and cat_y>bottom:
            print("True!")
            return True
        else:
            return False
    except:
        print("something wrong")
        return False

def only_if_max(curr_val, new_val):

    if curr_val==None or new_val > curr_val :

        return new_val
    return curr_val

def only_if_min(curr_val, new_val):
    if curr_val==None or new_val < curr_val:
        return new_val
    return curr_val

# In[8]:

# In[22]:

def draw2(image, boxes, scores, classes, all_classes, bad_guy, forbbiden_place):
    """Draw the boxes on the image.

    # Argument:
        image: original image.
        boxes: ndarray, boxes of objects.
        classes: ndarray, classes of objects.
        scores: ndarray, scores of objects.
        all_classes: all classes name.
    """
    cat_exsists=0
    toilet_exists=0
    toilet_left=None
    toilet_right=None
    toilet_bottom=None
    toilet_top=None
    tags=[]
    for box, score, cl in zip(boxes, scores, classes):
        x, y, w, h = box

        top = max(0, np.floor(x + 0.5).astype(int))
        left = max(0, np.floor(y + 0.5).astype(int))
        right = min(image.shape[1], np.floor(x + w + 0.5).astype(int))
        bottom = min(image.shape[0], np.floor(y + h + 0.5).astype(int))
        tags.append(all_classes[cl])
        if all_classes[cl]==bad_guy:
            cv2.rectangle(image, (top, left), (right, bottom), (0, 0, 255), 2)
            cv2.putText(image, '{0} {1:.2f}'.format(all_classes[cl], score),
                    (top, left - 6),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    1 ,(0, 0, 255), 1,
                    cv2.LINE_AA)

        if all_classes[cl]==forbbiden_place:
            toilet_exists=1
            toilet_exists=0
            toilet_left=only_if_min(toilet_left, left)
            toilet_right=only_if_max(toilet_right,right)
            toilet_bottom=only_if_max(toilet_bottom, bottom)
            toilet_top=only_if_min(toilet_top, top)
            text_hieght=  int((toilet_bottom+toilet_top)/2)
            cat_x=int((2*x+w)/2)
            cat_y=int((2*y+h)/2)
            #print("toilet")

        if toilet_left: #prevent nonetype
            cv2.rectangle(image, (toilet_top, toilet_left), (toilet_right, toilet_bottom), (200, 0, 0), 2)
        if forbidden_place and bad_guy in tags:
            if bad_guy in tags:
                if FindPoint(toilet_left,toilet_top,toilet_right,toilet_bottom, x,y,w,h):
                    #image = cv2.circle(image, (cat_y,cat_x) , 2, (0, 0, 100), 2 )
                    text = str(str(bad_guy).upper()+" IS ON THE "+str(forbbiden_place).upper())
                    print(text)
                    #print("CAT IN THE TOILET")
                    image = cv2.circle(image, (cat_x,cat_y) , 4, (0, 0, 255), 4 )
                    text_y=text_hieght
                    text_x=int((cat_x/2))
                    # font
                    font = cv2.FONT_HERSHEY_SIMPLEX

                    # org
                    org = (text_x-100, text_y )

                    # fontScale
                    fontScale = 1

                    # Blue color in BGR
                    color = (50, 0, 255)

                    # Line thickness of 2 px
                    thickness = 2

                    # Using cv2.putText() method

                    y0, dy = text_y, 150
                    #for i, line in enumerate(text.split('\n')):
                    #        y = y0 + i*dy
                    #        cv2.putText(image, line, (text_x, y ), cv2.FONT_HERSHEY_SIMPLEX, fontScale, color, thickness, cv2.LINE_AA)
                    image = cv2.putText(image,  text, org, font, fontScale, color, thickness, cv2.LINE_AA)

                    #cv2.putText(image,'{0} {1:.2f}'.format( "CAT IN THE TOILET"),(bottom, left +6), cv2.FONT_HERSHEY_SIMPLEX, 10 ,(0, 0, 255), 8, cv2.LINE_AA)

        #print('class: {0}, score: {1:.2f}'.format(all_classes[cl], score))
        #print('box coordinate x,y,w,h: {0}'.format(box))

# In[17]:

def detect_image(image, yolo, all_classes, bad_guy, forbbiden_place):
    """Use yolo v3 to detect images.

    # Argument:
        image: original image.
        yolo: YOLO, yolo model.
        all_classes: all classes name.

    # Returns:
        image: processed image.
    """
    pimage = process_image(image)

    start = time.time()
    boxes, classes, scores = yolo.predict(pimage, image.shape)
    end = time.time()

    print('frame process time: {0:.2f}s'.format(end - start))

    if boxes is not None:
        draw2(image, boxes, scores, classes, all_classes, bad_guy, forbbiden_place)

    return image

# In[18]:

def detect_video(video, yolo, all_classes, bad_guy, forbbiden_place):
    """Use yolo v3 to detect video.

    # Argument:
        video: video file.
        yolo: YOLO, yolo model.
        all_classes: all classes name.
    """
    print(video)
    # FILE SOURCE
    #video_path = os.path.join("videos", "test", video)
    #camera = cv2.VideoCapture(video_path)
    #cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)

    # STREAM source
    camera = cv2.VideoCapture(0)

    # Prepare for saving the detected video
    sz = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)), int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fourcc = cv2.VideoWriter_fourcc(*'mpeg')
    fps=20

    vout = cv2.VideoWriter()
    vout.open(os.path.join("videos", "res", video), fourcc, fps, sz, True)

    while True:
        res, frame = camera.read()

        if not res:
            break

        image = detect_image(frame, yolo, all_classes, bad_guy, forbbiden_place)
        #cv2.imshow("detection", image)

        # Save the video frame by frame
        vout.write(image)

        if cv2.waitKey(1) & 0xff == 27:
                break

    vout.release()
    camera.release()
    print("done")

# In[19]:

yolo = YOLO(0.25, 0.5)
file = 'data/coco_classes.txt'
all_classes = get_classes(file)

# ### Detecting Images

# In[35]:

# DEFINE MISSION:
# choose objects from classes list: data/coco_classes.txt
bad_guy="cat"
forbidden_place="toilet"

with open("data/coco_classes.txt") as f:
    if bad_guy and forbidden_place in f.read():
        print("Objects are valid")
    else:
        print("CHANGE OBJECT NAMES")

# In[20]:

f = 'oscar_toilet.jpg'
path = 'images/'+f
image = cv2.imread(path)
image = detect_image(image, yolo, all_classes,bad_guy, forbidden_place)
cv2.imwrite('images/res/' + f, image)

# # Detecting on Video

# In[36]:

# # detect videos one at a time in videos/test folder

video = 'cat_flushing2.mp4'
detect_video(video, yolo, all_classes, bad_guy, forbidden_place)

# In[ ]:

# In[ ]:


import json
import logging
import sys

from desktop.lib.django_util import JsonResponse
from desktop.lib.i18n import force_unicode
from metadata.manager_client import ManagerApi
from notebook.models import _get_notebook_api

from kafka.conf import has_kafka_api
from kafka.kafka_client import KafkaApi, KafkaApiException, SchemaRegistryApi

if sys.version_info[0] > 2:
  from django.utils.translation import gettext as _
else:
  from django.utils.translation import ugettext as _

LOG = logging.getLogger()

def error_handler(view_fn):
  def decorator(*args, **kwargs):
    status = 500
    response = {
      'message': ''
    }

    try:
      return view_fn(*args, **kwargs)
    except KafkaApiException as e:
      try:
        response['message'] = json.loads(e.message)
      except Exception:
        response['message'] = force_unicode(e.message)
    except Exception as e:
      message = force_unicode(e)
      response['message'] = message
      LOG.exception(message)

    return JsonResponse(response, status=status)
  return decorator

@error_handler
def list_topics(request):
  return JsonResponse({
    'status': 0,
    'topics': [
      {'name': topic} for topic in get_topics(request.user)
    ]
  })

@error_handler
def list_topic(request):
  name = request.POST.get('name')

  topic = get_topic(name)
  topic['name'] = name
  topic['type'] = 'topic'

  return JsonResponse({
    'status': 0,
    'topic': topic
  })

@error_handler
def create_topic(request):
  name = request.POST.get('name')
  partitions = request.POST.get('partitions', 1)
  replication_factor = request.POST.get('replication_factor', 1)

  status = KafkaApi().create_topic(name, partitions, replication_factor)

  return JsonResponse({
    'status': status,
    'topic': {
      'name': name,
      'partitions': partitions,
      'replication_factor': replication_factor
    }
  })

def get_topics(user):
  if has_kafka_api():
    return KafkaApi().topics()
  else:
    data = {
      'snippet': {},
      'database': 'topics'
    }

    from desktop.api_public import _get_interpreter_from_dialect  # Avoid circular import
    interpreter = _get_interpreter_from_dialect('ksql', user)
    api = _get_notebook_api(user, connector_id=interpreter['type'])

    return [
      topic['name']
      for topic in api.autocomplete(**data)['tables_meta']
      if not topic['name'].startswith('__')
    ]

def get_topic_data(user, name):
  if has_kafka_api():
    print(
      SchemaRegistryApi().subjects()
    )
    print(
      SchemaRegistryApi().subject(name='Kafka-value')
    )
    data = {
      'full_headers': [{'name': 'message', 'type': 'string'}],
      'rows': [
        ['This is rider 894 and I am at 38.1952, -123.1723'],
        ['This is rider 98 and I am at 39.2531, -121.9547'],
        ['This is rider 564 and I am at 22.3431, -111.7670']
      ]
    }
  else:
    from desktop.api_public import _get_interpreter_from_dialect  # Avoid circular import
    interpreter = _get_interpreter_from_dialect('ksql', user)
    api = _get_notebook_api(user, connector_id=interpreter['type'])

    data = api.get_sample_data(snippet={})

  print(data)

  return data

def get_topic(name):
  if has_kafka_api():
    pass
  else:
    manager = ManagerApi()
    broker_host = manager.get_kafka_brokers().split(',')[0].split(':')[0]
    return manager.get_kafka_topics(broker_host)[name]


from logging import getLogger
from threading import RLock
from time import time_ns
from typing import Dict, List, Optional

from opentelemetry.metrics import (
    Asynchronous,
    Counter,
    Instrument,
    ObservableCounter,
)
from opentelemetry.sdk.metrics._internal._view_instrument_match import (
    _ViewInstrumentMatch,
)
from opentelemetry.sdk.metrics._internal.aggregation import (
    Aggregation,
    ExplicitBucketHistogramAggregation,
    _DropAggregation,
    _ExplicitBucketHistogramAggregation,
    _ExponentialBucketHistogramAggregation,
    _LastValueAggregation,
    _SumAggregation,
)
from opentelemetry.sdk.metrics._internal.export import AggregationTemporality
from opentelemetry.sdk.metrics._internal.measurement import Measurement
from opentelemetry.sdk.metrics._internal.point import (
    ExponentialHistogram,
    Gauge,
    Histogram,
    Metric,
    MetricsData,
    ResourceMetrics,
    ScopeMetrics,
    Sum,
)
from opentelemetry.sdk.metrics._internal.sdk_configuration import (
    SdkConfiguration,
)
from opentelemetry.sdk.metrics._internal.view import View
from opentelemetry.sdk.util.instrumentation import InstrumentationScope

_logger = getLogger(__name__)

_DEFAULT_VIEW = View(instrument_name="")

class MetricReaderStorage:
    """The SDK's storage for a given reader"""

    def __init__(
        self,
        sdk_config: SdkConfiguration,
        instrument_class_temporality: Dict[type, AggregationTemporality],
        instrument_class_aggregation: Dict[type, Aggregation],
    ) -> None:
        self._lock = RLock()
        self._sdk_config = sdk_config
        self._instrument_view_instrument_matches: Dict[
            Instrument, List[_ViewInstrumentMatch]
        ] = {}
        self._instrument_class_temporality = instrument_class_temporality
        self._instrument_class_aggregation = instrument_class_aggregation

    def _get_or_init_view_instrument_match(
        self, instrument: Instrument
    ) -> List[_ViewInstrumentMatch]:
        # Optimistically get the relevant views for the given instrument. Once set for a given
        # instrument, the mapping will never change

        if instrument in self._instrument_view_instrument_matches:
            return self._instrument_view_instrument_matches[instrument]

        with self._lock:
            # double check if it was set before we held the lock
            if instrument in self._instrument_view_instrument_matches:
                return self._instrument_view_instrument_matches[instrument]

            # not present, hold the lock and add a new mapping
            view_instrument_matches = []

            self._handle_view_instrument_match(
                instrument, view_instrument_matches
            )

            # if no view targeted the instrument, use the default
            if not view_instrument_matches:
                view_instrument_matches.append(
                    _ViewInstrumentMatch(
                        view=_DEFAULT_VIEW,
                        instrument=instrument,
                        instrument_class_aggregation=(
                            self._instrument_class_aggregation
                        ),
                    )
                )
            self._instrument_view_instrument_matches[
                instrument
            ] = view_instrument_matches

            return view_instrument_matches

    def consume_measurement(self, measurement: Measurement) -> None:
        for view_instrument_match in self._get_or_init_view_instrument_match(
            measurement.instrument
        ):
            view_instrument_match.consume_measurement(measurement)

    def collect(self) -> Optional[MetricsData]:
        # Use a list instead of yielding to prevent a slow reader from holding
        # SDK locks

        # While holding the lock, new _ViewInstrumentMatch can't be added from
        # another thread (so we are sure we collect all existing view).
        # However, instruments can still send measurements that will make it
        # into the individual aggregations; collection will acquire those locks
        # iteratively to keep locking as fine-grained as possible. One side
        # effect is that end times can be slightly skewed among the metric
        # streams produced by the SDK, but we still align the output timestamps
        # for a single instrument.

        collection_start_nanos = time_ns()

        with self._lock:

            instrumentation_scope_scope_metrics: (
                Dict[InstrumentationScope, ScopeMetrics]
            ) = {}

            for (
                instrument,
                view_instrument_matches,
            ) in self._instrument_view_instrument_matches.items():
                aggregation_temporality = self._instrument_class_temporality[
                    instrument.__class__
                ]

                metrics: List[Metric] = []

                for view_instrument_match in view_instrument_matches:

                    data_points = view_instrument_match.collect(
                        aggregation_temporality, collection_start_nanos
                    )

                    if data_points is None:
                        continue

                    if isinstance(
                        # pylint: disable=protected-access
                        view_instrument_match._aggregation,
                        _SumAggregation,
                    ):
                        data = Sum(
                            aggregation_temporality=aggregation_temporality,
                            data_points=data_points,
                            is_monotonic=isinstance(
                                instrument, (Counter, ObservableCounter)
                            ),
                        )
                    elif isinstance(
                        # pylint: disable=protected-access
                        view_instrument_match._aggregation,
                        _LastValueAggregation,
                    ):
                        data = Gauge(data_points=data_points)
                    elif isinstance(
                        # pylint: disable=protected-access
                        view_instrument_match._aggregation,
                        _ExplicitBucketHistogramAggregation,
                    ):
                        data = Histogram(
                            data_points=data_points,
                            aggregation_temporality=aggregation_temporality,
                        )
                    elif isinstance(
                        # pylint: disable=protected-access
                        view_instrument_match._aggregation,
                        _DropAggregation,
                    ):
                        continue

                    elif isinstance(
                        # pylint: disable=protected-access
                        view_instrument_match._aggregation,
                        _ExponentialBucketHistogramAggregation,
                    ):
                        data = ExponentialHistogram(
                            data_points=data_points,
                            aggregation_temporality=aggregation_temporality,
                        )

                    metrics.append(
                        Metric(
                            # pylint: disable=protected-access
                            name=view_instrument_match._name,
                            description=view_instrument_match._description,
                            unit=view_instrument_match._instrument.unit,
                            data=data,
                        )
                    )

                if metrics:

                    if instrument.instrumentation_scope not in (
                        instrumentation_scope_scope_metrics
                    ):
                        instrumentation_scope_scope_metrics[
                            instrument.instrumentation_scope
                        ] = ScopeMetrics(
                            scope=instrument.instrumentation_scope,
                            metrics=metrics,
                            schema_url=instrument.instrumentation_scope.schema_url,
                        )
                    else:
                        instrumentation_scope_scope_metrics[
                            instrument.instrumentation_scope
                        ].metrics.extend(metrics)

            if instrumentation_scope_scope_metrics:

                return MetricsData(
                    resource_metrics=[
                        ResourceMetrics(
                            resource=self._sdk_config.resource,
                            scope_metrics=list(
                                instrumentation_scope_scope_metrics.values()
                            ),
                            schema_url=self._sdk_config.resource.schema_url,
                        )
                    ]
                )

            return None

    def _handle_view_instrument_match(
        self,
        instrument: Instrument,
        view_instrument_matches: List["_ViewInstrumentMatch"],
    ) -> None:
        for view in self._sdk_config.views:
            # pylint: disable=protected-access
            if not view._match(instrument):
                continue

            if not self._check_view_instrument_compatibility(view, instrument):
                continue

            new_view_instrument_match = _ViewInstrumentMatch(
                view=view,
                instrument=instrument,
                instrument_class_aggregation=(
                    self._instrument_class_aggregation
                ),
            )

            for (
                existing_view_instrument_matches
            ) in self._instrument_view_instrument_matches.values():
                for (
                    existing_view_instrument_match
                ) in existing_view_instrument_matches:
                    if existing_view_instrument_match.conflicts(
                        new_view_instrument_match
                    ):

                        _logger.warning(
                            "Views %s and %s will cause conflicting "
                            "metrics identities",
                            existing_view_instrument_match._view,
                            new_view_instrument_match._view,
                        )

            view_instrument_matches.append(new_view_instrument_match)

    @staticmethod
    def _check_view_instrument_compatibility(
        view: View, instrument: Instrument
    ) -> bool:
        """
        Checks if a view and an instrument are compatible.

        Returns `true` if they are compatible and a `_ViewInstrumentMatch`
        object should be created, `false` otherwise.
        """

        result = True

        # pylint: disable=protected-access
        if isinstance(instrument, Asynchronous) and isinstance(
            view._aggregation, ExplicitBucketHistogramAggregation
        ):
            _logger.warning(
                "View %s and instrument %s will produce "
                "semantic errors when matched, the view "
                "has not been applied.",
                view,
                instrument,
            )
            result = False

        return result