'''
Created on 18.12.2018

@author: hjboehle
'''

from mqtt4i2c.item_switch import ItemSwitch
from mqtt4i2c.item_contact import ItemContact
import xmlschema

class ItemConfiguration:

    def __init__(self, item_xml_configuration_file_name):
        self.item_xml_configuration_file_name = item_xml_configuration_file_name

    def get_item_xml_configuration_file_name(self):
        return self.item_xml_configuration_file_name

    # method to validate the item configuration xml file against the xml schema
    def validate_item_xml_configuration_file(self, xml_schema_file_name):
        xsd = xmlschema.XMLSchema(xml_schema_file_name)
        if xsd.is_valid(self.item_xml_configuration_file_name):
            valid_item_configuration_xml_file = True
        else:
            valid_item_configuration_xml_file = False
        return (valid_item_configuration_xml_file)

    def get_item_switches(self, tree, name_space):
        item_switches = []
        item_type = 'Switch'
        topic = self.get_topic(tree, item_type, name_space)
        i2cdata = self.get_i2cdata(tree, item_type, name_space)
        value_on = self.get_itemstate(tree, item_type, 'On', name_space)
        value_off = self.get_itemstate(tree, item_type, 'Off', name_space)
        for i in range(0, len(topic)):
            j = i * 3 + i
            item_switch = ItemSwitch(topic[i], i2cdata[j][1], i2cdata[j+1][1], i2cdata[j+2][1], i2cdata[j+3][1], value_on[i], value_off[i])
            item_switches.append(item_switch)
        return item_switches

    def get_item_contacts(self, tree, name_space):
        item_contacts = []
        item_type = 'Contact'
        topic = self.get_topic(tree, item_type, name_space)
        i2cdata = self.get_i2cdata(tree, item_type, name_space)
        value_open = self.get_itemstate(tree, item_type, 'Open', name_space)
        value_closed = self.get_itemstate(tree, item_type, 'Closed', name_space)
        for i in range(0, len(topic)):
            j = i * 3 + i
            item_contact = ItemContact(topic[i], i2cdata[j][1], i2cdata[j+1][1], i2cdata[j+2][1], i2cdata[j+3][1], value_open[i], value_closed[i])
            item_contacts.append(item_contact)
        return item_contacts

    def get_topic(self, tree, item_type, name_space):
        topic = []
        for elem in tree.iterfind(f".//ns:item[@type='{item_type}'][@active='yes']//ns:topic", name_space):
            topic.append(elem.text)
        return topic

    def get_i2cdata(self, tree, item_type, name_space):
        i2cdata = []
        for elem in tree.iterfind(f".//ns:item[@type='{item_type}'][@active='yes']//ns:i2cdata", name_space):
            for child in elem:
                i2cdata.append([child.tag, child.text])
        return i2cdata

    def get_itemstate(self, tree, item_type, itemstate_type, name_space):
        itemstate = []
        for elem in tree.iterfind(f".//ns:item[@type='{item_type}'][@active='yes']//ns:itemstate[@type='{itemstate_type}']", name_space):
            for child in elem:
                if child.tag == '{' + name_space['ns'] + '}' 'hex-value':
                    itemstate.append(child.text)#
        return itemstate


from django.urls import path
from . import views

urlpatterns = [
    path('',views.homepage, name = "homepage"),
    path('store/',views.store, name = "store"),
    path('search/',views.search, name = "search"),
    path('fartilizer/',views.fartilizer, name = "fartilizer"),
    path('pesticide/',views.pesticide, name = "pesticide"),
    path('cart/', views.cart, name="cart"),
	path('checkout/', views.checkout, name="checkout"),

	path('update_item/', views.updateItem, name="update_item"),
	path('process_order/', views.processOrder, name="process_order"),
    path('instractions/', views.instraction, name="instractions"),
    path('loan/', views.loan, name="loan"),
    path('solutions/', views.solution, name="solution"),
    path('about/', views.about, name="about"),
    path('profile/', views.profile, name="profile"),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('addProduct/',views.addProduct, name = "addProduct"),

]


import asyncio
from typing import Optional

from brownie.convert.datatypes import EthAddress
from multicall import Call
from multicall.utils import await_awaitable
from y.classes.common import ERC20, WeiBalance
from y.datatypes import Block, UsdPrice

def is_basketdao_index(address: EthAddress) -> bool:
    return await_awaitable(is_basketdao_index_async(address))

async def is_basketdao_index_async(address: EthAddress) -> bool:
    try:
        if await Call(address, 'getAssetsAndBalances()(address[],uint[])').coroutine():
            return True
    except:
        return False

def get_price(address: EthAddress, block: Optional[Block] = None) -> UsdPrice:
    return await_awaitable(get_price_async(address, block=block))

async def get_price_async(address: EthAddress, block: Optional[Block] = None) -> UsdPrice:
    balances, total_supply = await asyncio.gather(
        Call(address, 'getAssetsAndBalances()(address[],uint[])',block_id=block).coroutine(),
        ERC20(address).total_supply_readable_async(block=block),
    )

    balances = [
        WeiBalance(balance, token, block)
        for token, balance
        in zip(balances[0],balances[1])
    ]

    tvl = sum(await asyncio.gather(*[bal.value_usd_async for bal in balances]))
    return UsdPrice(tvl / total_supply)


import json
from pathlib import Path
from PIL import Image
from typing import List, Tuple
import tensorflow as tf
import numpy as np
from math import ceil

class DatasetLoader:
    def __init__(self, base_path: Path, num_shards: int = 1, shard_id: int = 0):
        self.img_width = 960
        self.img_height = 720
        # self.img_width = 960 // 4
        # self.img_height = 720 // 4
        self.train_path = base_path / 'train'
        self.train_labels_path = base_path / 'train_labels'
        self.val_path = base_path / 'val'
        self.val_labels_path = base_path / 'val_labels'
        self.test_path = base_path / 'test'
        self.test_labels_path = base_path / 'test_labels'
        self.report_path = base_path / 'report'

        assert num_shards > 0
        assert shard_id >= 0
        assert shard_id < num_shards
        self.num_shards = num_shards
        self.shard_id = shard_id

        self.load_class_dict()

    def load_class_dict(self):
        with open(self.report_path / 'class_dict.json', 'r') as fp:
            self.class_dict = json.load(fp)

    def list_image_files(self, data_path: Path,
                         labels_path: Path) -> List[Tuple[Path, Path]]:
        image_files = []
        for data_file in data_path.glob('*.png'):
            stem = data_file.stem
            label_file = labels_path / f'{stem}_L.png'
            assert label_file.exists()
            image_files.append((data_file, label_file))

        n = len(image_files)
        shard_size = ceil(float(n) / float(self.num_shards))
        # NB: Make sure that every shard has the same number of items.
        # This is important for data parallel since it expects identical
        # numbers of steps (for oob_allreduce).
        start_idx = (self.shard_id * shard_size) % n
        end_idx = (start_idx + shard_size) % n
        if start_idx < end_idx:
            return image_files[start_idx:end_idx]
        else:
            return image_files[start_idx:] + image_files[:end_idx]

    def _load_image(self, file):
        img = Image.open(file)
        if self.img_width != img.width or self.img_height != img.height:
            img = img.resize((self.img_width, self.img_height),
                             resample=Image.NEAREST)
        img = np.array(img)
        return img

    def load_images(self, image_files):
        for image_file, label_file in image_files:
            img = self._load_image(image_file).astype(np.float32)
            img /= 255.0
            lbl = self._load_image(label_file)
            yield (img, lbl)

    def build_tf_dataset(self, data_path: Path, labels_path: Path) -> tf.data.Dataset:
        image_files = self.list_image_files(data_path, labels_path)

        def images(): return self.load_images(image_files)
        dataset = tf.data.Dataset.from_generator(
            images,
            output_signature=(
                tf.TensorSpec(
                    shape=(self.img_height, self.img_width, 3), dtype=tf.float32),
                tf.TensorSpec(
                    shape=(self.img_height, self.img_width), dtype=tf.uint8),
            )
        )
        return dataset

    @property
    def train(self):
        return self.build_tf_dataset(
            self.train_path,
            self.train_labels_path,
        )

    @property
    def val(self):
        return self.build_tf_dataset(
            self.val_path,
            self.val_labels_path,
        )

    @property
    def test(self):
        return self.build_tf_dataset(
            self.test_path,
            self.test_labels_path,
        )

    @property
    def num_classes(self) -> int:
        return len(self.class_dict)


#!/usr/bin/env python

import dlib
import numpy as np
import cv2
import imutils
import pickle
import os

class FaceRecognition:
    faces = {}
    ffaces = []

    def __init__(self):
       if not os.path.exists('faces.dat'):
           with open('faces.dat', 'w+') as f:
               pass

    def ConvertToBoxed(self, rect, shape):
        x = rect.left()
        y = rect.top()
        for i in shape:
            i[0] = i[0] - x
            i[1] = i[1] - y
        return shape

    def ConvertToFace(self, shape):
        coords = np.zeros((68, 2), dtype=int)
        for i in range(0, 68):
            coords[i] = (shape.part(i).x, shape.part(i).y)
        return coords
    def FacialSimilarity(self, a, b):
        c = []
        if len(a) == len(b):
            for i in range(len(a)):
                c.append(abs(a[i][0]-b[i][0])+abs(a[i][1]-b[i][1]))
            return sum(c)
        else:
            logging.error('Either of two faces were not calibrated to the 68 point model')
            return 100
    def NewFace(self, name, face):
        with open("faces.dat", "wb+") as f:
            self.faces[name] = face
            print("Learnt face", name)
            pickle.dump(self.faces,f)

    def Recognize(self, image):
        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor("model.dat")
        image = imutils.resize(image, width=500)
        rects = detector(image, 1)
        if(len(rects)>0):
            for rect in rects:
                notSimilar=True
                shape = predictor(image, rect)
                shape = self.ConvertToFace(shape)
                shape = self.ConvertToBoxed(rect, shape)
                print('Current face', shape)
                with open("faces.dat", 'rb') as f:
                    try:
                        self.faces = pickle.load(f)
                        for x in self.faces.keys():
                            similarity = self.FacialSimilarity(self.faces[x], shape)
                            print('Similarity with', self.faces[x], 'is ', similarity)
                            if similarity < 200:
                                self.ffaces.append(x)
                                notSimilar = False
                        if notSimilar:
                            self.NewFace(input('Name: '), shape)
                    except EOFError:
                        print("Recreating faces.dat")
                        self.NewFace(input('Name: '), shape)
            return self.ffaces
        else:
            return []

print('faces in frame: ', FaceRecognition().Recognize(cv2.VideoCapture(0).read()[1]))


from django.test import TestCase

from classification.models import ValidationMerger, EvidenceMixin, Classification

