#!/usr/bin/env python

import sys, os, inspect, argparse
from natsort import natsorted
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import lib.library as lib
from Bio import SeqIO
from collections import OrderedDict

#setup menu with argparse
class MyFormatter(argparse.ArgumentDefaultsHelpFormatter):
    def __init__(self, prog):
        super(MyFormatter, self).__init__(prog, max_help_position=48)
parser = argparse.ArgumentParser(prog='gff2prot.py',
    description = '''Script to convert GFF3 and FASTA to tbl, proteins, transcripts.''',
    epilog = """Written by Jon Palmer (2018) nextgenusfs@gmail.com""",
    formatter_class = MyFormatter)
parser.add_argument('-g', '--gff3', required=True, help='Genome annotation GFF3 format')
parser.add_argument('-f', '--fasta', required=True, help='Genome in FASTA format')
args=parser.parse_args()

def scaffold2Dict(input):
    #get scaffold names/lengths
    scaffLen = {}
    with open(input, 'rU') as seqin:
        for record in SeqIO.parse(seqin, 'fasta'):
            if not record.id in scaffLen:
                scaffLen[record.id] = len(record.seq)
    return scaffLen

def dict2tbl(geneDict, scaffDict):
    def _sortDict(d):
        return (d[1]['contig'], d[1]['location'][0])
    #get ordered dict to get genes in proper location
    sGenes = sorted(Genes.iteritems(), key=_sortDict)
    sortedGenes = OrderedDict(sGenes)
    scaff2genes = {}
    for k,v in sortedGenes.items():
        if not v['contig'] in scaff2genes:
            scaff2genes[v['contig']] = [k]
        else:
            scaff2genes[v['contig']].append(k)
    #now have scaffolds dict and gene dict, loop through scaff dict printing tbl
    for k,v in natsorted(scaff2genes.items()):
        sys.stdout.write('>Feature %s\n' % k)
        sys.stdout.write('1\t%s\tREFERENCE\n' % scaffDict.get(k))
        sys.stdout.write('\t\t\t%s\t%s\n' % ('CFMR', '12345'))
        for genes in v: #now loop through each gene on the scaffold
            geneInfo = geneDict.get(genes)
            #check for partial models
            if True in geneInfo['partialStart']:
                partialStart = '<'
            else:
                partialStart = ''
            if True in geneInfo['partialStop']:
                partialStop = '>'
            else:
                partialStop = ''
            #now write gene model
            if geneInfo['strand'] == '+':
                sys.stdout.write('%s%i\t%s%i\tgene\n' % (partialStart, geneInfo['location'][0], partialStop, geneInfo['location'][1]))
            else:
                sys.stdout.write('%s%i\t%s%i\tgene\n' % (partialStart, geneInfo['location'][1], partialStop, geneInfo['location'][0]))
            if geneInfo['name']:
            	sys.stdout.write('\t\t\tgene\t%s\n' % geneInfo['name'])
            sys.stdout.write('\t\t\tlocus_tag\t%s\n' % genes)
            #support multiple transcripts
            for i in range(0,len(geneInfo['ids'])):
                if geneInfo['type'] == 'mRNA':
                    if geneInfo['partialStart'][i] == False:
                        partialStart = ''
                    else:
                        partialStart = '<'
                    if geneInfo['partialStop'][i] == False:
                        partialStop = ''
                    else:
                        partialStop = '>'
                    if geneInfo['strand'] == '+':
                        for num, exon in enumerate(geneInfo['mRNA'][i]):
                            if num == 0 and num == len(geneInfo['mRNA'][i]) - 1: #single exon, so slightly differnt method
                                sys.stdout.write('%s%s\t%s%s\tmRNA\n' % (partialStart, exon[0], partialStop, exon[1]))
                            elif num == 0:
                                sys.stdout.write('%s%s\t%s\tmRNA\n' % (partialStart, exon[0], exon[1]))
                            elif num == len(geneInfo['mRNA'][i]) - 1: #this is last one
                                sys.stdout.write('%s\t%s%s\n' % (exon[0], partialStop, exon[1]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (exon[0], exon[1]))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        sys.stdout.write('\t\t\ttranscript_id\tgnl|ncbi|%s-T%i_mrna\n' % (genes,i+1))
                        sys.stdout.write('\t\t\tprotein_id\tgnl|ncbi|%s-T%i\n' % (genes, i+1))
                        for num, cds in enumerate(geneInfo['CDS'][i]):
                            if num == 0 and num == len(geneInfo['CDS'][i]) - 1: #single exon, so slightly differnt method
                                sys.stdout.write('%s%s\t%s%s\tCDS\n' % (partialStart, cds[0], partialStop, cds[1]))
                            elif num == 0:
                                sys.stdout.write('%s%s\t%s\tCDS\n' % (partialStart, cds[0], cds[1]))
                            elif num == len(geneInfo['CDS'][i]) - 1: #this is last one
                                sys.stdout.write('%s\t%s%s\n' % (cds[0], partialStop, cds[1]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (cds[0], cds[1]))
                        sys.stdout.write('\t\t\tcodon_start\t%i\n' % geneInfo['codon_start'][i])
                        if geneInfo['db_xref'][i]:
                        	for x in geneInfo['db_xref'][i]:
                        		sys.stdout.write('\t\t\tdb_xref\t%s\n' % x)
                        if geneInfo['note'][i]:
                        	for x in geneInfo['note'][i]:
                        		sys.stdout.write('\t\t\tnote\t%s\n' % x)
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        sys.stdout.write('\t\t\ttranscript_id\tgnl|ncbi|%s-T%i_mrna\n' % (genes,i+1))
                        sys.stdout.write('\t\t\tprotein_id\tgnl|ncbi|%s-T%i\n' % (genes,i+1))
                    else:
                        for num, exon in enumerate(geneInfo['mRNA'][i]):
                            if num == 0 and num == len(geneInfo['mRNA'][i]) - 1: #single exon, so slightly differnt method
                                sys.stdout.write('%s%s\t%s%s\tmRNA\n' % (partialStart, exon[1], partialStop, exon[0]))
                            elif num == 0:
                                sys.stdout.write('%s%s\t%s\tmRNA\n' % (partialStart, exon[1], exon[0]))
                            elif num == len(geneInfo['mRNA']) - 1: #this is last one
                                sys.stdout.write('%s\t%s%s\n' % (exon[1], partialStop, exon[0]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (exon[1], exon[0]))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        sys.stdout.write('\t\t\ttranscript_id\tgnl|ncbi|%s-T%i_mrna\n' % (genes,i+1))
                        sys.stdout.write('\t\t\tprotein_id\tgnl|ncbi|%s-T%i\n' % (genes,i+1))
                        for num, cds in enumerate(geneInfo['CDS'][i]):
                            if num == 0 and num == len(geneInfo['CDS'][i]) - 1: #single exon, so slightly differnt method
                                sys.stdout.write('%s%s\t%s%s\tCDS\n' % (partialStart, cds[1], partialStop, cds[0]))
                            elif num == 0:
                                sys.stdout.write('%s%s\t%s\tCDS\n' % (partialStart, cds[1], cds[0]))
                            elif num == len(geneInfo['CDS'][i]) - 1: #this is last one
                                sys.stdout.write('%s\t%s%s\n' % (cds[1], partialStop, cds[0]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (cds[1], cds[0]))
                        sys.stdout.write('\t\t\tcodon_start\t%i\n' % geneInfo['codon_start'][i])
                        if geneInfo['db_xref'][i]:
                        	for x in geneInfo['db_xref'][i]:
                        		sys.stdout.write('\t\t\tdb_xref\t%s\n' % x)
                        if geneInfo['note'][i]:
                        	for x in geneInfo['note'][i]:
                        		sys.stdout.write('\t\t\tnote\t%s\n' % x)
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        sys.stdout.write('\t\t\ttranscript_id\tgnl|ncbi|%s-T%i_mrna\n' % (genes,i+1))
                        sys.stdout.write('\t\t\tprotein_id\tgnl|ncbi|%s-T%i\n' % (genes,i+1))
                elif geneInfo['type'] == 'tRNA':
                    if geneInfo['strand'] == '+':
                        for num, exon in enumerate(geneInfo['mRNA'][i]):
                            if num == 0:
                                sys.stdout.write('<%s\t>%s\ttRNA\n' % (exon[0], exon[1]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (exon[0], exon[1]))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        if geneInfo['product'] == 'tRNA-Xxx':
                            sys.stdout.write('\t\t\tpseudo\n')
                        if geneInfo['note'] != '':
                            sys.stdout.write('\t\t\tnote\t%s\n' % geneInfo['note'][i])
                    else:
                        sys.stdout.write('<%i\t>%i\tgene\n' % (geneInfo['end'], geneInfo['start']))
                        sys.stdout.write('\t\t\tlocus_tag\t%s\n' % genes)
                        for num, exon in enumerate(geneInfo['mRNA'][i]):
                            if num == 0:
                                sys.stdout.write('<%s\t>%s\ttRNA\n' % (exon[1], exon[0]))
                            else:
                                sys.stdout.write('%s\t%s\n' % (exon[1], exon[0]))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                        if geneInfo['product'] == 'tRNA-Xxx':
                            sys.stdout.write('\t\t\tpseudo\n')
                        if geneInfo['note'] != '':
                            sys.stdout.write('\t\t\tnote\t%s\n' % geneInfo['note'][i])
                elif geneInfo['type'] == 'rRNA':
                    if geneInfo['strand'] == '+':
                        sys.stdout.write('<%s\t>%s\t%s\n' % (geneInfo['location'][0],geneInfo['location'][1], geneInfo['type']))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])
                    else:
                        sys.stdout.write('<%s\t>%s\t%s\n' % (geneInfo['location'][1],geneInfo['location'][0], geneInfo['type']))
                        sys.stdout.write('\t\t\tproduct\t%s\n' % geneInfo['product'][i])

#load into dictionary
Genes = {}
Genes = lib.gff2dict(args.gff3, args.fasta, Genes)
scaffLen = scaffold2Dict(args.fasta)
dict2tbl(Genes, scaffLen)


from typing import List, Any
from unittest import TestCase

from scuti.domain.cqrs.bus.effect_handler import ManagedStateEffectHandler
from scuti.domain.cqrs.effects import Effect
from scuti.infrastructure.tools.list import filter_none

class EffectHandlerTestCase(TestCase):
    def feed_effects(self, into: ManagedStateEffectHandler, effects: List[Effect], initial_state: Any = "None"):
        current_state = initial_state
        emitted_effects = []
        for effect in effects:
            if current_state != "None":
                state, effects = into.handle(current_state, effect)
            else:
                state, effects = into.handle(effect)
            current_state = state
            emitted_effects += filter_none(effects)
        return current_state, emitted_effects


# 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)))


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


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}"


from __future__ import annotations

from typing import Dict, List, Optional, Union

from boa3.internal.compiler.codegenerator.methodtokencollection import MethodTokenCollection
from boa3.internal.compiler.codegenerator.vmcodemap import VMCodeMap
from boa3.internal.compiler.compileroutput import CompilerOutput
from boa3.internal.model.builtin.method import IBuiltinMethod
from boa3.internal.neo.vm.VMCode import VMCode
from boa3.internal.neo.vm.opcode import OpcodeHelper
from boa3.internal.neo.vm.opcode.OpcodeInformation import OpcodeInformation
from boa3.internal.neo3.contracts.contracttypes import CallFlags

class VMCodeMapping:
    """
    This class is responsible for managing the Neo VM instruction during the bytecode generation.
    """
    _instance: VMCodeMapping = None

    @classmethod
    def instance(cls):
        """
        :return: the singleton instance
        """
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance

    def __init__(self):
        self._code_map: VMCodeMap = VMCodeMap()
        self._method_tokens: MethodTokenCollection = MethodTokenCollection()

    @classmethod
    def reset(cls):
        """
        Resets the map to the first state
        """
        if cls._instance is not None:
            cls._instance._code_map.clear()
            cls._instance._method_tokens.clear()

    def add_method_token(self, method: IBuiltinMethod, call_flag: CallFlags) -> Optional[int]:
        """
        Creates a new method token if the method call another contract and return its id.
        Otherwise, returns None
        """
        if hasattr(method, 'contract_script_hash'):
            return self._method_tokens.append(method, call_flag)
        return None

    def get_method_token(self, method_token_id: int):
        """
        Returns the method token with given id if it exists.
        Otherwise, returns None

        :rtype: boa3.internal.neo3.contracts.nef.MethodToken or None
        """
        return self._method_tokens[method_token_id]

    @property
    def codes(self) -> List[VMCode]:
        """
        Gets a list with the included vm codes

        :return: a list of vm codes ordered by its address in the bytecode
        """
        return self._code_map.get_code_list()

    @property
    def code_map(self) -> Dict[int, VMCode]:
        """
        Gets a dictionary that maps each vm code with its address.

        :return: a dictionary that maps each instruction with its address. The keys are ordered by the address.
        """
        return self._code_map.get_code_map()

    def targeted_address(self) -> Dict[int, List[int]]:
        """
        Gets a dictionary that maps each address to the opcodes that targets it

        :return: a dictionary that maps the targeted instructions to its source.
        """
        target_maps = {}
        for code in self._code_map.get_code_with_target_list():
            if code.target is not None and code.target is not code:
                address = self.get_start_address(code)
                target = self.get_start_address(code.target)
                if target not in target_maps:
                    target_maps[target] = [address]
                else:
                    target_maps[target].append(address)
        return target_maps

    def bytecode(self) -> bytes:
        """
        Gets the bytecode of the translated code

        :return: the generated bytecode
        """
        self._remove_empty_targets()
        self._update_larger_codes()

        bytecode = bytearray()
        for code in self.codes:
            bytecode += code.opcode
            if code.data is not None:
                bytecode += code.data
        return bytes(bytecode)

    def result(self) -> CompilerOutput:
        """
        Gets the complete output of the translated code
        """
        bytecode = self.bytecode()
        return CompilerOutput(bytecode, self._method_tokens.to_list())

    @property
    def bytecode_size(self) -> int:
        return self._code_map.get_bytecode_size()

    def insert_code(self, vm_code: VMCode):
        return self._code_map.insert_code(vm_code, has_target=OpcodeHelper.has_target(vm_code.opcode))

    def get_code(self, address: int) -> Optional[VMCode]:
        """
        Gets the VM Opcode at the given position

        :param address: the position of the opcode
        :return: the opcode if it exists. None otherwise
        :rtype: VMCode or None
        """
        return self._code_map.get_code(address)

    def get_addresses(self, start_address: int, end_address: int) -> List[int]:
        return self._code_map.get_addresses(start_address, end_address)

    def get_start_address(self, vm_code: VMCode) -> int:
        """
        Gets the vm code's first byte address

        :param vm_code: the instruction to get the address
        :return: the vm code's address if it's in the map. Otherwise, return's zero.
        """
        return self._code_map.get_start_address(vm_code)

    def get_end_address(self, vm_code: VMCode) -> int:
        """
        Gets the vm code's last byte address

        :param vm_code: the instruction to get the address
        :return: the vm code's last address if it's in the map. Otherwise, return's zero.
        """
        return self._code_map.get_end_address(vm_code)

    def get_opcodes(self, addresses: List[int]) -> List[VMCode]:
        return self._code_map.get_opcodes(addresses)

    def update_vm_code(self, vm_code: VMCode, opcode: OpcodeInformation, data: bytes = bytes()):
        """
        Updates the information from an inserted code

        :param vm_code: code to be updated
        :param opcode: updated opcode information
        :param data: updated opcode data
        """
        code_size = vm_code.size
        vm_code._info = opcode
        vm_code._data = data
        if vm_code.size != code_size:
            self._update_addresses(self.get_start_address(vm_code))

    def _update_addresses(self, start_address: int = 0):
        """
        Updates the instruction map's keys when a opcode is changed

        :param start_address: the address from the changed opcode
        """
        return self._code_map.update_addresses(start_address)

    def _update_targets(self):
        from boa3.internal.neo.vm.type.Integer import Integer
        for code in self._code_map.get_code_with_target_list():
            if code.target is None:
                relative = Integer.from_bytes(code.data)
                absolute = self._code_map.get_start_address(code) + relative
                if absolute in self.code_map:
                    code.set_target(self.code_map[absolute])

    def _update_larger_codes(self):
        """
        Checks if each instruction data fits in its opcode maximum size and updates the opcode from those that don't
        """
        # gets a list with all instructions which its opcode has a larger equivalent, ordered by its address
        instr_with_small_codes = [code for code in self._code_map.get_code_list() if OpcodeHelper.has_larger_opcode(code.opcode)]
        instr_with_small_codes.sort(key=lambda code: self.get_start_address(code), reverse=True)

        from boa3.internal.neo.vm.opcode.OpcodeInfo import OpcodeInfo
        # total_len is initialized with zero because the loop must run at least once
        total_len = 0
        current_size = self.bytecode_size

        # if any instruction is updated, the following instruction addresses and the total size will change as well
        # with the change, previous instruction data may have overflowed the opcode maximum value
        # to make sure, it must check the opcodes that haven't changed again
        while total_len != current_size:
            total_len = current_size

            # verifies each instruction data length
            for code in instr_with_small_codes.copy():  # it's a copy because the list may change during the iteration
                if len(code.raw_data) > code.info.max_data_len:
                    # gets the shortest opcode equivalent that fits the instruction data
                    info = OpcodeInfo.get_info(OpcodeHelper.get_larger_opcode(code.opcode))
                    while len(code.raw_data) > info.max_data_len and OpcodeHelper.has_larger_opcode(info.opcode):
                        info = OpcodeInfo.get_info(OpcodeHelper.get_larger_opcode(code.opcode))

                    self.update_vm_code(code, info)
                    if info.opcode == OpcodeHelper.get_larger_opcode(info.opcode):
                        # if it's the largest equivalent, it won't be updated anymore
                        instr_with_small_codes.remove(code)
            current_size = self.bytecode_size

    def _validate_targets(self, code_or_address: Union[int, VMCode]):
        if isinstance(code_or_address, int):
            address = code_or_address
            code = self.get_code(address)
        else:
            code = code_or_address
            address = self.get_start_address(code)

        targeted_addresses = self.targeted_address()

        if address in targeted_addresses:
            next_address = self.get_end_address(code) + 1
            if next_address < self.bytecode_size:
                next_code = self._code_map.get_code(next_address)
                for source in targeted_addresses[address]:
                    self._code_map.get_code(source).set_target(next_code)

    def move_to_end(self, first_code_address: int, last_code_address: int) -> int:
        """
        Moves a set of instructions to the end of the current bytecode

        :param first_code_address: first instruction start address
        :param last_code_address: last instruction end address
        """
        result = self._code_map.move_to_end(first_code_address, last_code_address)
        if not isinstance(result, int):
            return self.bytecode_size

        self._update_targets()
        return result

    def remove_opcodes(self, first_code_address: int, last_code_address: int = None):
        if not isinstance(last_code_address, int):
            last_code_address = self.bytecode_size
        addresses_to_remove = self._code_map.get_addresses(first_code_address, last_code_address)
        for address in addresses_to_remove:
            self._validate_targets(address)
        return self._code_map.remove_opcodes_by_addresses(addresses_to_remove)

    def remove_opcodes_by_code(self, codes: List[VMCode]):
        addresses_to_remove = self._code_map.get_addresses_from_codes(codes)
        for address in addresses_to_remove:
            self._validate_targets(address)
        return self._code_map.remove_opcodes_by_addresses(addresses_to_remove)

    def _remove_empty_targets(self):
        """
        Checks if each instruction that requires a target has one set and remove those that don't
        """
        addresses_to_remove = []
        for code in self._code_map.get_code_with_target_list():
            if code.target is None or code.target is code:
                address = self.get_start_address(code)
                self._validate_targets(address)
                addresses_to_remove.append(address)

        if len(addresses_to_remove) > 0:
            self._code_map.remove_opcodes_by_addresses(addresses_to_remove)


"""mobiledetails URL Configuration

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

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.shortcuts import render
from django.urls import path
from .views import mobile_registration,signin,signout,create_mobile,mobile_list,mobile_view,status_Check,sucess,payment,mobile_edit,loginpage,mainlist
urlpatterns = [
path('', lambda request: render(request, "mobile/base.html")),
   path('register',mobile_registration,name="register"),
   path("signin",signin,name="signin"),
   path("signout",signout,name="signout"),
path("create",create_mobile,name="create"),
   path("list",mobile_list,name="list"),
   path("view/<int:id>",mobile_view,name="view"),
   path("status",status_Check,name="status"),
   path('success',sucess,name="sucess"),
   path('pay',payment,name="pay"),
   path("edit/<int:pk>",mobile_edit,name="edit"),
   path("login",loginpage,name="login"),
   path("mainlist",mainlist,name="mainlist")

]


import os
import unittest
from collections import OrderedDict
from unittest import mock

import opentelemetry.exporter.jaeger.proto.grpc.translate as pb_translator
from opentelemetry import trace as trace_api
from opentelemetry.exporter.jaeger.proto.grpc import JaegerExporter

# pylint:disable=no-name-in-module
# pylint:disable=import-error
from opentelemetry.exporter.jaeger.proto.grpc.gen import model_pb2
from opentelemetry.exporter.jaeger.proto.grpc.translate import (
    _SCOPE_NAME_KEY,
    _SCOPE_VERSION_KEY,
    NAME_KEY,
    VERSION_KEY,
    Translate,
)
from opentelemetry.sdk import trace
from opentelemetry.sdk.environment_variables import (
    OTEL_EXPORTER_JAEGER_CERTIFICATE,
    OTEL_EXPORTER_JAEGER_ENDPOINT,
    OTEL_EXPORTER_JAEGER_GRPC_INSECURE,
    OTEL_EXPORTER_JAEGER_TIMEOUT,
    OTEL_RESOURCE_ATTRIBUTES,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SpanExportResult
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
from opentelemetry.test.spantestutil import (
    get_span_with_dropped_attributes_events_links,
)
from opentelemetry.trace.status import Status, StatusCode

def _translate_spans_with_dropped_attributes():
    span = get_span_with_dropped_attributes_events_links()
    translate = Translate([span])

    # pylint: disable=protected-access
    return translate._translate(pb_translator.ProtobufTranslator("svc"))

# pylint:disable=no-member
class TestJaegerExporter(unittest.TestCase):
    def setUp(self):
        # create and save span to be used in tests
        self.context = trace_api.SpanContext(
            trace_id=0x000000000000000000000000DEADBEEF,
            span_id=0x00000000DEADBEF0,
            is_remote=False,
        )

        self._test_span = trace._Span("test_span", context=self.context)
        self._test_span.start()
        self._test_span.end()

        # pylint: disable=protected-access

    def test_constructor_by_environment_variables(self):
        """Test using Environment Variables."""
        # pylint: disable=protected-access
        service = "my-opentelemetry-jaeger"

        collector_endpoint = "localhost:14250"

        env_patch = mock.patch.dict(
            "os.environ",
            {
                OTEL_EXPORTER_JAEGER_ENDPOINT: collector_endpoint,
                OTEL_EXPORTER_JAEGER_CERTIFICATE: os.path.dirname(__file__)
                + "/certs/cred.cert",
                OTEL_RESOURCE_ATTRIBUTES: "service.name=my-opentelemetry-jaeger",
                OTEL_EXPORTER_JAEGER_TIMEOUT: "5",
                OTEL_EXPORTER_JAEGER_GRPC_INSECURE: "False",
            },
        )

        env_patch.start()
        provider = TracerProvider(resource=Resource.create({}))
        trace_api.set_tracer_provider(provider)
        exporter = JaegerExporter()
        self.assertEqual(exporter.service_name, service)
        self.assertIsNotNone(exporter._collector_grpc_client)
        self.assertEqual(exporter.collector_endpoint, collector_endpoint)
        self.assertEqual(exporter._timeout, 5)
        self.assertIsNotNone(exporter.credentials)
        self.assertEqual(exporter.insecure, False)
        env_patch.stop()

    # pylint: disable=too-many-locals,too-many-statements
    def test_translate_to_jaeger(self):

        span_names = ("test1", "test2", "test3")
        trace_id = 0x6E0C63257DE34C926F9EFCD03927272E
        span_id = 0x34BF92DEEFC58C92
        parent_id = 0x1111111111111111
        other_id = 0x2222222222222222

        base_time = 683647322 * 10**9  # in ns
        start_times = (
            base_time,
            base_time + 150 * 10**6,
            base_time + 300 * 10**6,
        )
        durations = (50 * 10**6, 100 * 10**6, 200 * 10**6)
        end_times = (
            start_times[0] + durations[0],
            start_times[1] + durations[1],
            start_times[2] + durations[2],
        )

        span_context = trace_api.SpanContext(
            trace_id, span_id, is_remote=False
        )
        parent_span_context = trace_api.SpanContext(
            trace_id, parent_id, is_remote=False
        )
        other_context = trace_api.SpanContext(
            trace_id, other_id, is_remote=False
        )

        event_attributes = OrderedDict(
            [
                ("annotation_bool", True),
                ("annotation_string", "annotation_test"),
                ("key_float", 0.3),
            ]
        )

        event_timestamp = base_time + 50 * 10**6
        # pylint:disable=protected-access
        event_timestamp_proto = (
            pb_translator._proto_timestamp_from_epoch_nanos(event_timestamp)
        )

        event = trace.Event(
            name="event0",
            timestamp=event_timestamp,
            attributes=event_attributes,
        )

        link_attributes = {"key_bool": True}

        link = trace_api.Link(
            context=other_context, attributes=link_attributes
        )

        default_tags = [
            model_pb2.KeyValue(
                key="span.kind",
                v_type=model_pb2.ValueType.STRING,
                v_str="internal",
            ),
        ]

        otel_spans = [
            trace._Span(
                name=span_names[0],
                context=span_context,
                parent=parent_span_context,
                events=(event,),
                links=(link,),
                kind=trace_api.SpanKind.CLIENT,
                resource=Resource(
                    attributes={"key_resource": "some_resource"}
                ),
            ),
            trace._Span(
                name=span_names[1],
                context=parent_span_context,
                parent=None,
                resource=Resource({}),
            ),
            trace._Span(
                name=span_names[2],
                context=other_context,
                parent=None,
                resource=Resource({}),
                instrumentation_scope=InstrumentationScope(
                    name="name", version="version"
                ),
            ),
        ]

        otel_spans[0].start(start_time=start_times[0])
        # added here to preserve order
        otel_spans[0].set_attribute("key_bool", False)
        otel_spans[0].set_attribute("key_string", "hello_world")
        otel_spans[0].set_attribute("key_float", 111.22)
        otel_spans[0].set_attribute("key_tuple", ("tuple_element",))
        otel_spans[0].set_status(
            Status(StatusCode.ERROR, "Example description")
        )
        otel_spans[0].end(end_time=end_times[0])

        otel_spans[1].start(start_time=start_times[1])
        otel_spans[1].end(end_time=end_times[1])

        otel_spans[2].start(start_time=start_times[2])
        otel_spans[2].set_status(Status(StatusCode.OK))
        otel_spans[2].end(end_time=end_times[2])

        translate = Translate(otel_spans)
        # pylint: disable=protected-access
        spans = translate._translate(pb_translator.ProtobufTranslator("svc"))

        span1_start_time = pb_translator._proto_timestamp_from_epoch_nanos(
            start_times[0]
        )
        span2_start_time = pb_translator._proto_timestamp_from_epoch_nanos(
            start_times[1]
        )
        span3_start_time = pb_translator._proto_timestamp_from_epoch_nanos(
            start_times[2]
        )

        span1_end_time = pb_translator._proto_timestamp_from_epoch_nanos(
            end_times[0]
        )
        span2_end_time = pb_translator._proto_timestamp_from_epoch_nanos(
            end_times[1]
        )
        span3_end_time = pb_translator._proto_timestamp_from_epoch_nanos(
            end_times[2]
        )

        span1_duration = pb_translator._duration_from_two_time_stamps(
            span1_start_time, span1_end_time
        )
        span2_duration = pb_translator._duration_from_two_time_stamps(
            span2_start_time, span2_end_time
        )
        span3_duration = pb_translator._duration_from_two_time_stamps(
            span3_start_time, span3_end_time
        )

        expected_spans = [
            model_pb2.Span(
                operation_name=span_names[0],
                trace_id=pb_translator._trace_id_to_bytes(trace_id),
                span_id=pb_translator._span_id_to_bytes(span_id),
                start_time=span1_start_time,
                duration=span1_duration,
                flags=0,
                tags=[
                    model_pb2.KeyValue(
                        key="key_bool",
                        v_type=model_pb2.ValueType.BOOL,
                        v_bool=False,
                    ),
                    model_pb2.KeyValue(
                        key="key_string",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="hello_world",
                    ),
                    model_pb2.KeyValue(
                        key="key_float",
                        v_type=model_pb2.ValueType.FLOAT64,
                        v_float64=111.22,
                    ),
                    model_pb2.KeyValue(
                        key="key_tuple",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="('tuple_element',)",
                    ),
                    model_pb2.KeyValue(
                        key="key_resource",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="some_resource",
                    ),
                    model_pb2.KeyValue(
                        key="otel.status_code",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="ERROR",
                    ),
                    model_pb2.KeyValue(
                        key="otel.status_description",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="Example description",
                    ),
                    model_pb2.KeyValue(
                        key="span.kind",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="client",
                    ),
                    model_pb2.KeyValue(
                        key="error",
                        v_type=model_pb2.ValueType.BOOL,
                        v_bool=True,
                    ),
                ],
                references=[
                    model_pb2.SpanRef(
                        ref_type=model_pb2.SpanRefType.CHILD_OF,
                        trace_id=pb_translator._trace_id_to_bytes(trace_id),
                        span_id=pb_translator._span_id_to_bytes(parent_id),
                    ),
                    model_pb2.SpanRef(
                        ref_type=model_pb2.SpanRefType.FOLLOWS_FROM,
                        trace_id=pb_translator._trace_id_to_bytes(trace_id),
                        span_id=pb_translator._span_id_to_bytes(other_id),
                    ),
                ],
                logs=[
                    model_pb2.Log(
                        timestamp=event_timestamp_proto,
                        fields=[
                            model_pb2.KeyValue(
                                key="annotation_bool",
                                v_type=model_pb2.ValueType.BOOL,
                                v_bool=True,
                            ),
                            model_pb2.KeyValue(
                                key="annotation_string",
                                v_type=model_pb2.ValueType.STRING,
                                v_str="annotation_test",
                            ),
                            model_pb2.KeyValue(
                                key="key_float",
                                v_type=model_pb2.ValueType.FLOAT64,
                                v_float64=0.3,
                            ),
                            model_pb2.KeyValue(
                                key="message",
                                v_type=model_pb2.ValueType.STRING,
                                v_str="event0",
                            ),
                        ],
                    )
                ],
                process=model_pb2.Process(
                    service_name="svc",
                    tags=[
                        model_pb2.KeyValue(
                            key="key_resource",
                            v_str="some_resource",
                            v_type=model_pb2.ValueType.STRING,
                        )
                    ],
                ),
            ),
            model_pb2.Span(
                operation_name=span_names[1],
                trace_id=pb_translator._trace_id_to_bytes(trace_id),
                span_id=pb_translator._span_id_to_bytes(parent_id),
                start_time=span2_start_time,
                duration=span2_duration,
                flags=0,
                tags=default_tags,
                process=model_pb2.Process(
                    service_name="svc",
                ),
            ),
            model_pb2.Span(
                operation_name=span_names[2],
                trace_id=pb_translator._trace_id_to_bytes(trace_id),
                span_id=pb_translator._span_id_to_bytes(other_id),
                start_time=span3_start_time,
                duration=span3_duration,
                flags=0,
                tags=[
                    model_pb2.KeyValue(
                        key="otel.status_code",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="OK",
                    ),
                    model_pb2.KeyValue(
                        key="span.kind",
                        v_type=model_pb2.ValueType.STRING,
                        v_str="internal",
                    ),
                    model_pb2.KeyValue(
                        key=NAME_KEY,
                        v_type=model_pb2.ValueType.STRING,
                        v_str="name",
                    ),
                    model_pb2.KeyValue(
                        key=VERSION_KEY,
                        v_type=model_pb2.ValueType.STRING,
                        v_str="version",
                    ),
                    model_pb2.KeyValue(
                        key=_SCOPE_NAME_KEY,
                        v_type=model_pb2.ValueType.STRING,
                        v_str="name",
                    ),
                    model_pb2.KeyValue(
                        key=_SCOPE_VERSION_KEY,
                        v_type=model_pb2.ValueType.STRING,
                        v_str="version",
                    ),
                ],
                process=model_pb2.Process(
                    service_name="svc",
                ),
            ),
        ]

        # events are complicated to compare because order of fields
        # (attributes) in otel is not important but in jeager it is
        # pylint: disable=no-member
        self.assertCountEqual(
            spans[0].logs[0].fields,
            expected_spans[0].logs[0].fields,
        )

        self.assertEqual(spans, expected_spans)

    def test_max_tag_value_length(self):
        span = trace._Span(
            name="span",
            resource=Resource(
                attributes={
                    "key_resource": "some_resource some_resource some_more_resource"
                }
            ),
            context=trace_api.SpanContext(
                trace_id=0x000000000000000000000000DEADBEEF,
                span_id=0x00000000DEADBEF0,
                is_remote=False,
            ),
        )

        span.start()
        span.set_attribute("key_bool", False)
        span.set_attribute("key_string", "hello_world hello_world hello_world")
        span.set_attribute("key_float", 111.22)
        span.set_attribute("key_int", 1100)
        span.set_attribute("key_tuple", ("tuple_element", "tuple_element2"))
        span.end()

        translate = Translate([span])

        # does not truncate by default
        # pylint: disable=protected-access
        spans = translate._translate(pb_translator.ProtobufTranslator("svc"))
        tags_by_keys = {
            tag.key: tag.v_str
            for tag in spans[0].tags
            if tag.v_type == model_pb2.ValueType.STRING
        }
        self.assertEqual(
            "hello_world hello_world hello_world", tags_by_keys["key_string"]
        )
        self.assertEqual(
            "('tuple_element', 'tuple_element2')", tags_by_keys["key_tuple"]
        )
        self.assertEqual(
            "some_resource some_resource some_more_resource",
            tags_by_keys["key_resource"],
        )

        # truncates when max_tag_value_length is passed
        # pylint: disable=protected-access
        spans = translate._translate(
            pb_translator.ProtobufTranslator("svc", max_tag_value_length=5)
        )
        tags_by_keys = {
            tag.key: tag.v_str
            for tag in spans[0].tags
            if tag.v_type == model_pb2.ValueType.STRING
        }
        self.assertEqual("hello", tags_by_keys["key_string"])
        self.assertEqual("('tup", tags_by_keys["key_tuple"])
        self.assertEqual("some_", tags_by_keys["key_resource"])

    def test_export(self):
        client_mock = mock.Mock()
        spans = []
        exporter = JaegerExporter()
        exporter._grpc_client = client_mock
        status = exporter.export(spans)
        self.assertEqual(SpanExportResult.SUCCESS, status)

    def test_export_span_service_name(self):
        resource = Resource.create({SERVICE_NAME: "test"})
        span = trace._Span(
            "test_span", context=self.context, resource=resource
        )
        span.start()
        span.end()
        client_mock = mock.Mock()
        exporter = JaegerExporter()
        exporter._grpc_client = client_mock
        exporter.export([span])
        self.assertEqual(exporter.service_name, "test")

    def test_dropped_span_attributes(self):
        spans = _translate_spans_with_dropped_attributes()
        tags_by_keys = {
            tag.key: tag.v_str or tag.v_int64 for tag in spans[0].tags
        }
        self.assertEqual(1, tags_by_keys["otel.dropped_links_count"])
        self.assertEqual(2, tags_by_keys["otel.dropped_attributes_count"])
        self.assertEqual(3, tags_by_keys["otel.dropped_events_count"])

    def test_dropped_event_attributes(self):
        spans = _translate_spans_with_dropped_attributes()
        fields_by_keys = {
            tag.key: tag.v_str or tag.v_int64
            for tag in spans[0].logs[0].fields
        }
        # get events
        self.assertEqual(
            2,
            fields_by_keys["otel.dropped_attributes_count"],
        )


# -*- 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)


import requests
import re
import logging
from bs4 import BeautifulSoup

logger = logging.getLogger('scraping.all_books_page')

class BookWebPageLocator:
    WEB_PAGE_NUMBER = 'div ul.pager li.current'
    WEB_PAGE_URL = 'div ul.pager li.next a'

class BookPageURL:
    def __init__(self, web_link):
        logger.debug('Parsing page content with BeautifulSoup HTML parser. ')
        self.web_link = web_link
        self.page_content = requests.get(self.web_link).content
        self.soup = BeautifulSoup(self.page_content, 'html.parser')

    @property
    def web_url(self):  # Return part of URL /page-2.html
        return self.soup.select_one(BookWebPageLocator.WEB_PAGE_URL).attrs['href']

    @property
    def pages_number(self):  # Return an integer the total pages numbers
        logger.debug('Finding all number of catalogue pages available...')
        return int(re.findall('[0-9]+', self.soup.select_one(BookWebPageLocator.WEB_PAGE_NUMBER).string)[1])


''' 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()


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]


#! /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)


# -*- 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 pika

import urllib.request

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

connection = pika.BlockingConnection(pika.ConnectionParameters(external_ip, credentials=pika.PlainCredentials("ubuntu", "ubuntu")
                                                               ))
channel = connection.channel()
channel.exchange_declare("events", exchange_type="fanout")
channel.exchange_declare("chat", exchange_type="fanout")

Car Racing Game using Pygame/server_init.py


import os
from pathlib import Path

def write(file_name, content):
    Path(os.path.dirname(file_name)).mkdir(parents=True, exist_ok=True)
    with open(file_name, 'w') as file:
        file.write(content)

def read_line_looping(file_name, count):
    i = 0
    lines = []
    file = open(file_name, 'r')
    line = file.readline()
    if line == '':
        raise EmptyFileError(f'Error: Dictionary {file_name} seems to be empty')
    while i < count:
        lines.append(line.strip())
        i += 1
        line = file.readline()
        if line == '':
            file.close()
            file = open(file_name, 'r')
            line = file.readline()
    file.close()
    return lines

class EmptyFileError(Exception):
    pass


import cv2
import numpy as np

class ObjectTracker:
    def __init__(self):
        self.trackers = None
        self.boxes = None

    def reset_trackers(self):
        # grab the appropriate object tracker using our dictionary of
        # OpenCV object tracker objects
        trackers = cv2.MultiTracker_create()
        self.trackers = trackers
        return trackers

    def add_new_trackers(self, current_obs, boxes, track_algo='csrt'):
        for box in boxes:
            self.add_new_tracker(current_obs, box, track_algo)

    def add_new_tracker(self, current_obs, box, track_algo='csrt'):
        # initialize a dictionary that maps strings to their corresponding
        # OpenCV object tracker implementations
        OPENCV_OBJECT_TRACKERS = {
            "csrt": cv2.TrackerCSRT_create,
            "kcf": cv2.TrackerKCF_create,
            "boosting": cv2.TrackerBoosting_create,
            "mil": cv2.TrackerMIL_create,
            "tld": cv2.TrackerTLD_create,
            "medianflow": cv2.TrackerMedianFlow_create,
            "mosse": cv2.TrackerMOSSE_create
        }
        new_tracker = OPENCV_OBJECT_TRACKERS[track_algo]()
        self.trackers.add(new_tracker, current_obs, box)

    def _get_bounding_box(self, obs, color):
        """ Calculates the bounding box of a ndarray"""
        mask = np.all(obs == color, axis=-1)
        rows = np.any(mask, axis=0)
        cols = np.any(mask, axis=1)

        if len(np.where(rows)[0]) == 0 or len(np.where(cols)[0]) == 0:
            return None
        rmin, rmax = np.where(rows)[0][[0, -1]]
        cmin, cmax = np.where(cols)[0][[0, -1]]

        return [rmin, cmin, rmax-rmin, cmax-cmin]

    def _get_key_pickup_bounding_box(self, obs):
        key_pickup_agent_color = (127, 127, 127)
        key_pickup_key_color = (0, 0, 255)
        key_pickup_door_color = (0, 0, 0)

        boxes = []
        for color in [key_pickup_agent_color, key_pickup_key_color, key_pickup_door_color]:
            box = self._get_bounding_box(obs, color)
            if box is not None:
                boxes.append(box)
        return boxes

    def update(self, obs):
        (success, boxes) = self.trackers.update(obs)
        self.boxes = boxes
        return success, boxes

    def add_bounding_boxes(self, obs, boxes):
        # no need to call update fn again. just use the boxes.
        for box in boxes:
            (x, y, h, w) = [int(v) for v in box]
            cv2.rectangle(obs, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # as numpy
        return obs


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)


from SCons.Script import COMMAND_LINE_TARGETS
Import("env", "projenv")

# sourceFile = open('saida.txt', 'w')

# print(env.Dump(), file=sourceFile)
# print(projenv.Dump(), file=sourceFile)

# sourceFile.close()

#
# (Optional) Do not run extra script when IDE fetches C/C++ project metadata
#

if "idedata" in COMMAND_LINE_TARGETS:
    print("Saindo do script...")
    env.Exit(0)

def BuildMergeCommands(source, target, env):
    print("Construindo comandos de merge...")

    # Comandos comentados abaixo utilizados para debug#
    ###################################################
    # sourceFile = open('saida.txt', 'w')
    # print(env.Dump(), file=sourceFile)
    # sourceFile.close()

    # print(env['FLASH_EXTRA_IMAGES'])
    # print(len(env['FLASH_EXTRA_IMAGES']))
    ###################################################

    JOINCOMMANDS = [
        "$OBJCOPY",
        "--chip esp32",
        "merge_bin",
        "-o $BUILD_DIR/merged_qemu.bin",
        "--flash_mode dout",
        "--flash_size 4MB",
        "--fill-flash-size 4MB",
        "$ESP32_APP_OFFSET $BUILD_DIR/${PROGNAME}.bin",
    ]

    for i in range(len(env['FLASH_EXTRA_IMAGES'])):
        for j in range(len(env['FLASH_EXTRA_IMAGES'][i])):
            JOINCOMMANDS.append(env['FLASH_EXTRA_IMAGES'][i][j])

    env.Execute(" ".join(JOINCOMMANDS))

env.AddPostAction("buildprog", BuildMergeCommands)