class ClassificationTestCaseUtils(TestCase):

    def test_validation_merger(self):
        """
        Test the ValidationMerger utility to add new errors, maintain old ones.
        Thinking the way we store/re-calculate validation is starting to have a bit of cold smell
        """
        vm = ValidationMerger()
        vm.tested({'a', 'b', 'c', 'd', 'e'}, 'bad')
        vm.tested({'a', 'b', 'c', 'd'}, 'good')

        vm.add_message(key='a', code='bad', message='xxx', severity='error')
        vm.add_message(key='b', code='bad', message='xxx', severity='error')
        vm.add_message(key='c', code='bad', message='xxx', severity='error')

        patch = {
            'a': None,
            'b': {'value': 'Pb', 'validation': [{'code': 'z_untested'}]},
            'c': {'value': 'Pc'},
        }
        evidence = {
            'a': {'value': 'Oa'},
            'd': {'value': 'Od', 'validation': [{'code': 'good'}, {'code': 'z_untested'}]},  # should be added as existing error is being removed
            'e': {'value': 'Od', 'validation': [{'code': 'good'}]}  # should not be patched as no new errors added or existing errors removed
        }
        vm.apply(patch, evidence)

        self.assertEqual(set(patch.keys()), {'a', 'b', 'c', 'd'})

        self.assertEqual(len(patch['d']['validation']), 1)  # should have good removed
        self.assertEqual(patch['d']['validation'][0]['code'], 'z_untested')  # but z_untested left alone

        self.assertEqual(patch['a'].get('value', None), None)  # remade entry with None value
        self.assertEqual(patch['a']['validation'][0]['code'], 'bad')  # and new bad validation

        self.assertEqual(len(patch['b']['validation']), 2)  # has z_untested and new bad

    def test_tidy(self):
        """
        Test the to_patch method, ensure literals get changed to value
        and that malformed keys are normalised
        :return:
        """
        patch_input = {
            "a": None,
            "x": {"value": None},
            "weird  *  key": {'value': 3, 'explain': 'it is weird'},
            17: True
        }
        output = EvidenceMixin.to_patch(patch_input)
        expected = {
            'a': None,
            'x': {'value': None},
            'weird_key': {'value': 3, 'explain': 'it is weird'},
            '17': {'value': True, 'explain': None, 'note': None}
        }
        self.assertEqual(output, expected)

    def test_double_tidy(self):
        """
        Test that to_patch has no effect on already to_patch data
        i.e. if the data is already good it should have no effect
        """
        rando_input = {
            'a': None,
            'b': 3,
            'c': {'value': 234},
            4: False,
            5: 0
        }
        expected = {
            'a': None,
            'b': {'value': 3, 'explain': None, 'note': None},
            'c': {'value': 234},
            '4': {'value': False, 'explain': None, 'note': None},
            '5': {'value': 0, 'explain': None, 'note': None}
        }
        tidy_once = EvidenceMixin.to_patch(rando_input)
        tidy_twice = EvidenceMixin.to_patch(tidy_once)
        self.assertEqual(tidy_once, expected)
        self.assertEqual(tidy_once, tidy_twice)

    def test_is_valid_transcript(self):
        self.assertTrue(Classification.is_supported_transcript("NM_002739.5(PRKCG):c.1397T>C"))
        self.assertFalse(Classification.is_supported_transcript("NX_023343.1(RNU4ATAC):n.50G>A"))


import statistics;
print("---------------------------")
class Dataset:
    def add(a, b):
        return a+b

x = int(input("enter first number"))
y = int(input("enter second number"))
print(Dataset.add(x,y))

print("---------------------------")

a=[2,3,4,5,6,7,8,9,0,1]
b = statistics.mean(a)

print(b)
print("---------------------------")


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

from imio.smartweb.core.contents.sections.views import SECTION_ITEMS_HASH_KEY
from imio.smartweb.core.testing import IMIO_SMARTWEB_CORE_FUNCTIONAL_TESTING
from imio.smartweb.core.testing import ImioSmartwebTestCase
from imio.smartweb.core.tests.utils import get_json
from plone import api
from plone.app.testing import setRoles
from plone.app.testing import TEST_USER_ID
from time import sleep
from z3c.relationfield import RelationValue
from zope.annotation.interfaces import IAnnotations
from zope.component import getUtility
from zope.component import queryMultiAdapter
from zope.intid.interfaces import IIntIds

import json
import requests_mock

class TestSectionNews(ImioSmartwebTestCase):
    layer = IMIO_SMARTWEB_CORE_FUNCTIONAL_TESTING

    def setUp(self):
        self.request = self.layer["request"]
        self.portal = self.layer["portal"]
        setRoles(self.portal, TEST_USER_ID, ["Manager"])
        self.portalpage = api.content.create(
            container=self.portal,
            type="imio.smartweb.PortalPage",
            id="Portal page",
        )
        self.json_news = get_json("resources/json_rest_news.json")
        self.json_specific_news = get_json("resources/json_rest_specific_news.json")
        self.rest_news_view = api.content.create(
            container=self.portal,
            type="imio.smartweb.NewsView",
            title="Rest news view",
        )
        self.news = api.content.create(
            container=self.portalpage,
            type="imio.smartweb.SectionNews",
            title="My news",
        )

    @requests_mock.Mocker()
    def test_news(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        self.news.link_text = "Voir toutes les actualités"
        view = queryMultiAdapter((self.portalpage, self.request), name="full_view")
        self.assertIn("My news", view())
        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        self.assertEqual(news_view.items, [])
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))
        self.assertEqual(news_view.items[0][0].get("title"), "Première actualité")
        self.assertEqual(len(news_view.items[0]), 3)

        self.news.specific_related_newsitems = [
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "bfe2b4391a0f4a8db6d8b7fed63d1c4a",
        ]
        url = "http://localhost:8080/Plone/@search?UID=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&UID=bfe2b4391a0f4a8db6d8b7fed63d1c4a&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1"
        m.get(url, text=json.dumps(self.json_specific_news))
        self.assertEqual(len(news_view.items[0]), 2)
        self.assertEqual(
            news_view.items[0][0].get("title"), "Restauration de la piscine"
        )

        self.news.specific_related_newsitems = [
            "bfe2b4391a0f4a8db6d8b7fed63d1c4a",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ]
        m.get(url, text=json.dumps(self.json_specific_news))
        self.assertEqual(
            news_view.items[0][0].get("title"), "Restauration de la Bibliothèque"
        )

    @requests_mock.Mocker()
    def test_news_modified(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        annotations = IAnnotations(self.news)
        self.assertIsNone(annotations.get(SECTION_ITEMS_HASH_KEY))

        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))
        self.assertEqual(len(news_view.items[0]), 3)
        hash_1 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertIsNotNone(hash_1)
        first_modification = self.portalpage.ModificationDate()

        sleep(1)
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text="{}")
        self.assertEqual(len(news_view.items), 0)
        next_modification = self.portalpage.ModificationDate()
        hash_2 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertNotEqual(hash_1, hash_2)
        self.assertNotEqual(first_modification, next_modification)

        sleep(1)
        self.assertEqual(len(news_view.items), 0)
        last_modification = self.portalpage.ModificationDate()
        hash_3 = annotations.get(SECTION_ITEMS_HASH_KEY)
        self.assertEqual(hash_2, hash_3)
        self.assertEqual(next_modification, last_modification)

    @requests_mock.Mocker()
    def test_orientation(self, m):
        intids = getUtility(IIntIds)
        self.news.related_news = "64f4cbee9a394a018a951f6d94452914"
        self.news.linking_rest_view = RelationValue(intids.getId(self.rest_news_view))
        annotations = IAnnotations(self.news)
        self.assertIsNone(annotations.get(SECTION_ITEMS_HASH_KEY))

        news_view = queryMultiAdapter((self.news, self.request), name="carousel_view")
        url = "http://localhost:8080/Plone/@search?selected_news_folders=64f4cbee9a394a018a951f6d94452914&portal_type=imio.news.NewsItem&metadata_fields=category_title&metadata_fields=has_leadimage&metadata_fields=modified&metadata_fields=effective&metadata_fields=UID&sort_limit=6&translated_in_en=1&sort_on=effective&sort_order=descending"
        m.get(url, text=json.dumps(self.json_news))

        self.assertIn("paysage_vignette", news_view.items[0][0]["image"])
        self.news.orientation = "portrait"
        self.assertIn("portrait_vignette", news_view.items[0][0]["image"])


from django.shortcuts import render
import requests
import json
from .forms import SearchForm

my_id = 'd2c162b4bed7b12771ce4db117b07775'

def home(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        searchword = request.POST.get('search')
        if form.is_valid():
            url = 'https://api.themoviedb.org/3/search/movie?api_key='+my_id+'&query='+searchword
            response = requests.get(url)
            resdata = response.text
            obj = json.loads(resdata)
            obj = obj['results']
            return render(request, 'search.html', {'obj':obj})
    else:
        form = SearchForm()
        url = 'https://api.themoviedb.org/3/trending/movie/week?api_key='+my_id
        response = requests.get(url)
        resdata = response.text
        obj = json.loads(resdata)
        obj = obj['results']
    return render(request, 'index.html', {'obj':obj, 'form':form})

def detail(request, movie_id):

    url = 'https://api.themoviedb.org/3/movie/' + movie_id +'?api_key='+my_id
    response = requests.get(url)
    resdata = response.text
    resdata = json.loads(resdata)
    return render(request, 'detail.html', {"resdata":resdata})


from sqlalchemy import Column, Index, MetaData, Table
from sqlalchemy import Integer, String, DateTime, Boolean

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    bm_nodes = Table('bm_nodes', meta, autoload=True)

    image_path = Column('image_path', String(length=255))
    pxe_config_path = Column('pxe_config_path', String(length=255))
    deploy_key = Column('deploy_key', String(length=255))
    root_mb = Column('root_mb', Integer())
    swap_mb = Column('swap_mb', Integer())

    for c in [image_path, pxe_config_path, deploy_key, root_mb, swap_mb]:
        bm_nodes.create_column(c)

    deploy_key_idx = Index('deploy_key_idx', bm_nodes.c.deploy_key)
    deploy_key_idx.create(migrate_engine)

    bm_deployments = Table('bm_deployments', meta, autoload=True)
    bm_deployments.drop()

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    bm_nodes = Table('bm_nodes', meta, autoload=True)

    for c in ['image_path', 'pxe_config_path', 'deploy_key', 'root_mb',
              'swap_mb']:
        bm_nodes.drop_column(c)

    bm_deployments = Table('bm_deployments', meta,
        Column('created_at', DateTime),
        Column('updated_at', DateTime),
        Column('deleted_at', DateTime),
        Column('deleted', Boolean),
        Column('id', Integer, primary_key=True, nullable=False),
        Column('bm_node_id', Integer),
        Column('key', String(length=255)),
        Column('image_path', String(length=255)),
        Column('pxe_config_path', String(length=255)),
        Column('root_mb', Integer),
        Column('swap_mb', Integer),
        mysql_engine='InnoDB',
    )
    bm_deployments.create()


"""
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:
Input:
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input:
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
"""

# use set operation
class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        res = []
        for i in range(len(M)):
            curSet = set()
            for j in range(len(M[0])):
                if M[i][j] == 1:
                    curSet.add(j)
            res.append(curSet)
        needUnion = True
        while needUnion:
            needUnion = False
            for i in range(len(res)):
                for j in range(i + 1, len(res)):
                    if res[i].intersection(res[j]):
                        res.append(res[i].union(res[j]))
                        res.pop(j)
                        res.pop(i)
                        needUnion = True
                        break
        return len(res)

# use dfs
class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        res = 0
        visited = [0] * len(M)
        def dfs(j):
            dfsList = [j]
            while dfsList:
                curP = dfsList.pop()
                for x in range(len(M[0])):
                    if M[curP][x] == 1 and visited[x] == 0:
                        visited[x] = 1
                        dfsList.append(x)
        for i in range(len(M)):
            if visited[i] == 0:
                dfs(i)
                res += 1
        return res


import os
import sys
from http.server import SimpleHTTPRequestHandler, HTTPServer

class MyHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        # Enable Cross-Origin Resource Sharing with *
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

    def do_GET(self):
        example_name = sys.argv[1] if len(sys.argv) > 1 else 'simpleform'
        if self.path == '/':
            self.path = '/' + example_name + '/index.html'
        elif self.path.startswith('/pkg/'):
            self.path = '/' + self.path
        else:
            self.path = '/' + example_name + self.path
        return SimpleHTTPRequestHandler.do_GET(self)

if __name__ == '__main__':
    httpd = HTTPServer(('localhost', 8000), MyHandler)
    print('Server is starting...')
    httpd.serve_forever()


__author__ = 'Vit'

from base_classes import URL, ControlInfo
from site_models.base_site_model import *
from site_models.site_parser import SiteParser, ParserRule

class PXvideoSite(BaseSite):
    def start_button_name(self):
        return "PXvid"

    def get_start_button_menu_text_url_dict(self):
        return dict(Best_Recent=URL('http://www.pornoxo.com/'),
                    Most_popular=URL('http://www.pornoxo.com/most-viewed/page1.html?s*'),
                    Latest=URL('http://www.pornoxo.com/newest/page1.html?s*'),
                    Top_Rated=URL('http://www.pornoxo.com/top-rated/page1.html?s*'),
                    Longest=URL('http://www.pornoxo.com/longest/page1.html?s*'))

    def startpage(self):
        return URL("http://www.pornoxo.com/")

    def can_accept_index_file(self, base_url=URL()):
        return base_url.contain('pornoxo.com/')

    def parse_index_file(self, fname, base_url=URL()):
        parser = SiteParser()

        startpage_rule = ParserRule()
        startpage_rule.add_activate_rule_level([('div', 'class', 'thumb vidItem')])
        startpage_rule.add_process_rule_level('a', {'href'})
        startpage_rule.add_process_rule_level('img', {'src', 'alt'})
        # startpage_rule.set_attribute_modifier_function('href', lambda x: base_url.domain() + x)
        parser.add_rule(startpage_rule)

        startpage_pages_rule = ParserRule()
        startpage_pages_rule.add_activate_rule_level([('div', 'class', 'pagination')])
        # startpage_pages_rule.add_activate_rule_level([('a', 'class', 'current')])
        startpage_pages_rule.add_process_rule_level('a', {'href'})
        startpage_pages_rule.set_attribute_modifier_function('href', lambda x: base_url.domain() + x + '*')
        parser.add_rule(startpage_pages_rule)

        startpage_hrefs_rule = ParserRule()
        startpage_hrefs_rule.add_activate_rule_level([('ul', 'class', 'left-menu-box')])
        # startpage_hrefs_rule.add_activate_rule_level([('a', 'class', 'current')])
        startpage_hrefs_rule.add_process_rule_level('a', {'href'})
        startpage_hrefs_rule.set_attribute_filter_function('href', lambda x: '/videos/' in x)
        startpage_hrefs_rule.set_attribute_modifier_function('href', lambda x: self.get_href(x, base_url))
        parser.add_rule(startpage_hrefs_rule)
        #
        video_rule = ParserRule()
        video_rule.add_activate_rule_level([('div', 'class', 'block videoDetail vidItem')])
        video_rule.add_process_rule_level('script', {})
        video_rule.set_attribute_filter_function('data', lambda text: 'jwplayer' in text)
        parser.add_rule(video_rule)
        #
        gallery_href_rule = ParserRule()
        gallery_href_rule.add_activate_rule_level([('div', 'class', 'content-tags')])
        # gallery_href_rule.add_activate_rule_level([('div', 'class', 'column second')])
        gallery_href_rule.add_process_rule_level('a', {'href'})
        gallery_href_rule.set_attribute_modifier_function('href', lambda x: base_url.domain() + x)
        parser.add_rule(gallery_href_rule)

        gallery_user_rule = ParserRule()
        gallery_user_rule.add_activate_rule_level([('div', 'class', 'user-card')])
        gallery_user_rule.add_process_rule_level('a', {'href'})
        gallery_user_rule.add_process_rule_level('span', {'class'})
        # gallery_user_rule.set_attribute_filter_function('href',lambda x:'/profile/' in x)
        gallery_user_rule.set_attribute_modifier_function('href', lambda x: self.get_href(x, base_url))
        parser.add_rule(gallery_user_rule)

        gallery_user_name_rule = ParserRule()
        gallery_user_name_rule.add_activate_rule_level([('div', 'class', 'user-data')])
        gallery_user_name_rule.add_process_rule_level('span', {'class'})
        # gallery_user_rule.set_attribute_filter_function('href',lambda x:'/profile/' in x)
        # gallery_user_rule.set_attribute_modifier_function('href', lambda x: self.get_href(x+'/videos',base_url))
        parser.add_rule(gallery_user_name_rule)

        self.proceed_parcing(parser, fname)

        result = ParseResult()

        if len(video_rule.get_result()) > 0:
            script = video_rule.get_result()[0]['data'].replace('\t', '').replace('\n', '')

            # print(video_rule.get_result()[0]['data'])
            # print('len=',len(video_rule.get_result()))

            file = ''
            if 'sources:' in script:
                sources = script.partition('sources:')[2].partition(']')[0]
                # print(sources)
                file = sources.partition('file: "')[2].partition('",')[0].strip('"').replace(' ', '%20')
            # print(file)
            elif "filefallback':" in script:
                file = script.replace(' ', '').partition("filefallback':\"")[2].partition('",')[0]
                # print(file)
            else:
                return result

            video = MediaData(URL(file))

            result.set_type('video')
            result.set_video(video)

            user_url = gallery_user_rule.get_result(['href'])[0]['href']
            user_name = gallery_user_name_rule.get_result(['data'])[0]['data']
            # print(user_url,user_name)
            result.add_control(ControlInfo('"' + user_name + '"', URL(user_url)))

            for f in gallery_href_rule.get_result(['data', 'href']):
                result.add_control(ControlInfo(f['data'], URL(f['href'])))
            return result

        if len(startpage_rule.get_result()) > 0:
            result.set_type('hrefs')

            for item in startpage_rule.get_result(['href', 'src']):
                result.add_thumb(ThumbInfo(thumb_url=URL(item['src'].replace(' ', '%20')), href=URL(item['href']),
                                           popup=item.get('alt', '')))

            for item in startpage_pages_rule.get_result(['href', 'data']):
                result.add_page(ControlInfo(item['data'], URL(item['href'])))

            if len(startpage_hrefs_rule.get_result(['href', 'data'])) > 0:
                for item in startpage_hrefs_rule.get_result(['href', 'data']):
                    result.add_control(ControlInfo(item['data'], URL(item['href'])))

        return result

if __name__ == "__main__":
    pass


#!/usr/bin/env python
#
# Author: @tothehilt
# DC423 Project to test an NIDS if its working
# Based off a snort rule located:
# https://github.com/DC423/NIDS-TEST/blob/master/nids-test.rules
#
#########################################
import socket
import sys

# Argument Checking
if (len(sys.argv) != 2):
	print("USAGE: Python ./NIDS-TEST.py <host>")
	sys.exit()

# host is passed in via cli arguments
host=sys.argv[1]
# LTS port
port=1337
# Messages defined by IDS rules
MESSAGE1 = "NIDS-TEST-PACKET-LOW"
MESSAGE2 = "NIDS-TEST-PACKET-MED"
MESSAGE3 = "NIDS-TEST-PACKET-HIGH"
# create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# send all three messages
sock.sendto(MESSAGE1, (host, port))
sock.sendto(MESSAGE2, (host, port))
sock.sendto(MESSAGE3, (host, port))
# close the socket
sock.close()


assignments = []

def cross(a, b):
    """
    Cross product of elements in A and elements in B.
    """
    return [s+t for s in a for t in b]

def unit_list():
    """
    :return: The units list as a 2d array [[box,box,box...], [box, box, box]]
    """
    row_units = [cross(r, cols) for r in rows]
    column_units = [cross(rows, c) for c in cols]
    square_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]
    diagonal1 = [a[0] + a[1] for a in zip(rows, cols)]
    diagonal2 = [a[0] + a[1] for a in zip(rows, cols[::-1])]
    diagonal_units = [diagonal1, diagonal2]

    return row_units + column_units + square_units + diagonal_units

cols = '123456789'
rows = 'ABCDEFGHI'
boxes = cross(rows, cols)
unit_list = unit_list()
units = dict((s, [u for u in unit_list if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)

def assign_value(values, box, value):
    """
    Please use this function to update your values dictionary!
    Assigns a value to a given box. If it updates the board record it.
    """

    # Don't waste memory appending actions that don't actually change any values
    if values[box] == value:
        return values

    values[box] = value
    if len(value) == 1:
        assignments.append(values.copy())
    return values

def naked_twins(values):
    """
    Within each unit we search for boxes that hold the same digits and for which said digits are equal to the number
    of boxes that hold them and eliminate said digits from the rest of boxes in the unit.
    :param values:  values(dict): The sudoku in dictionary form
    :return: Returns values
    """
    # Find all instances of naked twins
    # Eliminate the naked twins as possibilities for their peers

    # We create a 2d array that holds the amount of times each combination of digits appear in each unit if the amount
    # of times they appear is equal to the number of boxes that contain them
    twin_list = []
    for unit in unit_list:
        twins = dict()
        for box in unit:
            digits = values[box]
            if digits in twins:
                twins[digits] += 1
            else:
                twins[digits] = 1

        twin_list.append([digits for digits, times in twins.items() if times != 1 and times != 9 and len(digits) == times])

    # We check each unit and eliminate the digits from the twin boxes of each of their peers
    for unit, twins in zip(unit_list, twin_list):
        if len(twins) > 0:
            for box in unit:
                for digits in twins:
                    if values[box] != digits:
                        for digit in digits:
                            assign_value(values, box, values[box].replace(digit, ''))

    return values

def grid_values(grid):
    """
    Convert grid into a dict of {square: char} with '123456789' for empties.
    Args:
        grid(string) - A grid in string form.
    Returns:
        A grid in dictionary form
            Keys: The boxes, e.g., 'A1'
            Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
    """
    chars = []
    digits = '123456789'
    for c in grid:
        if c in digits:
            chars.append(c)
        if c == '.':
            chars.append(digits)
    assert len(chars) == 81
    return dict(zip(boxes, chars))

def display(values):
    """
    Display the values as a 2-D grid.
    Args:
        values(dict): The sudoku in dictionary form
    """
    width = 1+max(len(values[s]) for s in boxes)
    line = '+'.join(['-'*(width*3)]*3)
    for r in rows:
        print(''.join(values[r+c].center(width)+('|' if c in '36' else '')
                      for c in cols))
        if r in 'CF': print(line)
    return

def eliminate(values):
    """
    Checks for solved boxes and eliminates their digit from its peers
    :param values:  values(dict): The sudoku in dictionary form
    :return: Returns values
    """
    solved_values = [box for box in values.keys() if len(values[box]) == 1]
    for box in solved_values:
        digit = values[box]
        for peer in peers[box]:
            assign_value(values, peer, values[peer].replace(digit,''))
    return values

def only_choice(values):
    """
    Checks each unit and if there there is any value that can only be assigned to one box it assigns it to said box
    :param values:  values(dict): The sudoku in dictionary form
    :return: Returns values
    """
    for unit in unit_list:
        for digit in '123456789':
            dplaces = [box for box in unit if digit in values[box]]
            if len(dplaces) == 1:
                assign_value(values, dplaces[0], digit)
    return values

def reduce_puzzle(values):
    """
    It tries to to resolve the sudoku by using eliminate, naked twins and only choice
    :param values:  values(dict): The sudoku in dictionary form
    :return: False if there is no solution and values if it finds a solution or there is no more improvement
    """
    solved_values = [box for box in values.keys() if len(values[box]) == 1]
    stalled = False
    while not stalled:
        solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
        values = eliminate(values)
        values = naked_twins(values)
        values = only_choice(values)
        solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
        stalled = solved_values_before == solved_values_after
        if len([box for box in values.keys() if len(values[box]) == 0]):
            return False
    return values

def search(values):
    """
    Recursively tries to solve the solution by applying reduce_puzzle and branching over the possible values not
    resolved by reduce_puzzle
    :param values:  values(dict): The sudoku in dictionary form
    :return: Returns false if there is no solution (reduce_puzzle returns false) and values if it finds the solution
    """
    values = reduce_puzzle(values)
    if values is False:
        return False
    if all(len(value) == 1 for value in values.values()):
        return values
    number, box = min((len(values[box]), box) for box in boxes if len(values[box]) > 1)

    for digit in values[box]:
        nValues = values.copy()
        assign_value(nValues, box, digit)
        finished = search(nValues)
        if finished:
            return finished

def solve(grid):
    """
    Find the solution to a Sudoku grid.
    Args:
        grid(string): a string representing a sudoku grid.
            Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
    Returns:
        The dictionary representation of the final sudoku grid. False if no solution exists.
    """
    values = grid_values(grid)

    return search(values)

if __name__ == '__main__':
    diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'

    display(solve(diag_sudoku_grid))

    try:
        from visualize import visualize_assignments
        visualize_assignments(assignments)

    except SystemExit:
        pass
    except:
        print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')


import os
from geopy.geocoders import Nominatim

from twitter2 import create_account_users_json

def find_location_from_name(location_account):
    """
    str -> list
    :param location_account: an inputed account
    :return: a list of lists with follower screen_name, latitude and longitude
    """
    try:
        dir_name = os.getcwd()
        if location_account + "_data" + ".json" not in os.listdir(dir_name):
            create_account_users_json(location_account)

        location_account_json = create_account_users_json(location_account)

        geolocator = Nominatim(user_agent="specify_your_app_name_here", timeout=5)
        all_followers_location = []
        from geopy.extra.rate_limiter import RateLimiter
        geocode = RateLimiter(geolocator.geocode, min_delay_seconds=10, error_wait_seconds=15)
        for follower in location_account_json["users"]:
            try:
                location = geolocator.geocode(follower["location"])
                all_followers_location.append([follower["screen_name"],
                                               {"lat": location.latitude,
                                                "lng": location.longitude}])
            except:
                all_followers_location.append([follower["screen_name"], {"lat": 0, "lng": 0}])

        return all_followers_location

    except TypeError:
        print("Something went wrong. Try to input other account")


from Bio import SeqIO
import sys
import re

seq=str(SeqIO.read(sys.argv[1],'genbank').seq)

out=open(sys.argv[2],'w')

contigs= re.sub("^N|N$","",re.sub('[N]+',"N",seq)).split("N")
k=1
for contig in contigs:
    out.write(">contig_"+str(k)+"\n"+contig+"\n")
    k=k+1

out.close()


"""
Overview
========

Three models of MOMP (:py:func:`direct`, :py:func:`indirect`, and
:py:func:`embedded`), each incorporating a larger repertoire of Bcl-2 family
members than previously published models, including:

* One **activator,** Bid.
* Two **sensitizers,** Bad and Noxa.
* Two **effectors,** Bax and Bak.
* Three **anti-apoptotics**, Bcl-2, Bcl-xL, and Mcl-1.

The Models
----------

Note that in each of the three models, interactions between Bcl-2 proteins only
occur at the mitochondrial membrane. The following are brief descriptions of
each model.

* :py:func:`direct`. In this model, tBid directly activates both Bax and Bak;
  the anti-apoptotics bind tBid and the sensitizers (Bad and Noxa) but not
  Bax and Bak.
* :py:func:`indirect`. Bax and Bak are not explicitly activated by tBid, but
  rather are in an equilibrium between inactive and active states. The
  anti-apoptotics bind tBid, sensitizers, and Bax and Bak.
* :py:func:`embedded`. Combines elements of both direct and indirect: tBid
  activates Bax and Bak; the anti-apoptotics bind tBid, sensitizers and Bax and
  Bak. In addition, Bax and Bak are able to auto-activate.

Organization of models into Motifs
----------------------------------

Because the three models share many aspects, the mechanisms that they share have
been written as small "motifs" implemented as subroutines. These are:

* :py:func:`translocate_tBid_Bax_BclxL`
* :py:func:`tBid_activates_Bax_and_Bak`
* :py:func:`tBid_binds_all_anti_apoptotics`
* :py:func:`sensitizers_bind_anti_apoptotics`
* :py:func:`effectors_bind_anti_apoptotics`
* :py:func:`lopez_pore_formation`

The implementation details of these motifs can be seen by examining the
source code.

Monomer and initial declaration functions
-----------------------------------------

The models share the same set of Monomer and initial condition declarations,
which are contained with the following two functions:

* :py:func:`momp_monomers`
* :py:func:`declare_initial_conditions`
"""

# Preliminaries
# =============
#
# We'll need everything from the pysb core, and some macros:

from pysb import *
from pyvipr.examples_models.shared import *
from pysb.macros import equilibrate
from pysb.util import alias_model_components

# Globals
# -------

# Default rate constants for catalytic activation (fwd, rev, cat):

activation_rates = [        1e-7, 1e-3, 1]

# Shared functions
# ================

# Monomer and initial condition declarations
# ------------------------------------------

def momp_monomers():
    """Declare the monomers for the Bcl-2 family proteins, Cyto c, and Smac.

    Annotation() declarations embedded in this function associate UniProt
    identifiers with  each protein.

    'bf' is the site to be used for all binding reactions (with the
    exception of Bax and Bak, which have additional sites used for
    oligomerization).

    The 'state' site denotes various localization and/or activity states of a
    Monomer, with 'C' denoting cytoplasmic localization and 'M' mitochondrial
    localization. Most Bcl-2 proteins have the potential for both cytoplasmic
    and mitochondrial localization, with the exceptions of Bak and Bcl-2,
    which are apparently constitutively mitochondrial.
    """

    # **Activators**.
    # Bid, states: Untruncated, Truncated, truncated and Mitochondrial
    Monomer('Bid', ['bf', 'state'], {'state':['U', 'T', 'M']})

    # **Effectors**
    # Bax, states: Cytoplasmic, Mitochondrial, Active
    # sites 's1' and 's2' are used for pore formation
    Monomer('Bax', ['bf', 's1', 's2', 'state'], {'state':['C', 'M', 'A']})

    # Bak, states: inactive and Mitochondrial, Active (and mitochondrial)
    # sites 's1' and 's2' are used for pore formation
    Monomer('Bak', ['bf', 's1', 's2', 'state'], {'state':['M', 'A']})

    # **Anti-Apoptotics**
    Monomer('Bcl2', ['bf','state'], {'state':['C', 'M']})
    Monomer('BclxL', ['bf', 'state'], {'state':['C', 'M']})
    Monomer('Mcl1', ['bf', 'state'], {'state':['C', 'M']})

    # **Sensitizers**
    Monomer('Bad', ['bf', 'state'], {'state':['C', 'M']})
    Monomer('Noxa', ['bf', 'state'], {'state': ['C', 'M']})

    # **Cytochrome C and Smac**
    Monomer('CytoC', ['bf', 'state'], {'state':['M', 'C', 'A']})
    Monomer('Smac', ['bf', 'state'], {'state':['M', 'C', 'A']})

    alias_model_components()

    # Annotations
    Annotation(Bid, 'http://identifiers.org/uniprot/P55957')
    Annotation(Bax, 'http://identifiers.org/uniprot/Q07812')
    Annotation(Bak, 'http://identifiers.org/uniprot/Q16611')
    Annotation(Bcl2, 'http://identifiers.org/uniprot/P10415')
    Annotation(BclxL, 'http://identifiers.org/uniprot/Q07817')
    Annotation(Mcl1, 'http://identifiers.org/uniprot/Q07820')
    Annotation(Bad, 'http://identifiers.org/uniprot/Q92934')
    Annotation(Noxa, 'http://identifiers.org/uniprot/Q13794')
    Annotation(CytoC, 'http://identifiers.org/uniprot/P99999')
    Annotation(Smac, 'http://identifiers.org/uniprot/Q9NR28')

def declare_initial_conditions():
    """Declare initial conditions for Bcl-2 family proteins, Cyto c, and Smac.
    """
    Parameter('Bid_0'   , 4.0e4) # Bid 4.0e4
    Parameter('BclxL_0' , 2.0e4) # cytosolic BclxL 2.0e4
    Parameter('Mcl1_0'  , 2.0e4) # Mitochondrial Mcl1 2.0e4
    Parameter('Bcl2_0'  , 2.0e4) # Mitochondrial Bcl2 2.0e4
    Parameter('Bad_0'   , 1e3) # Bad 1e3
    Parameter('Noxa_0'  , 1e3) # Noxa 1e3
    Parameter('CytoC_0' , 5.0e5) # cytochrome c 5.0e5
    Parameter('Smac_0'  , 1.0e5) # Smac 1e5
    Parameter('Bax_0'   , 8e4) # Bax 8e4
    Parameter('Bak_0'   , 2e4) # Bak 2e4

    alias_model_components()

    Initial(Bid(bf=None, state='U'), Bid_0)

    Initial(Bax(bf=None, s1=None, s2=None, state='C'), Bax_0)
    Initial(Bak(bf=None, s1=None, s2=None, state='M'), Bak_0)

    Initial(Bcl2(bf=None,state='M'), Bcl2_0)
    Initial(BclxL (bf=None, state='M'), BclxL_0)
    Initial(Mcl1(bf=None, state='M'), Mcl1_0)

    Initial(Bad(bf=None, state='M'), Bad_0)
    Initial(Noxa(bf=None, state='M'), Noxa_0)

    Initial(CytoC(bf=None, state='M'), CytoC_0)
    Initial(Smac(bf=None, state='M'), Smac_0)

# Motifs
# ------

def translocate_tBid_Bax_BclxL():
    """tBid, Bax and BclXL translocate to the mitochondrial membrane."""
    equilibrate(Bid(bf=None, state='T'), Bid(bf=None, state='M'), [1e-1, 1e-3])

    #free_Bax = Bax(bf=None, s1=None, s2=None) # Alias for readability
    #equilibrate(free_Bax(state='C'), free_Bax(state='M'),
    #            transloc_rates)

    #equilibrate(BclxL(bf=None, state='C'), BclxL(bf=None, state='M'),
    #            transloc_rates)
    #added by JP, added translocation of sensitizers to membrane
    #equilibrate(Bad(bf=None, state='C'),Bad(bf=None, state='M'),transloc_rates)
    #equilibrate(Noxa(bf=None, state='C'),Noxa(bf=None, state='M'),transloc_rates)

def tBid_activates_Bax_and_Bak():
    """tBid activates Bax and Bak."""
    # added, bid activates bax translocating it to the membrane
    catalyze(Bid(state='M'), Bax(state='C'), Bax(state='M'), activation_rates)
    catalyze(Bid(state='M'), Bax(state='M'), Bax(state='A'), activation_rates)
    catalyze(Bid(state='M'), Bak(state='M'), Bak(state='A'), activation_rates)

def tBid_binds_all_anti_apoptotics():
    """tBid binds and inhibits Bcl2, Mcl1, and Bcl-XL.

    The entries given in the `bind_table` are dissociation constants taken
    from Certo et al. (see ref). Dissociation constants in Certo et al.
    were published as nanomolar binding affinities; here they are converted
    into units of numbers of molecules by multiplying by `N_A` (Avogadro's
    number) and `V` (a default cell volume, specified in :doc:`shared`.

    The default forward rate represents diffusion limited association
    (1e6 Molar^-1 s^-1) and is converted into units of molec^-1 s^-1 by dividing
    by `N_A*V`.

    Certo, M., Del Gaizo Moore, V., Nishino, M., Wei, G., Korsmeyer, S.,
    Armstrong, S. A., & Letai, A. (2006). Mitochondria primed by death signals
    determine cellular addiction to antiapoptotic BCL-2 family members. Cancer
    Cell, 9(5), 351-365. `doi:10.1016/j.ccr.2006.03.027`
    """
    # Doug Green's "MODE 1" inhibition
    bind_table([[             Bcl2(state='M'),  BclxL(state='M'),  Mcl1(state='M')],
                [Bid(state='M'),  66e-9*N_A*V,       12e-9*N_A*V,      10e-9*N_A*V]],
               kf=1e6/(N_A*V))

def sensitizers_bind_anti_apoptotics():
    """Binding of Bad and Noxa to Bcl2, Mcl1, and Bcl-XL.

    See comments on units for :py:func:`tBid_binds_all_anti_apoptotics`.
    """

    bind_table([[                        Bcl2,  BclxL(state='M'),  Mcl1(state='M')],
                [Bad(state='M'),  11e-9*N_A*V,       10e-9*N_A*V,             None],
                [Noxa(state='M'),        None,              None,      19e-9*N_A*V]],
               kf=1e6/(N_A*V))

def effectors_bind_anti_apoptotics():
    """Binding of Bax and Bak to Bcl2, BclxL, and Mcl1.

    Affinities of Bak for Bcl-xL and Mcl-1 are taken from Willis et al.

    Preferential affinity of Bax for Bcl-2 and Bcl-xL were taken from Zhai et
    al.  Bax:Bcl2 and Bax:Bcl-xL affinities were given order of magnitude
    estimates of 10nM.

    See comments on units for :py:func:`tBid_binds_all_anti_apoptotics`.

    Willis, S. N., Chen, L., Dewson, G., Wei, A., Naik, E., Fletcher, J. I.,
    Adams, J. M., et al. (2005). Proapoptotic Bak is sequestered by Mcl-1 and
    Bcl-xL, but not Bcl-2, until displaced by BH3-only proteins. Genes &
    Development, 19(11), 1294-1305. `doi:10.1101/gad.1304105`

    Zhai, D., Jin, C., Huang, Z., Satterthwait, A. C., & Reed, J. C. (2008).
    Differential regulation of Bax and Bak by anti-apoptotic Bcl-2 family
    proteins Bcl-B and Mcl-1. The Journal of biological chemistry, 283(15),
    9580-9586.  `doi:10.1074/jbc.M708426200`
    """

    bind_table([[                            Bcl2,  BclxL(state='M'),Mcl1(state='M')],
                [Bax(active_monomer), 10e-9*N_A*V,       10e-9*N_A*V,         None],
                [Bak(active_monomer),        None,       50e-9*N_A*V,  10e-9*N_A*V]],
               kf=1e6/(N_A*V))

def lopez_pore_formation(do_pore_transport=True):
    """ Pore formation and transport process used by all modules.
    """
    alias_model_components()

    # Rates
    pore_max_size = 4
    pore_rates = [[2.040816e-04,  # 1.0e-6/v**2
                   1e-3]] * (pore_max_size - 1)
    pore_transport_rates = [[2.857143e-5, 1e-3, 10]] # 2e-6 / v?

    # Pore formation by effectors
    assemble_pore_sequential(Bax(bf=None, state='A'), pore_max_size, pore_rates)
    assemble_pore_sequential(Bak(bf=None, state='A'), pore_max_size, pore_rates)

    # CytoC, Smac release
    if do_pore_transport:
        pore_transport(Bax(bf=None, state='A'), pore_max_size, CytoC(state='M'),
                       CytoC(state='C'), pore_transport_rates)
        pore_transport(Bax(bf=None, state='A'), pore_max_size, Smac(state='M'),
                       Smac(state='C'), pore_transport_rates)
        pore_transport(Bak(bf=None, state='A'), pore_max_size, CytoC(state='M'),
                       CytoC(state='C'), pore_transport_rates)
        pore_transport(Bak(bf=None, state='A'), pore_max_size, Smac(state='M'),
                       Smac(state='C'), pore_transport_rates)

# MOMP model implementations
# ==========================

def embedded(do_pore_transport=True):
    """ Direct and indirect modes of action, occurring at the membrane.
    """
    alias_model_components()

    declare_initial_conditions()

    translocate_tBid_Bax_BclxL()

    tBid_activates_Bax_and_Bak()

    # Autoactivation: Bax and Bak activate their own kind, but only when
    # free (i.e. not part of a pore complex)
    catalyze(Bax(active_monomer), Bax(state='M'), Bax(state='A'),
             activation_rates)
    catalyze(Bak(active_monomer), Bak(state='M'), Bak(state='A'),
             activation_rates)

    # Anti-apoptotics bind activator tBid
    # Doug Green's "MODE 1" inhibition
    tBid_binds_all_anti_apoptotics()

    # Anti-apoptotics bind activated effectors
    # Doug Green's "MODE 2" inhibition
    effectors_bind_anti_apoptotics()

    sensitizers_bind_anti_apoptotics()

    # Bax and Bak form pores by sequential addition and transport CytoC/Smac
    lopez_pore_formation(do_pore_transport=do_pore_transport)

def indirect(do_pore_transport=True):
    """Bax and Bak spontaneously form pores without activation.
       The "activator" tBid binds all of the anti-apoptotics.
    """
    alias_model_components()

    declare_initial_conditions()

    translocate_tBid_Bax_BclxL()

    # Bax and Bak spontaneously become activated
    free_Bax = Bax(bf=None, s1=None, s2=None) # Alias
    free_Bak = Bak(bf=None, s1=None, s2=None) # Alias
    free_Bax = Bax(bf=None, s1=None, s2=None) # Alias for readability
    equilibrate(free_Bax(state='C'), free_Bax(state='M'),
                transloc_rates)
    equilibrate(free_Bax(state='M'), free_Bax(state='A'), transloc_rates)
    equilibrate(free_Bak(state='M'), free_Bak(state='A'), transloc_rates)

    # Anti-apoptotics bind activator tBid
    # Doug Green's "MODE 1" inhibition
    tBid_binds_all_anti_apoptotics()

    # Anti-apoptotics bind activated effectors
    # Doug Green's "MODE 2" inhibition
    effectors_bind_anti_apoptotics()

    sensitizers_bind_anti_apoptotics()

    # Bax and Bak form pores by sequential addition
    lopez_pore_formation(do_pore_transport=do_pore_transport)

def direct(do_pore_transport=True):
    """Anti-apoptotics prevent BH3-onlies from activating Bax and Bak.

    Bax and Bak require activation to be able to form pores.
    The anti-apoptotics don't inhibit activated Bax and Bak; their only role
    is to bind BH3-onlies.
    """

    alias_model_components()
    declare_initial_conditions()

    translocate_tBid_Bax_BclxL()

    tBid_activates_Bax_and_Bak()

    # Anti-apoptotics bind activator tBid
    # Doug Green's "MODE 1" inhibition
    tBid_binds_all_anti_apoptotics()

    sensitizers_bind_anti_apoptotics()

    # Bax and Bak form pores by sequential addition
    lopez_pore_formation(do_pore_transport=do_pore_transport)


import torch
from torch_geometric.data import HeteroData
import torch_geometric.transforms as T
from typing import List

class TSPInstance:
    def __init__(self, filename):
        self.filename = filename
        self.distance_matrix = None
        self.connectivity = None
        self.optimal_tour = None
        self.parse_instance()

    def parse_instance(self):
        with open(self.filename, 'r') as f:
            lines = f.readlines()
            i = 0
            while i < len(lines):
                if lines[i].startswith('DIMENSION'):
                    self.dimension = int(lines[i].split(':')[1].strip())
                elif lines[i].startswith('EDGE_WEIGHT_TYPE'):
                    self.edge_weight_type = lines[i].split(':')[1].strip()
                elif lines[i].startswith('EDGE_WEIGHT_FORMAT'):
                    self.edge_weight_format = lines[i].split(':')[1].strip()
                elif lines[i].startswith('EDGE_DATA_SECTION'):
                    i += 1
                    edges = []
                    while lines[i].strip() != '-1':
                        edges.append(list(map(int, lines[i].strip().split())))
                        i += 1
                    self.connectivity = len(edges) / (self.dimension * (self.dimension - 1) / 2)
                elif lines[i].startswith('EDGE_WEIGHT_SECTION'):
                    i += 1
                    self.distance_matrix = []
                    for j in range(self.dimension):
                        row = list(map(float, lines[i+j].strip().split()))
                        self.distance_matrix.append(row)
                elif lines[i].startswith('TOUR_SECTION'):
                    i += 1
                    self.optimal_tour = list(map(int, lines[i].strip().split()))
                elif lines[i].startswith("OPTIMAL_VALUE"):
                    i += 1
                    self.optimal_value = float(lines[i].strip())
                i += 1

    def get_dtsp_specific_representation(self, target_deviation):
        """Build the graph representation used in the Prates DTSP paper.
        This representation takes a TSP instance and builds a bipartite graph where node types are:
         - cities (nodes in the base instance)
         - arcs (edges in the base instance)
        The nodes are connected if an arc is connected to a city in the base graph
        Cities have a feature vector of 1s, while arcs have a feature vector of [w, C], where w is the edge weight and C is the target
        cost for the decision TSP.

        Args:
            target_cost (float): the target deviation cost for the decision TSP, in percentage. For example, 0.02 means that the target cost is 2% more
            or less than the optimal cost.

        Returns:
            data (tuple(torch_geometric.data.HeteroData)): graph for the DTSP problem, one for the positive instance (cost = optimal value + target_deviation * optimal_value)
             and one for the negative instance (cost = optimal value - target_deviation * optimal_value)
             labels are stored in data.label
        """
        target_cost_positive = self.optimal_value * (1 + target_deviation)
        target_cost_negative = self.optimal_value * (1 - target_deviation)
        # Nodes and node stuff
        cities = []
        arcs = []
        arc_features_positive = []
        arc_features_negative = []
        arcs_to_id_mapping = {}
        arc_counter = 0
        for i in range(self.dimension):
            cities.append([1])
            for j in range(i+1, self.dimension):
                arcs.append([i, arc_counter])
                arcs.append([j, arc_counter])
                distance = self.distance_matrix[i][j]
                arc_features_positive.append([distance, target_cost_positive])
                arc_features_negative.append([distance, target_cost_negative])
                arcs_to_id_mapping[(i, j)] = arc_counter
                arc_counter += 1

        data_positive, data_negative = HeteroData(), HeteroData()
        data_positive["city"].x = torch.Tensor(cities)
        data_positive["arc"].x = torch.Tensor(arc_features_positive)
        data_positive["city", "connected_to", "arc"].edge_index = self.build_edge_index_tensor(arcs)
        data_positive.filename = self.filename
        data_positive.label = 1
        T.ToUndirected()(data_positive)

        data_negative["city"].x = torch.Tensor(cities)
        data_negative["arc"].x = torch.Tensor(arc_features_negative)
        data_negative["city", "connected_to", "arc"].edge_index = self.build_edge_index_tensor(arcs)
        data_negative.filename = self.filename
        data_negative.label = 0
        T.ToUndirected()(data_negative)

        return data_positive, data_negative

    def get_circuit_based_representation(self, target_deviation):
        """
        CP Model for the Traveling Salesman Problem (TSP) with Circuit constraint

        Parameters:
            distances (matrix of floats): Distance matrix where distances[i][j] represents the distance between node i and node j.

        Variables:
            x (array of ints): Values are the successor node
            distance (float): total distance traveled. - OPTIONAL, not implemented

        Objective:
            Minimize the total distance traveled.

        Constraints:
            1. All nodes must be visited exactly once: AllDifferent(x)
            2. Circuit constraint: Circuit(x)

        Operators:
            1. Distances are represented as operators between

        Args:
            target_cost (float): the target deviation cost for the decision TSP, in percentage. For example, 0.02 means that the target cost is 2% more
            or less than the optimal cost.

        Returns:
            data (tuple(torch_geometric.data.HeteroData)): graph for the DTSP problem, one for the positive instance (cost = optimal value + target_deviation * optimal_value)
             and one for the negative instance (cost = optimal value - target_deviation * optimal_value)
             labels are stored in data.label
        """
        target_cost_positive = self.optimal_value * (1 + target_deviation)
        target_cost_negative = self.optimal_value * (1 - target_deviation)

        x_features_positive = [[1, target_cost_positive] for _ in range(self.dimension)]
        x_features_negative = [[1, target_cost_negative] for _ in range(self.dimension)]
        values = [[1] for i in range(self.dimension)]
        constraints = [[1, 0], [0, 1]] # Circuit and AllDifferent Constraints
        x_to_constraint_edges = []

        for i in range(self.dimension):
            x_to_constraint_edges.append([i, 0])
            x_to_constraint_edges.append([i, 1])

        values_to_x_edges = []
        for i in range(self.dimension):
            for j in range(self.dimension):
                if i != j:
                    values_to_x_edges.append([i, j])

        distance_parameters_features = []
        distance_parameter_to_x_edges = []
        distance_parameter_to_value_edges = []
        distance_parameter_counter = 0

        for i in range(self.dimension):
            for j in range(i+1, self.dimension):
                distance = self.distance_matrix[i][j]
                distance_parameters_features.append([distance])
                distance_parameter_to_x_edges.append([distance_parameter_counter, i])
                distance_parameter_to_x_edges.append([distance_parameter_counter, j])
                distance_parameter_to_value_edges.append([distance_parameter_counter, i])
                distance_parameter_to_value_edges.append([distance_parameter_counter, j])
                distance_parameter_counter += 1

        data_positive, data_negative = HeteroData(), HeteroData()

        data_positive["x"].x = torch.Tensor(x_features_positive)
        data_positive["constraint"].x = torch.Tensor(constraints)
        data_positive["value"].x = torch.Tensor(values)
        data_positive["operator"].x = torch.Tensor(distance_parameters_features)
        data_positive["x", "involved_in", "constraint"].edge_index = self.build_edge_index_tensor(x_to_constraint_edges)
        data_positive["x", "has_value", "value"].edge_index = self.build_edge_index_tensor(values_to_x_edges)
        data_positive["operator", "has_parameter", "x"].edge_index = self.build_edge_index_tensor(distance_parameter_to_x_edges)
        data_positive["operator", "has_parameter", "value"].edge_index = self.build_edge_index_tensor(distance_parameter_to_value_edges)
        data_positive.filename = self.filename
        data_positive.label = 1
        T.ToUndirected()(data_positive)

        data_negative["x"].x = torch.Tensor(x_features_negative)
        data_negative["constraint"].x = torch.Tensor(constraints)
        data_negative["value"].x = torch.Tensor(values)
        data_negative["operator"].x = torch.Tensor(distance_parameters_features)
        data_negative["x", "involved_in", "constraint"].edge_index = self.build_edge_index_tensor(x_to_constraint_edges)
        data_negative["x", "has_value", "value"].edge_index = self.build_edge_index_tensor(values_to_x_edges)
        data_negative["operator", "has_parameter", "x"].edge_index = self.build_edge_index_tensor(distance_parameter_to_x_edges)
        data_negative["operator", "has_parameter", "value"].edge_index = self.build_edge_index_tensor(distance_parameter_to_value_edges)
        data_negative.filename = self.filename
        data_negative.label = 0

        T.ToUndirected()(data_negative)

        return data_positive, data_negative

    def build_edge_index_tensor(self, edges:List)->torch.Tensor:
        return torch.Tensor(edges).long().t().contiguous()

if __name__ == "__main__":
    instance = TSPInstance('data/0.graph')
    instance.get_dtsp_specific_representation(0.02)
    a=1


from utils.node_utils import list_to_link

def getIntersectionNode(headA, headB):
    n1 = n2 = 0
    node1 = headA
    node2 = headB
    while node1 or node2:
        if node1:
            node1 = node1.next
            n1 += 1
        if node2:
            node2 = node2.next
            n2 += 1

    diff = abs(n1 - n2)
    if n1 > n2:
        for i in range(diff):
            headA = headA.next
    else:
        for i in range(diff):
            headB = headB.next

    while headA is not headB:
        headA = headA.next
        headB = headB.next

    return headA

if __name__ == '__main__':
    l1 = list_to_link([4, 1])
    l2 = list_to_link([5, 6, 1])
    intersection = list_to_link([8, 4, 5])
    l1.next.next = intersection
    l2.next.next.next = intersection
    assert getIntersectionNode(l1, l2) is intersection


# Source: https://leetcode.com/problems/word-pattern/description/
# Author: Paulo Lemus
# Date  : 2017-11-13
# Info  : #290, Easy, 69 ms, 22.58%

class Solution:
    # 69 ms, 22.58%
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        words = str.split()
        matcher = {}
        used_words = set()

        if len(pattern) != len(words):
            return False

        for idx, letter in enumerate(pattern):
            word = words[idx]
            if letter not in matcher and word not in used_words:
                matcher[letter] = word
                used_words.add(word)
            if word != matcher.get(letter):
                return False
        return True


"""Python wrapper for getting weather data from AccueWeather API."""

from __future__ import annotations

import logging
from http import HTTPStatus
from typing import TYPE_CHECKING, Any

import orjson
from aiohttp import ClientSession

from .const import (
    ATTR_CURRENT_CONDITIONS,
    ATTR_FORECAST_DAILY,
    ATTR_FORECAST_HOURLY,
    ATTR_GEOPOSITION,
    HTTP_HEADERS,
    LANGUAGE_MAP,
    REMOVE_FROM_CURRENT_CONDITION,
    REMOVE_FROM_FORECAST,
    REQUESTS_EXCEEDED,
)
from .exceptions import (
    ApiError,
    InvalidApiKeyError,
    InvalidCoordinatesError,
    RequestsExceededError,
)
from .utils import (
    construct_url,
    parse_current_condition,
    parse_daily_forecast,
    parse_hourly_forecast,
    valid_api_key,
    valid_coordinates,
)

_LOGGER = logging.getLogger(__name__)

class AccuWeather:
    """Main class to perform AccuWeather API requests."""

    def __init__(  # noqa: PLR0913
        self,
        api_key: str,
        session: ClientSession,
        latitude: float | None = None,
        longitude: float | None = None,
        location_key: str | None = None,
        language: str = "en",
    ) -> None:
        """Initialize."""
        if not valid_api_key(api_key):
            raise InvalidApiKeyError(
                "Your API Key must be a 32-character hexadecimal string"
            )
        if not location_key and not valid_coordinates(latitude, longitude):
            raise InvalidCoordinatesError("Your coordinates are invalid")

        self.latitude = latitude
        self.longitude = longitude
        self.language = LANGUAGE_MAP.get(language, "en-us")
        self._api_key = api_key
        self._session = session
        self._location_key = location_key
        self._location_name: str | None = None
        self._requests_remaining: int | None = None

    async def _async_get_data(self, url: str) -> Any:
        """Retrieve data from AccuWeather API."""
        async with self._session.get(url, headers=HTTP_HEADERS) as resp:
            if resp.status == HTTPStatus.UNAUTHORIZED.value:
                raise InvalidApiKeyError("Invalid API key")

            if resp.status != HTTPStatus.OK.value:
                error_text = orjson.loads(await resp.text())
                if error_text["Message"] == REQUESTS_EXCEEDED:
                    raise RequestsExceededError(
                        "The allowed number of requests has been exceeded"
                    )
                raise ApiError(f"Invalid response from AccuWeather API: {resp.status}")

            _LOGGER.debug("Data retrieved from %s, status: %s", url, resp.status)
            data = await resp.json()

        if resp.headers["RateLimit-Remaining"].isdigit():
            self._requests_remaining = int(resp.headers["RateLimit-Remaining"])

        if "hourly" in url:
            return data

        return data if isinstance(data, dict) else data[0]

    async def async_get_location(self) -> None:
        """Retrieve location data from AccuWeather."""
        url = construct_url(
            ATTR_GEOPOSITION,
            api_key=self._api_key,
            lat=str(self.latitude),
            lon=str(self.longitude),
            language=self.language,
        )
        data = await self._async_get_data(url)
        self._location_key = data["Key"]
        self._location_name = data["LocalizedName"]

    async def async_get_current_conditions(self) -> dict[str, Any]:
        """Retrieve current conditions data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_CURRENT_CONDITIONS,
            api_key=self._api_key,
            location_key=self._location_key,
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_current_condition(data, REMOVE_FROM_CURRENT_CONDITION)

    async def async_get_daily_forecast(
        self, days: int = 5, metric: bool = True
    ) -> list[dict[str, Any]]:
        """Retrieve daily forecast data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_FORECAST_DAILY,
            api_key=self._api_key,
            location_key=self._location_key,
            days=str(days),
            metric=str(metric).lower(),
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_daily_forecast(data, REMOVE_FROM_FORECAST)

    async def async_get_hourly_forecast(
        self, hours: int = 12, metric: bool = True
    ) -> list[dict[str, Any]]:
        """Retrieve hourly forecast data from AccuWeather."""
        if not self._location_key:
            await self.async_get_location()

        if TYPE_CHECKING:
            assert self._location_key is not None

        url = construct_url(
            ATTR_FORECAST_HOURLY,
            api_key=self._api_key,
            location_key=self._location_key,
            hours=str(hours),
            metric=str(metric).lower(),
            language=self.language,
        )
        data = await self._async_get_data(url)
        return parse_hourly_forecast(data, REMOVE_FROM_FORECAST)

    @property
    def location_name(self) -> str | None:
        """Return location name."""
        return self._location_name

    @property
    def location_key(self) -> str | None:
        """Return location key."""
        return self._location_key

    @property
    def requests_remaining(self) -> int | None:
        """Return number of remaining allowed requests."""
        return self._requests_remaining


# Hunter is derived from each of the Mobile_Simulton and Pulsator classes:
#   updating/displaying like a Pulsator, but also moving (either in a straight
#   line or in pursuit of Prey).

from prey import Prey
from pulsator import Pulsator
from mobilesimulton import Mobile_Simulton
from math import atan2

class Hunter(Pulsator, Mobile_Simulton):
    dist = 200
    def __init__(self,x,y):
        Pulsator.__init__(self,x,y)
        self.set_speed(5)
        self.randomize_angle()

    def update(self,model):
        Pulsator.update(self, model)
        p = model.find(lambda x: isinstance(x, Prey) and self.distance(x.get_location()) <=  Hunter.dist)

        if p:
            closest = min([(self.distance(prey.get_location()),prey) for prey in p], key = lambda x: x[0])

            angle = atan2(closest[1].get_location()[1] - self.get_location()[1], closest[1].get_location()[0] - self.get_location()[0])
            self.set_angle(angle)

        self.move()
        self.wall_bounce()

Inheritance and Animation (p.1)/hunter.py


from django.urls import path
from .views import contacto, contratacion, galeria, home, quienessomos, vercontrataciones, form_del_solicitud, form_mod_solicitud

urlpatterns = [
    path('', home,name="home"),
    path('galeria/', galeria, name='galeria'),
    path('quienessomos/', quienessomos, name='quienessomos'),
    path('contacto/', contacto, name='contacto'),
    path('contratacion/', contratacion, name='contratacion'),
    path('vercontrataciones/', vercontrataciones, name='vercontrataciones'),
    path('form_mod_solicitud/<id>', form_mod_solicitud, name="form_mod_solicitud"),
    path('form_del_solicitud/<id>', form_del_solicitud, name="form_del_solicitud")
]


# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

from HTMLParser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc

class _DeHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.__text = []

    def handle_data(self, data):
        text = data.strip()
        if len(text) > 0:
            self.__text.append(text)

    def handle_starttag(self, tag, attrs):
        if tag == 'br':
            self.__text.append('\n')
        if tag == 'h2':
            self.__text.append('\n')
        if tag == 'td':
            if self.__text[-1] != '\n':
                self.__text.append('\t')

    def handle_endtag(self, tag):
        if tag == 'tr':
            self.__text.append('\n')

    def text(self):
        return ''.join(self.__text).strip()

def dehtml(text):
    try:
        parser = _DeHTMLParser()
        parser.feed(text)
        parser.close()
        return parser.text()
    except:
        print_exc(file=stderr)
        return text

def get_years():
    import json

    my_syllabus = []

    if 'Autodetect course' not in request.vars.course:
        course = db(db.course.course == request.vars.course).select(db.course.id).first()
        syllabi = db(db.subject_course.course == course.id).select(db.subject_course.year, distinct=True)
        my_syllabus = [syllabus.year.year for syllabus in syllabi]

    return json.dumps(my_syllabus)

def index():
    import urllib

    courses = db(db.course.id > 0).select(orderby=db.course.course)
    my_course = ['Autodetect course']
    for course in courses: my_course.append(course.course)

    my_syllabus = ['Autodetect syllabus']

    form = SQLFORM.factory(
        Field('grades', 'text', label='Grades', requires=IS_NOT_EMPTY()),
        Field('course', 'list:string', requires=IS_IN_SET(my_course,labels=my_course, zero=None))
    )
    year = TR(LABEL('Curriculum'),SELECT('Autodetect curriculum', _id='no_table_curriculum', _name='curriculum', value='Autodetect curriculum'))
    form[0].insert(-1,year)

    contactme = SQLFORM(db.comments)

    subjects = None
    info = None
    mygrades = None
    mysubjects = None
    year = None
    pes = None
    cwts = None
    ges = None
    non_ges = None
    course = None
    notes = None
    c_notes = None
    changelog = db(db.changelog.id > 0).select(orderby=~db.changelog.timestamp, limitby=(0,5))

    if request.vars.bookmark:
        text = dehtml(urllib.unquote(request.vars.bookmark))
        form.vars.grades = text
        info,mygrades = parse(text)
        if info != 'Error':
            mysubjects,year,pes,cwts,ges,non_ges,course,notes,c_notes = parse_subjects(mygrades, info, 'Autodetect course', 'Autodetect curriculum')

    if form.accepts(request.vars, session, formname='form_one'):

        info,mygrades = parse(form.vars.grades)

        if info != 'Error':
            mysubjects,year,pes,cwts,ges,non_ges,course,notes,c_notes = parse_subjects(mygrades, info, form.vars.course,
                                         form.vars.curriculum)

    if contactme.accepts(request.vars, session, formname='form_two'):
        response.flash = 'Thank you for posting.'

    return dict(form=form, info=info, mygrades=mygrades, mysubjects=mysubjects, contactme=contactme,year=year,
            pes=pes,cwts=cwts,ges=ges,non_ges=non_ges,course=course,changelog=changelog,notes=notes,c_notes=c_notes)

def parse_subjects(mygrades, info, mycourse, myyear):

    courses = db(db.course.id > 0).select(orderby=db.course.course)

    if mycourse == 'Autodetect course':
        course = db(db.course.course == info['course']).select().first()
        if course is None:
            if 'Master ' in info['course']:
                return 'not BS',None,None,None,None,None,None,None,None
            else: return 'not supported',None,None,None,None,None,None,None,None
    else: course = db(db.course.course == mycourse).select().first()

    if myyear == 'Autodetect curriculum':
        studno = int(info['studno'][:4])
        syllabi = db(db.subject_course.course == course.id).select(db.subject_course.year, distinct=True)
        my_syllabus = [syllabus.year.year for syllabus in syllabi]
        year = filter(lambda x: x <= studno, my_syllabus)

        if len(year):
            syllabus = db(db.syllabus.year == max(year)).select().first()
        else: return 'too old',None,None,None,None,None,None,None,None

    else:
        syllabus = db(db.syllabus.year == int(myyear)).select().first()

        if len(db((db.subject_course.course == course.id) & (db.subject_course.year == syllabus.id)).select()) == 0:
            return 'not supported',None,None,None,None,None,None,None,None

    majors = db((db.subject_course.course == course.id) & (db.subject_course.year == syllabus.id))._select(db.subject_course.subject)

    major_subjects = db(db.subject.id.belongs(majors)).select()
    require = db(db.subject_requirements.course.contains(course.id)).select()
    prereqs = db((db.prerequisites.year == syllabus.id) & (db.prerequisites.course.contains(course.id))).select()
    coreqs = db((db.corequisites.year == syllabus.id) & (db.corequisites.course.contains(course.id))).select()

    notes = db(db.notes.course.contains(course.id)).select().first()
    c_notes = db(db.notes_curriculum.course.contains(course.id)).select().first()
    ges_domain = db(db.ge_domain.id > 0)._select(db.ge_domain.ge)
    ah = db(db.domains.domain == 'AH').select().first()
    ssp = db(db.domains.domain == 'SSP').select().first()
    mst = db(db.domains.domain == 'MST').select().first()
    ges_ah = db(db.ge_domain.domain == ah.id).select()
    ges_ssp = db(db.ge_domain.domain == ssp.id).select()
    ges_mst = db(db.ge_domain.domain == mst.id).select()
    ges = db(db.subject.id.belongs(ges_domain)).select()

    phil = db(db.phil_stud.id > 0)._select(db.phil_stud.ge)
    ges_phil_stud = db(db.subject.id.belongs(phil)).select()

    eng = db(db.english.id > 0)._select(db.english.ge)
    ges_english = db(db.subject.id.belongs(eng)).select()

    taken_majors = []
    taken_pes = []
    taken_non_majors = []
    taken_cwts = []
    taken_msts = []
    taken_ahs = []
    taken_ssps = []
    taken_phil_stud = []
    taken_english = []

    taken_mst = []
    taken_ah = []
    taken_ssp = []
    taken_phil = []
    taken_eng = []

    for sem in mygrades:
        semester = sem['sem'].replace('Semester', 'Sem').replace('20', '').replace('First','1st').replace('Second', '2nd')
        for subject in sem['subject']:
            subject['grade'] = subject['grade'].strip()
            if subject['subject'] == 'Bio 1': subject['subject'] = 'BIO 1'   #Fixed for Bio 1
            if ' III' in subject['subject']: subject['subject'] = subject['subject'].replace('III', '3')
            if ' II' in subject['subject']: subject['subject'] = subject['subject'].replace('II', '2')
            if ' I' in subject['subject']: subject['subject'] = subject['subject'].replace('I', '1')
            if subject['subject'] == 'Comm 3 Eng': subject['subject'] = 'Comm 3'   #Fixed for Comm 3
            if subject['subject'] == 'Humanidades 1': subject['subject'] = 'Humad 1' #Fixed for Humad 1

            blank = subject['grade'] == ''
            fail = '5.00' in subject['grade']
            ng = subject['grade'] == 'NG'
            inc = subject['grade'] == 'INC'
            four = subject['grade'] == '4.00'
            drp = subject['grade'] == 'DRP'
            f = 'F' in subject['grade']

            if not blank and not drp and not fail and not ng and not inc and not four and not f:
                if len(major_subjects.find(lambda row: row.name == subject['subject'])) != 0:
                    taken_majors.append(subject['subject'])
                elif subject['unit'].find('(') != -1:
                    if 'PE' in subject['subject']:
                        taken_pes.append({'subject':subject['subject'], 'sem':semester})
                    elif 'CWTS' in subject['subject']:
                        taken_cwts.append({'subject':subject['subject'], 'sem':semester})
                elif len(ges.find(lambda row: row.name == subject['subject'])) != 0:
                    ge = ges_ah.find(lambda row: row.ge.name == subject['subject']).first()
                    if ge is not None:
                        taken_ahs.append({'subject':subject['subject'], 'sem':semester, 'title':ge.ge.title, 'description':ge.ge.description})
                        taken_ah.append(subject['subject'])

                    ge = ges_mst.find(lambda row: row.ge.name == subject['subject']).first()
                    if ge is not None:
                        taken_msts.append({'subject':subject['subject'], 'sem':semester, 'title':ge.ge.title, 'description':ge.ge.description})
                        taken_mst.append(subject['subject'])

                    ge = ges_ssp.find(lambda row: row.ge.name == subject['subject']).first()
                    if ge is not None:
                        taken_ssps.append({'subject':subject['subject'], 'sem':semester, 'title':ge.ge.title, 'description':ge.ge.description})
                        taken_ssp.append(subject['subject'])

                    if len(ges_phil_stud.find(lambda row: row.name == subject['subject'])) != 0:
                        taken_phil_stud.append({'subject':subject['subject'], 'sem':semester})
                        taken_phil.append(subject['subject'])

                    if len(ges_english.find(lambda row: row.name == subject['subject'])) != 0:
                        taken_english.append({'subject':subject['subject'], 'sem':semester})
                        taken_eng.append(subject['subject'])

                else:
                    taken_non_majors.append({'subject':subject['subject'], 'sem':semester})

    if ('Math 53' in taken_majors or 'Math 100' in taken_majors) and 'Math 17' not in taken_majors: #APE
        if len(major_subjects.find(lambda row:row.name == 'Math 17')) != 0:
            taken_majors.append('Math 17')
            if 'Math 14' in taken_majors: taken_majors.remove('Math 14')
            if 'Math 11' in taken_majors: taken_majors.remove('Math 11')

            for subject in taken_non_majors:
                if subject['subject'] == 'Math 14':
                    taken_non_majors.remove(subject)
                    break
            for subject in taken_non_majors:
                if subject['subject'] == 'Math 11':
                    taken_non_majors.remove(subject)
                    break
        else:
            taken_majors.append('Math 11')
            taken_majors.append('Math 14')

    if 'Math 17' in taken_majors and len(major_subjects.find(lambda row:row.name == 'Math 17')) == 0:
        taken_majors.remove('Math 17')
        taken_majors.append('Math 14')
        taken_majors.append('Math 11')

        for subject in taken_non_majors:
            if subject['subject'] == 'Math 17':
                taken_non_majors.remove(subject)
                break

    taken_ges = {'mst':taken_msts, 'ah':taken_ahs, 'ssp':taken_ssps, 'phil_stud':taken_phil_stud,
                    'english':taken_english, 'others':taken_non_majors}

    eligible = []
    not_taken_majors = db(~db.subject.name.belongs(taken_majors) & db.subject.id.belongs(majors)).select()

    _msts = db(db.subject.name.belongs(taken_mst))._select(db.subject.id)
    not_taken_msts =  db(~db.ge_domain.ge.belongs(_msts) & (db.ge_domain.domain == mst.id)).select()
    _ssps = db(db.subject.name.belongs(taken_ssp))._select(db.subject.id)
    not_taken_ssps =  db(~db.ge_domain.ge.belongs(_ssps) & (db.ge_domain.domain == ssp.id)).select()
    _ahs = db(db.subject.name.belongs(taken_ah))._select(db.subject.id)
    not_taken_ahs =  db(~db.ge_domain.ge.belongs(_ahs) & (db.ge_domain.domain == ah.id)).select()
    _phil = db(db.subject.name.belongs(taken_phil))._select(db.subject.id)
    not_taken_phils =  db(~db.phil_stud.ge.belongs(_phil)).select()
    _eng = db(db.subject.name.belongs(taken_eng))._select(db.subject.id)
    not_taken_eng =  db(~db.english.ge.belongs(_eng)).select()

    not_taken_ges = {'mst':not_taken_msts, 'ssp':not_taken_ssps, 'ah':not_taken_ahs, 'phil_stud':not_taken_phils, 'english':not_taken_eng}

    mysubjects = {}
    mysubjects['elig'] = []
    mysubjects['non_elig'] = []
    mysubjects['senior'] = []

    for subject in not_taken_majors:
        if len(require.find(lambda row: row.subject == subject.id)) == 1:
            req = require.find(lambda row: row.subject == subject.id).first()
            mysubjects['senior'].append({'subject':subject.name, 'requirements':req.requirements})
        elif len(prereqs.find(lambda row: row.subject == subject.id)) == 0:
            coreq = coreqs.find(lambda row: row.subject == subject.id)
            if len(coreq):
                core = []
                for co in coreq:
                    core.append(co.coreq.name)
                mysubjects['elig'].append({'subject':subject.name, 'coreq':', '.join(core)})
            else: mysubjects['elig'].append({'subject':subject.name, 'coreq':''})
        else:
            prereq_sub = []
            prereq = prereqs.find(lambda row: row.subject.id == subject.id)
            count = 0

            for subj in prereq:
                if subj.prereq.name not in taken_majors: prereq_sub.append(subj.prereq.name)
                else: count = count + 1

            if count == len(prereq):
                coreq = coreqs.find(lambda row: row.subject == subject.id)

                if len(coreq):
                    core = []
                    for co in coreq:
                        core.append(co.coreq.name)
                    mysubjects['elig'].append({'subject':subject.name, 'coreq':','.join(core)})
                else: mysubjects['elig'].append({'subject':subject.name, 'coreq':''})
            else:
                coreq = coreqs.find(lambda row: row.subject == subject.id)
                if len(coreq):
                    core = []
                    for co in coreq:
                        core.append(co.coreq.name)
                    mysubjects['non_elig'].append({'subject':subject.name, 'prereq':', '.join(prereq_sub), 'coreq':', '.join(core)})
                else: mysubjects['non_elig'].append({'subject':subject.name, 'prereq':', '.join(prereq_sub), 'coreq':''})

    return mysubjects, syllabus.year, taken_pes, taken_cwts, taken_ges, not_taken_ges, course.course, notes, c_notes

def parse(grades):
    index = grades.find('View Grades')
    if index == -1: return 'Error',None
    grades = grades[index:]
    lines = grades.splitlines()

    if 'Load another student' in lines[1]: del lines[1]

    if len(lines) < 5: return 'Error',None

    name, studno, course = lines[1:4]

    info = {}
    info['name'] = name
    info['studno'] = studno
    info['course'] = course

    mygrades = []

    more_than_one = 0
    for line in lines[5:]:
        if 'Summer' in line or 'Semester' in line:
            mygrades.append({'sem':line})
            mygrades[-1]['subject'] = []
        elif more_than_one:
            l = line.split('\t')
            if len(l) == 4:
                unit, grade = l[-3], l[-2]
                mygrades[-1]['subject'][-1]['unit'] = unit
                mygrades[-1]['subject'][-1]['grade'] = grade
                more_than_one = 0
        elif 'Class Code' in line: continue
        elif len(line) == 0: continue
        elif 'NOTICE' in line: break
        elif 'Unresolved INC or 4.00' in line: break
        else:
            l = line.split('\t')
            if len(l) == 3:
                subj = l[1][:l[1].rfind(' ')]
                mygrades[-1]['subject'].append({'subject':subj})
                more_than_one = 1
            elif len(l) == 6:
                subj,unit, grade = l[1][:l[1].strip().rfind(' ')],l[-3], l[-2]
                mygrades[-1]['subject'].append({'subject':subj,'unit':unit,'grade':grade})
    return info, mygrades


from django.shortcuts import render, get_object_or_404
from rest_framework import views
from rest_framework.response import Response
from datetime import date, timedelta, datetime
from news.serializers import *
from events.serializers import *
from .serializers import *

class AllTrends(views.APIView):
    def get(self, request):
        serializerTrends = TrendSerializer(Trend.objects.all(), many=True)
        return Response(serializerTrends.data)

class TrendDetail(views.APIView):
    def get(self, request, pk):
        id = int(pk)
        trend = get_object_or_404(Trend, id=id)
        serializerTrend = TrendDetailSerializer(trend).data
        serializerTrend["directions"] = DirectionSerializer(Direction.objects.filter(id_fk=trend), many=True).data
        serializerTrend["documents"] = TrendsDocumentsSerializer(TrendsDocuments.objects.filter(id_fk=trend), many=True).data
        return Response(serializerTrend)

class TrendDetailNews(views.APIView):
    def get(self, request, pk, page):
        id = int(pk)
        offset = int(page)
        trend = get_object_or_404(Trend, id=id)
        news = News.objects.filter(directions__id_fk = trend).distinct()[offset:offset+6]
        serializerDirectionNews = NewsPartBlockSerializer(news, many=True)
        dataDirectionNews = serializerDirectionNews.data
        from image_cropping.utils import get_backend
        for news in dataDirectionNews:
            ID = news.get("id")
            obj = News.objects.get(id=ID)
            image = get_backend().get_thumbnail_url(
                obj.imageOld,
                {
                    'size': (300, 300),
                    'box': obj.image,
                    'crop': True,
                    'detail': True,
                }
            )
            news['image'] = image
        return Response(dataDirectionNews)

class TrendDetailEvents(views.APIView):
    def get(self, request, pk, page):
        id = int(pk)
        offset = int(page)
        trend = get_object_or_404(Trend, id=id)
        events = Event.objects.filter(directions__id_fk = trend).distinct()[offset:offset+6]
        serializerDirectionEvents = EventBlockSerializer(events, many=True)
        dataDirectionEvents = serializerDirectionEvents.data
        from image_cropping.utils import get_backend
        for event in dataDirectionEvents:
            ID = event.get("id")
            obj = Event.objects.get(id=ID)
            image = get_backend().get_thumbnail_url(
                obj.imageOld,
                {
                    'size': (390, 280),
                    'box': obj.image,
                    'crop': True,
                    'detail': True,
                }
            )
            event['image'] = image
        return Response(dataDirectionEvents)


from collections import deque
def solution(targets):
    answer = 0
    targets = deque(sorted(targets, key = lambda x : x[1]))
    tmp = targets.popleft()
    shot = tmp[1] - 0.5
    while targets:
        tmp = targets.popleft()
        if shot < tmp[0]:
            answer += 1
            shot = tmp[1] - 0.5
    return answer + (shot > tmp[0])