import code
import brackets
import sys
import argparse
import brackets.importer
from brackets.helpers import eval, exec, compile
from brackets import exception_handler

USAGE = "%(prog)s [-h | -c cmd | file | -] [arg] ..."
VERSION = "%(prog)s " + brackets.__version__
EPILOG = """  file         program read from script
  -            program read from stdin
  [arg] ...    arguments passed to program in sys.argv[1:]
"""
BANNER = "Brackets %s\nRunning Python %s on %s\n" % (brackets.__version__, sys.version, sys.platform)

class Console(code.InteractiveConsole):
    def __init__(self, spy=False, source='', *args, **kwargs):
        self.spy = spy
        super().__init__(*args, **kwargs)
        self.runsource('from brackets import *')
        if source:
            self.runsource(source)

    def runsource(self, source, filename="<input>", symbol="single"):
        try:
            code, debug, original = brackets.translate(source)
        except:
            if source.endswith('\n'):
                # Case 1
                self.showsyntaxerror(filename)
                return False
            else:
                return True

        if code is None:
            # Case 2
            return True

        # Case 3
        if self.spy:
            print(('-'*80)+'\n{0}'.format(code)+('-'*80))
        self.runcode(code)
        return False

def shell(scriptname, argv):
    parser = argparse.ArgumentParser(
        prog="brackets",
        usage=USAGE,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=EPILOG)

    parser.add_argument("-c", dest="command",
                        help="program passed in as a string")

    parser.add_argument("--spy", action="store_true",
                        help="print equivalent Python code before executing")

    parser.add_argument("-v", "--version", action="version", version=VERSION)

    # this will contain the script/program name and any arguments for it.
    parser.add_argument('args', nargs=argparse.REMAINDER,
                        help=argparse.SUPPRESS)

    # stash the brackets executable in case we need it later
    # mimics Python sys.executable
    brackets.executable = argv[0]

    options = parser.parse_args(argv[1:])

    # reset sys.argv like Python
    sys.argv = options.args

    if options.command:
        # User did "brackets -c ..."
        return run_command(options.command)

    if options.args:
        if options.args[0] == "-":
            # Read the program from stdin
            return run_command(sys.stdin.read())

        else:
            # User did "brackets <filename>"
            return run_file(options.args[0])

    # User did NOTHING!
    return run_repl(spy=options.spy)

def run_repl(spy):
    sys.exit(Console(spy).interact(banner=BANNER))

def run_command(command):
    code, debug, original = brackets.translate(command)
    try:
        sys.exit(Console().runcode(code))
    except Exception as e:
        exception_handler(e, debug, original)

def run_file(file):
    brackets.importer.BracketsLoader('__brackets_main__', file).load_module('__brackets_main__')

def main():
    sys.exit(shell("brackets", sys.argv))

if __name__ == '__main__':
    main()


from datetime import datetime
import time
import threading

class LatencyTracker:
  def __init__(self, network_handler):
    self.last_mesuraments = []
    self.network_handler = network_handler

  def is_latency_packet(self, output):
    splited_output = output.split("\n")
    if len(output) <= 1: return False
    header = output[0].split()
    if len(header) <= 1: return False
    if header[0] != "PINL" or header[0] != "200": return False
    return True

  def start_tracking(self):
    thread = threading.Thread(self.send_latency_packets)
    thread.start()

  def send_latency_packets(self):
    while True:
      self.network_handler.send_message("PINL")
      initial_time = datetime.now().timestamp()
      self.last_initial_time = initial_time
      time.sleep(20)

  def send_latency_response(self, connection_socket):
    arrival_time = datetime.now().timestamp()
    connection_socket.sendall(f"PINL 200\n{arrival_time}")

  def store_mesurament(self, latency_packet):
    arrival_time = latency_packet.split('\n')[1]
    new_mesurament = self.Latency(self.last_initial_time, arrival_time)
    self.last_mesuraments.append(new_mesurament)

  def __str__(self):
    mesuraments = len(self.last_mesuraments)
    if mesuraments == 0:
      return "No latency mesurament done yet."
    final_srt = ""
    for mesurament in self.last_mesuraments:
      final_srt = final_srt + str(mesurament)

  class Latency:
    def __init__(self, initial_time, arrival_time):
      self.initial_time = initial_time
      self.arrival_time = arrival_time
      self.interval = round((arrival_time - initial_time) * 1000, 2)

    def __str__(self):
      datetime_obj = datetime.utcfromtimestamp(int(self.initial_time))
      datetime_str = datetime_obj.strftime("%H:%M:%S - %d:%m:%y")
      return f"Latency(ms): {self.interval}\nTime of Mesurament: {datetime_str}\n"


# Emanuel Estrada
# Maximo Bautista
# Sebastian Cedeño
# Georgina González
# Francisco Márquez

from python_speech_features import mfcc, logfbank
from scipy.io import wavfile
import numpy as np
import matplotlib.pyplot as plt
from hmmlearn import hmm
from sklearn.metrics import confusion_matrix
import itertools
import os
import glob
import os.path as path

class HMMTrainer(object):
  def __init__(self, model_name='GaussianHMM', n_components=4, cov_type='diag', n_iter=1000):
    self.model_name = model_name
    self.n_components = n_components
    self.cov_type = cov_type
    self.n_iter = n_iter
    self.models = []
    if self.model_name == 'GaussianHMM':
      self.model = hmm.GaussianHMM(n_components=self.n_components,        covariance_type=self.cov_type,n_iter=self.n_iter)
    else:
      raise TypeError('Invalid model type')

  def train(self, X):
    np.seterr(all='ignore')
    self.models.append(self.model.fit(X))
    # Run the model on input data
  def get_score(self, input_data):
    return self.model.score(input_data)

def plot_confusion_matrix():

    classes = ["Cough","No Cough"]

    plt.imshow(conf_matrix, interpolation='nearest', cmap=plt.cm.Blues)
    plt.colorbar()

    plt.title("Normalized Confusion Matrix")
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes)
    plt.yticks(tick_marks, classes)

    plt.ylabel('True')
    plt.xlabel('Predicted')

    for i in range(2):
        for j in range(2):
            c = round(conf_matrix[j,i], 5)
            plt.text(i, j, str(c), va='center', ha='center')

hmm_models = []
input_folder = '/private/tmp/detector-de-tos-markov/entrenamiento'

X = np.array([])

# Parse the input directory
for filename in os.listdir(input_folder):
    # Read the input file
    filepath = os.path.join(input_folder, filename)
    sampling_freq, audio = wavfile.read(filepath)
    # Extract MFCC features
    mfcc_features = mfcc(audio, sampling_freq, nfft=1200)
    # Append to the variable X
    if len(X) == 0:
        X = mfcc_features
    else:
        X = np.append(X, mfcc_features, axis=0)
print('X.shape =', X.shape)
# Train and save HMM model
hmm_trainer = HMMTrainer(n_components=1)
print("Start training")
hmm_trainer.train(X)
print("Finish training")

input_folder_tos = '/private/tmp/detector-de-tos-markov/prueba'

real = []
predicted = []

TP = 0
FP = 0
FN = 0
TN = 0

max_score = -9999999999999999999

for dir in os.listdir(input_folder_tos):
    directory = os.path.join(input_folder_tos, dir)
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        sampling_freq, audio = wavfile.read(filepath)
        mfcc_features = mfcc(audio, sampling_freq, nfft=1200)
        score = hmm_trainer.get_score(mfcc_features)
        if score > max_score:
            max_score = score

for dir in os.listdir(input_folder_tos):
    directory = os.path.join(input_folder_tos, dir)
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        sampling_freq, audio = wavfile.read(filepath)
        mfcc_features = mfcc(audio, sampling_freq, nfft=1200)
        score = hmm_trainer.get_score(mfcc_features)
        if dir == "notos":
            real_output = "No Cough"
        else:
            real_output = "Cough"

        output = "Cough"

        if (score * 100) / max_score > 55:
            max_score = score
            output = "No Cough"
        predicted.append(output)
        real.append(real_output)

        print("\nPREDICTED::", output)
        print("ACTUAL_VALUE:", real_output)

        if output == "Cough" and real_output == "Cough":
            TP += 1
            print("-> TRUE POSITIVE")
        elif output == "Cough" and real_output == "No Cough":
            FN += 1
            print("-> FALSE NEGATIVE")
        elif output == "No Cough" and real_output == "No Cough":
            TN += 1
            print("-> TRUE NEGATIVE")
        elif output == "No Cough" and real_output == "Cough":
            FP += 1
            print("-> FALSE POSITIVE")

print()

conf_matrix = np.matrix([[TP/(TP+FP), FP/(TP+FP)], [FN/(FN+TN), TN/(FN+TN)]])
print("\n", conf_matrix)
plot_confusion_matrix()

TP = conf_matrix[0,0]
FP = conf_matrix[0,1]
FN = conf_matrix[1,0]
TN = conf_matrix[1,1]

acc = (TP + TN) / (TP + FP + FN + TN)
rec = TP / (TP + FN)
pre = TP / (TP + FP)
fms = (2 * rec * pre) / (rec + pre)

print('\nAccuracy =', acc)
print('Recall =', rec)
print('Presicion =', pre)
print('F-measure =', fms)

plt.show()


from absl.testing import absltest
from connectomics.common import array
from connectomics.common import bounding_box
from connectomics.volume import base
import numpy as np
import numpy.testing as npt

Box = bounding_box.BoundingBox

class ShimVolume(base.BaseVolume):

  def __init__(self, *args, **kwargs):
    super(*args, **kwargs)
    self.called = False

  @property
  def shape(self) -> array.Tuple4i:
    return (1, 12, 11, 10)

class BaseVolumeTest(absltest.TestCase):

  def test_not_implemented(self):
    v = base.BaseVolume()

    for field in [
        'volume_size', 'voxel_size', 'shape', 'ndim', 'dtype', 'bounding_boxes'
    ]:
      with self.assertRaises(NotImplementedError):
        _ = getattr(v, field)

  def test_get_points(self):
    tself = self

    class GetPointsVolume(ShimVolume):

      def get_points(self, points):
        self.called = True
        tself.assertLen(points, 4)
        for i in range(1, 4):
          tself.assertLen(points[i], 3)
        return np.random.uniform(size=[1, 3, 3, 3])

    v = GetPointsVolume()
    _ = v[0, (1, 2, 3), (4, 5, 6), (7, 8, 9)]
    self.assertTrue(v.called)

    v = GetPointsVolume()
    _ = v[0, [1, 2, 3], [4, 5, 6], [7, 8, 9]]
    self.assertTrue(v.called)

  def test_get_slices(self):
    tself = self

    expected = (
        slice(0, 1, None),
        slice(1, 3, 1),
        slice(5, 11, 1),
        slice(0, 10, 1),
    )

    class GetSlicesVolume(ShimVolume):

      def get_slices(self, slices):
        self.called = True
        tself.assertLen(slices, 4)
        tself.assertEqual(expected, slices)
        shape = [(i.stop - i.start) for i in slices]
        data = np.random.uniform(size=shape)
        return data

    v = GetSlicesVolume()
    sv = v[0, 1:3, 5:, :]
    self.assertTrue(v.called)
    self.assertEqual(sv.data.shape, (1, 2, 6, 10))
    self.assertEqual(tuple(sv.bbox.start), (0, 5, 1))
    self.assertEqual(tuple(sv.bbox.end), (10, 11, 3))
    self.assertEqual(tuple(sv.bbox.size), (10, 6, 2))

    # Test accessing the data directly without the subvolume abstraction.
    v.called = False
    data = v.asarray[0, 1:3, 5:, :]
    self.assertTrue(v.called)
    self.assertEqual(data.shape, (1, 2, 6, 10))

  def test_write_points(self):
    tself = self

    expected = [1, 2, 3]

    class WritePointsVolume(ShimVolume):

      def write_points(self, points, values):
        self.called = True
        tself.assertLen(points, 4)
        for i in range(1, 4):
          tself.assertLen(points[i], 3)
        tself.assertLen(values, 3)
        npt.assert_array_equal(values, expected)

    v = WritePointsVolume()
    v[0, (1, 2, 3), (4, 5, 6), (7, 8, 9)] = np.array(expected)
    self.assertTrue(v.called)

  def test_write_slices(self):
    tself = self

    expected_slices = (
        slice(0, 1, None),
        slice(1, 3, 1),
        slice(5, 11, 1),
        slice(0, 10, 1),
    )

    expected_data = np.random.uniform(size=[1, 12, 11, 10])

    class WriteSlicesVolume(ShimVolume):

      def write_slices(self, slices, data):
        self.called = True
        tself.assertLen(slices, 4)
        tself.assertEqual(expected_slices, slices)
        npt.assert_array_equal(expected_data, data)

    v = WriteSlicesVolume()
    v[0, 1:3, 5:, :] = expected_data
    self.assertTrue(v.called)

  def test_clip_box(self):

    class GetPointsVolume(ShimVolume):

      @property
      def volume_size(self):
        return [4, 5, 6]

    v = GetPointsVolume()
    box = Box([1, 2, 3], [100, 200, 300])
    clipped = v.clip_box_to_volume(box)
    self.assertNotEqual(clipped, box)
    self.assertEqual(tuple(clipped.end), (4, 5, 6))

    v = GetPointsVolume()
    box = Box([0, 0, 0], [2, 1, 3])
    clipped = v.clip_box_to_volume(box)
    self.assertEqual(clipped, box)

  def test_get_bounding_boxes_or_full(self):

    volume_boxes = [
        Box([0, 0, 0], [11, 21, 31]),
    ]

    class BBoxVolume(ShimVolume):

      def __init__(self, boxes, size=None):
        super().__init__()
        if size is None:
          size = [10, 20, 30]
        self._boxes = boxes
        self._size = size

      @property
      def bounding_boxes(self):
        return self._boxes

      @property
      def volume_size(self):
        return self._size

    # Get bounding boxes from volume
    result = base.get_bounding_boxes_or_full(BBoxVolume(volume_boxes))
    self.assertLen(result, 1)
    self.assertEqual(tuple(result), tuple(volume_boxes))

    # Get full bounding box since there's none in the volume.
    result = base.get_bounding_boxes_or_full(BBoxVolume([]))
    self.assertLen(result, 1)
    self.assertEqual(tuple(result), (Box(
        [0, 0, 0],
        [10, 20, 30],
    ),))

    # Get bboxes not clipped to volume
    expected = [
        Box([0, 0, 4], [0, 0, 3]),
        Box([6, 7, 8], end=[10, 20, 30]),
    ]
    result = base.get_bounding_boxes_or_full(BBoxVolume([]), expected)
    self.assertLen(result, 2)
    self.assertEqual(tuple(result), tuple(expected))

    # Get bboxes clipped to volume
    expected = [
        Box([0, 0, 4], [0, 0, 3]),
        Box([6, 7, 8], end=[10, 20, 30]),
    ]
    result = base.get_bounding_boxes_or_full(
        BBoxVolume([]), [
            Box([-70, -3, 4], [1, 2, 3]),
            Box([6, 7, 8], end=[440, 234, 3222]),
        ],
        clip=True)
    self.assertLen(result, 2)
    self.assertEqual(tuple(result), tuple(expected))

if __name__ == '__main__':
  absltest.main()


#!/usr/bin/env python3
"""
    manual_update.py

    Part of Argostimè

    Standalone script to manually update the price of a product offer by product_offer_id.
"""

import sys
import logging

from argostime.models import ProductOffer
from argostime import create_app

app = create_app()
app.app_context().push()

try:
    product_offer_id: int = int(sys.argv[1])
except:
    print("No number given")
    sys.exit(-1)

offer: ProductOffer = ProductOffer.query.get(product_offer_id)

logging.debug("Found offer %s", product_offer_id)
logging.debug("Manually updating ProductOffer %s", offer)

try:
    offer.crawl_new_price()
except Exception as exception:
    logging.error("Received %s while updating price of %s, continuing...", exception, offer)


from __future__ import print_function
import re
import spacy
from pyclausie import ClausIE

nlp = spacy.load('en')
re_spaces = re.compile(r'\s+')

class Person(object):
    def __init__(self, name, likes=None, has=None, travels=None):
        self.name = name
        self.likes = [] if likes is None else likes
        self.has = [] if has is None else has
        self.travels = [] if travels is None else travels

    def __repr__(self):
        return self.name

class Pet(object):
    def __init__(self, pet_type, name=None):
        self.name = name
        self.type = pet_type

class Trip(object):
    def __init__(self, departs_on, departs_to):
        self.departs_on = departs_on
        self.departs_to = departs_to

persons = []
pets = []
trips = []

def get_data_from_file(file_path='./assignment_01.data'):
    with open(file_path) as infile:
        cleaned_lines = [line.strip() for line in infile if not line.startswith(('$$$', '###', '==='))]

    return cleaned_lines

def select_person(name):
    for person in persons:
        if person.name == name:
            return person

def add_person(name):
    person = select_person(name)

    if person is None:
        new_person = Person(name)
        persons.append(new_person)

        return new_person

    return person

def select_pet(name):
    for pet in pets:
        if pet.name == name:
            return pet

def add_pet(type, name=None):
    pet = None

    if name:
        pet = select_pet(name)

    if pet is None:
        pet = Pet(type, name)
        pets.append(pet)

    return pet

# select trip
def select_trip(departs_to):
    for trip in trips:
        if trip.departs_to == departs_to:
            return trip

# add trip
def add_trip(departs_on, departs_to):
    trip = select_trip(departs_to) # with respect to departs_to

    if trip is None:
        new_trip = Trip(departs_on, departs_to)
        trips.append(new_trip)
        return new_trip
    elif trip and len(trip.departs_on) == 0:
        trip.departs_on == departs_on
        return trip

    return trip

def get_persons_pet(person_name):

    person = select_person(person_name)

    for thing in person.has:
        if isinstance(thing, Pet):
            return thing

# get somebody some trip
def get_persons_trip(person_name):

    person = select_person(person_name)

    for thing in person.travels:
        if isinstance(thing, Trip):
            return thing

def process_data_from_input_file(triplet):
    """
    Process a relation triplet found by ClausIE and store the data

    find relations of types:
    (PERSON, likes, PERSON)
    (PERSON, has, PET)
    (PET, has_name, NAME)
    (PERSON, travels, TRIP)
    (TRIP, departs_on, DATE)
    (TRIP, departs_to, PLACE)

    :param triplet: The relation triplet from ClausIE
    :type triplet: tuple
    :return: a triplet in the formats specified above
    :rtype: tuple
    """

    sentence = triplet.subject + ' ' + triplet.predicate + ' ' + triplet.object
    doc = nlp(unicode(sentence))
    root = doc[0]
    for t in doc:
        if t.pos_ == 'VERB' and t.head == t:
            root = t
        # elif t.pos_ == 'NOUN'

    # also, if only one sentence
    # root = doc[:].root

    """
    CURRENT ASSUMPTIONS:
    - People's names are unique (i.e. there only exists one person with a certain name).
    - Pet's names are unique
    - The only pets are dogs and cats
    - Only one person can own a specific pet
    - A person can own only one pet
    """

    # Process (PERSON, likes, PERSON) relations
    if root.lemma_ == 'like':
        if triplet.subject in [e.text for e in doc.ents if e.label_ == 'PERSON' or e.label_ == 'ORG'] and triplet.object in [e.text for e in doc.ents if e.label_ == 'PERSON' or e.label_ == 'ORG'] and "n't" not in triplet.predicate:
            s = add_person(triplet.subject)
            o = add_person(triplet.object)
            s.likes.append(o)

    if root.lemma_ == 'be' and triplet.object.startswith('friends with'):
        fw_doc = nlp(unicode(triplet.object))
        with_token = [t for t in fw_doc if t.text == 'with'][0]
        # get text after with
        after_with = fw_doc.text.split(with_token.text+ ' ')[1]
        people = []
        for p in after_with.split(' '):
            if nlp(p)[0].tag_ == 'NNP':
                people.append(nlp(p)[0].text)
        # fw_who = [t for t in with_token.children if t.dep_ == 'pobj'][0].text
        # fw_who = [e for e in fw_doc.ents if e.label_ == 'PERSON'][0].text
        for p in people:
            if triplet.subject in [e.text for e in doc.ents if e.label_ == 'PERSON']:
                s = add_person(triplet.subject)
                o = add_person(p)
                s.likes.append(o)
                o.likes.append(s)
    if root.lemma_ == 'be' and triplet.object == 'friends':
        fw_doc = nlp(unicode(triplet.subject))
        and_token = [t for t in fw_doc if t.text == 'and']
        if and_token:
            and_token = and_token[0].text
        if and_token == 'and' and fw_doc[0].text in [e.text for e in doc.ents if e.label_ == 'PERSON'] and fw_doc[2].text in [e.text for e in doc.ents if e.label_ == 'PERSON']:
            s = add_person(fw_doc[0].text)
            o = add_person(fw_doc[2].text)
            s.likes.append(o)
            o.likes.append(s)

    # Process (PET, has, NAME) Mary's dog's name is Rover
    if triplet.subject.endswith('name') and ('dog' in triplet.subject or 'cat' in triplet.subject):
        obj_span = doc.char_span(sentence.find(triplet.object), len(sentence))

        # handle single names, but what about compound names? Noun chunks might help.
        if (len(obj_span) == 1 or len(obj_span) == 2) and obj_span[-1].pos_ == 'PROPN':
            name = triplet.object
            subj_start = sentence.find(triplet.subject)
            subj_doc = doc.char_span(subj_start, subj_start + len(triplet.subject))

            s_people = [token.text for token in subj_doc if token.ent_type_ == 'PERSON']
            assert len(s_people) == 1
            s_person = select_person(s_people[0])

            pet = get_persons_pet(s_person.name)

            pet.name = name
            s_person.has.append(pet)

    # Process (Who has dog)
    if root.lemma_ == 'have'and ('dog' in triplet.object or 'cat' in triplet.object):
        # find pets name and instantiate name empty str
        obj_span = doc.char_span(sentence.find(triplet.object), len(sentence))
        name = ''

        if obj_span[-1].pos_ == 'PROPN':
            name = obj_span[-1].text
        s = add_person(triplet.subject)
        s_pet_type = 'dog' if 'dog' in triplet.object else 'cat'
        pet = add_pet(s_pet_type, name)
        s.has.append(pet)

    date = [e.text for e in doc.ents if e.label_ == 'DATE']
    gpe = [e.text for e in doc.ents if e.label_ == 'GPE']
    person = [e.text for e in doc.ents if e.label_ == 'PERSON' or e.label_ == 'ORG']
    # if person and GPE exists, we add it into trip(departs_on, departs_to)
    if person and (gpe or date):
        s = add_person(triplet.subject)
        o = add_trip(date, gpe)
        s.travels.append(o)

def preprocess_question(question):
    # remove articles: a, an, the

    q_words = question.split(' ')

    # when won't this work?
    for article in ('a', 'an', 'the'):
        try:
            q_words.remove(article)
        except:
            pass

    return re.sub(re_spaces, ' ', ' '.join(q_words))

def has_question_word(string):
    # note: there are other question words
    for qword in ('who', 'what'):
        if qword in string.lower():
            return True

    return False

def make_sentence_from_triplet(triplet):
    return triplet.subject + ' ' + triplet.predicate + ' ' + triplet.object
def answer_question(question):
    cl = ClausIE.get_instance()
    # q_trip = cl.extract_triples([preprocess_question(question)])[0]
    # triplet_sentence = make_sentence_from_triplet(q_trip) + '?'
    # doc = nlp(unicode(triplet_sentence))
    doc = nlp(unicode(question))
    root = doc[:].root
    if root.text == "'s" and doc[-2].dep_ == 'pobj' and [t.text for t in doc.ents if t.label_ == 'PERSON']:
        answer = '{} has a {} named {}'
        ss = [t.text for t in doc.ents if t.label_ == 'PERSON'][0]
        pet = get_persons_pet(ss)
        if pet.type == doc[-2].text:
                print(answer.format(ss, doc[-2], pet.name))
        else:
            print('I dont know!')
    else:
        q_trip = cl.extract_triples([preprocess_question(question)])[0]
        triplet_sentence = make_sentence_from_triplet(q_trip) + '?'
        doc = nlp(unicode(triplet_sentence))
        doc = nlp(unicode(question))
        root = doc[:].root
        adv = doc[0]
        for t in doc:
            if t.pos_ == 'ADV':
                adv = t

        # (WHO, has, PET)
        # here's one just for dogs
        if q_trip.subject.lower() == 'who' and q_trip.object == 'dog':
            answer = '{} has a {} named {}.'
            # answer_set = set()
            for person in persons:
                pet = get_persons_pet(person.name)
                if pet and pet.type == 'dog':
                    print(answer.format(person.name, 'dog', pet.name))
        # here's one just for cats
        elif q_trip.subject.lower() == 'who' and q_trip.object == 'cat':
            answer = '{} has a {} named {}.'
            # answer_set = set()
            for person in persons:
                pet = get_persons_pet(person.name)
                if pet and pet.type == 'cat':
                    print(answer.format(person.name, 'cat', pet.name))

        # predicate includes like
        elif 'like' in q_trip.predicate:
            # Who likes Mary?
            if q_trip.subject.lower() == 'who':
                answer_set = set()
                answer = '{} likes {}.'

                liked_person = select_person(q_trip.object)

                for person in persons:
                    if person.name != q_trip.object and liked_person in person.likes:
                        new_answer = answer.format(person.name, liked_person.name)
                        answer_set.add(new_answer)
                print(answer_set if len(answer_set) != 0 else 'I dont know!')
            # Who does Joe like?
            elif q_trip.object.lower() == 'who':
                answer = '{} likes {}.'

                like_person = select_person(q_trip.subject)  # q.trip.subject == 'Joe'

                for person in persons:
                    if person.name == q_trip.subject:
                        for p in person.likes:
                            print(answer.format(like_person, p.name))
            # Does Bob like Sally?
            elif doc[1].ent_type_ == 'PERSON' and doc[3].ent_type_ == 'PERSON':
                subject = doc[1].text
                oobject = doc[3].text
                answer_set = set()
                answer = '{} {} likes {}.'
                for person in persons:
                    # print('Persons Name: '+person.name)
                    # print('Question subject ' + subject)
                    if person.name == subject:
                        for p in person.likes:
                            # print('Liked name: '+p.name)
                            # print('Liked name in question '+oobject)
                            if oobject == p.name:
                                new_answer = answer.format('Yes', subject, oobject)
                                answer_set.add(new_answer)
                print(answer_set if len(answer_set) != 0 else 'I dont know!')
                # new_answer  = answer.format('Yes,', subject, oobject)
                # answer_set.add(new_answer)
                # print(answer_set)
        # (WHO, going to| flying to| travelling to| visiting, PLACE)
        elif q_trip.subject.lower() == 'who':
            ent = [str(ent.text) for ent in doc.ents if ent.label_ == 'GPE']
            answer_set = set()
            answer = '{} {} to {}.'
            if ent:
                for person in persons:
                    person = select_person(person.name)
                    for trip in person.travels:
                        if ent == trip.departs_to:
                            new_answer = answer.format(person.name, root, ent[0])
                            answer_set.add(new_answer)
                print(answer_set)
            else:
                print('I dont know!')
        # When is someone going to smplace
        elif str(adv.lemma_) == 'when':
            ent = [str(ent.text) for ent in doc.ents if ent.label_ == 'GPE']
            answer_set = set()
            answer = '{} {} to {} on {}.'
            if ent:
                for person in persons:
                    person = select_person(person.name)
                    if q_trip.subject in person.name:
                        for trip in person.travels:
                            if ent == trip.departs_to:
                                new_answer = answer.format(person.name, root, ent[0], trip.departs_on[0])
                                # answer_set.append(new_answer) if new_answer not in answer_set
                                answer_set.add(new_answer)
                print(answer_set if len(answer_set) != 0 else 'I dont know!')

        else:
            print('I dont know!')

def main():
    sents = get_data_from_file()

    cl = ClausIE.get_instance()
    triples = cl.extract_triples(sents)
    for t in triples:
        r = process_data_from_input_file(t)
    # samp = process_data_from_input_file(triples[30])
    # samp1 = process_relation_triplet(triples[15])
    # doc = process_relation_triplet(u'Sally is going to Mexico some time in 2020.')
    question = ' '
    while question[-1] != '?':
        question = raw_input("Please enter your question: ")

        if question[-1] != '?':
            print('This is not a question... please try again')
    answer_question(question)

if __name__ == '__main__':
    main()


import requests
import re
import socket

def get_lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("1.1.1.1",80))
    ipaddr=s.getsockname()[0]
    s.close()

    return ipaddr

class Getmyip:
    def getip(self):
        try:
            myip = self.visit("http://www.ip.cn/")
        except:
            try:
                myip = self.visit("http://dir.twseo.org/ip-check.php")
            except:
                try:
                    myip = self.visit("http://ip111.cn/")
                    # if you want to add more,use the format "except try"
                    # make sure the most useful link be the first
                except:
                    print("Fail to get the Network ip.")
                    print("Get the LAN ip.")
                    myip = get_lan_ip()
        return myip

    def visit(self,url):
        opener = requests.get(url)
        # print(opener.url)
        if url == opener.url:
            str = opener.text
            print("IP information from",url)
        return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)

def get_network_ip():
    getmyip = Getmyip()
    localip = getmyip.getip()
    print(localip)
    return localip

get_network_ip()
# opener = requests.get("http://www.ip.cn/",timeout=20)
# str = opener.text
# print(str)


# !/usr/bin/env python
from baselines.common import set_global_seeds, tf_util as U
import gym, logging
from baselines import logger
from half_cheetah import *

def train(env_id, num_timesteps, seed, num_options,app, saves ,wsaves, epoch,dc,plots,w_intfc,switch,mainlr,intlr,piolr,fewshot,k):
    from baselines.ppoc_int import mlp_policy, pposgd_simple
    U.make_session(num_cpu=1).__enter__()
    set_global_seeds(seed)

    if env_id=="TMaze":
        from twod_tmaze import TMaze
        env=TMaze()
        env.seed(seed)
    else:
        env = gym.make(env_id)
        env._seed(seed)

    def policy_fn(name, ob_space, ac_space):
        return mlp_policy.MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space,
            hid_size=64, num_hid_layers=2, num_options=num_options, dc=dc, w_intfc=w_intfc,k=k)

    gym.logger.setLevel(logging.WARN)

    if num_options ==1:
        optimsize=64
    elif num_options ==2:
        optimsize=32
    else:
        optimsize=int(64/num_options)

    num_timesteps = num_timesteps #if env_id!="TMaze" else 5e5
    tperbatch = 2048 if not epoch else int(1e4)
    pposgd_simple.learn(env, policy_fn,
            max_timesteps=num_timesteps,
            timesteps_per_batch=tperbatch,
            clip_param=0.2, entcoeff=0.0,
            optim_epochs=10, optim_stepsize=mainlr, optim_batchsize=optimsize,
            gamma=0.99, lam=0.95, schedule='constant', num_options=num_options,
            app=app, saves=saves, wsaves=wsaves, epoch=epoch, seed=seed,dc=dc,plots=plots,
            w_intfc=w_intfc,switch=switch,intlr=intlr,piolr=piolr,fewshot=fewshot,k=k
        )
    env.close()

def main():
    import argparse
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--env', help='environment ID', default='TMaze')
    parser.add_argument('--timesteps', help='number of timesteps', type=int, default=1e6)
    parser.add_argument('--seed', help='RNG seed', type=int, default=1)
    parser.add_argument('--opt', help='number of options', type=int, default=2)
    parser.add_argument('--app', help='Append to folder name', type=str, default='')
    parser.add_argument('--saves', help='Save the returns at each iteration', dest='saves', action='store_true', default=False)
    parser.add_argument('--wsaves', help='Save the weights',dest='wsaves', action='store_true', default=False)
    parser.add_argument('--plots',  help='Plot some visualization', dest='plots', action='store_true', default=False)
    parser.add_argument('--switch', help='Switch task after 150 iterations', dest='switch', action='store_true', default=False)
    parser.add_argument('--fewshot', help='Value learning after 150 iterations', dest='fewshot', action='store_true', default=False)
    parser.add_argument('--nointfc', help='Disables interet functions', dest='w_intfc', action='store_false', default=True)
    parser.add_argument('--epoch', help='Load weights from a certain epoch', type=int, default=0)
    parser.add_argument('--dc', help='Deliberation cost  (not used)', type=float, default=0.)
    parser.add_argument('--mainlr', type=float, default=3e-4)
    parser.add_argument('--intlr', type=float, default=1e-4)
    parser.add_argument('--piolr', type=float, default=1e-4)
    parser.add_argument('--k', type=float, default=0., help='threshold for interest function')

    args = parser.parse_args()

    train(args.env, num_timesteps=args.timesteps, seed=args.seed, num_options=args.opt, app=args.app,
     saves=args.saves, wsaves=args.wsaves, epoch=args.epoch,dc=args.dc,plots=args.plots,
     w_intfc=args.w_intfc,switch=args.switch,mainlr=args.mainlr,intlr=args.intlr,piolr=args.piolr,fewshot=args.fewshot,k=args.k)

if __name__ == '__main__':
    main()


# Python imports
import os
import sys
# Flask
from flask import jsonify, make_response, send_from_directory
from flask_graphql import GraphQLView
from flask_cors import CORS
# Local
from modules import logger
from modules.app import create_app
from modules.app.database import db_session, init_db
from modules.app.schema import schema

app = create_app()
app.debug = True

default_query = '''
{
  Users {
    edges {
      node {
        id,
        username,
        email,
        password
        blog {
          id,
          title,
          text
        },
        role {
          id,
          name
        }
      }
    }
  }
}
'''.strip()

"""
:ROOT_PATH : Set root path
:PUBLIC_PATH : Always for joining react public index.html to ROOT_PATH
"""
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
os.environ.update({'ROOT_PATH': ROOT_PATH})
PUBLIC_PATH = os.path.join(ROOT_PATH, 'modules', 'client', 'public')

''' Set the view for Graphiql '''
view_func = GraphQLView.as_view(
    'graphql', schema=schema, graphiql=True)

""" logger object to output info and debug information """
LOG = logger.get_root_logger(os.environ.get(
    'ROOT_LOGGER', 'root'), filename=os.path.join(ROOT_PATH, 'output.log'))

PORT = os.environ.get('PORT')

app.add_url_rule('/graphql', view_func=view_func)

""" Sets routes for Flask """
@app.errorhandler(404)
def not_found(error):
    """ error handler """
    LOG.error(error)
    return make_response(jsonify({'error': 'Not Found'}), 404)

@app.route('/')
def index():
    """ serve index.html """
    return send_from_directory(PUBLIC_PATH, 'index.html')

@app.route('/login')
def login():
    """ serve index.html """
    return send_from_directory(PUBLIC_PATH, 'index.html')

@app.route('/register')
def register():
    """ serve route to register to index.html """
    return send_from_directory(PUBLIC_PATH, 'index.html')

@app.route('/<path:path>')
def static_proxy(path):
    """
    static folder serve
    :param path: to load all static files in `public`
    :return: the directory `public` with filename i.e. 404.html
    """
    file_name = path.split('/')[-1]
    dir_name = os.path.join(PUBLIC_PATH, '/'.join(path.split('/')[:-1]))
    return send_from_directory(dir_name, file_name)

@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

if __name__ == "__main__":
    init_db()
    CORS(app, resources={r'/graphql': {'origins': '*'}})
    LOG.info('running environment: {}'.format(os.environ.get('ENV')))
    app.config['DEBUG'] = os.environ.get('ENV') == 'development'
    app.run(host='0.0.0.0', port=int(PORT))


import asyncio
import json
import os
import random
import re
import textwrap
import time
import typing
from io import BytesIO

import aiohttp
import async_timeout
import discord
import gtts
from asyncdagpi import Client
from bottom import from_bottom, to_bottom
from cryptography.fernet import Fernet
from discord.ext import commands
from menus import menus
from PIL import Image, ImageDraw, ImageFont
from utils.asyncstuff import asyncexe
from utils.embed import embedbase
from utils.paginator import AnimePages

talk_token = os.getenv("talk_token")
rapid_api_key = os.getenv("rapid_api_key")
tenor_API_key = os.getenv("tenor_API_key")

class UrbanDictionaryPageSource(menus.ListPageSource):
    BRACKETED = re.compile(r'(\[(.+?)\])')

    def __init__(self, data):
        super().__init__(entries=data, per_page=1)

    def cleanup_definition(self, definition, *, regex=BRACKETED):
        def repl(m):
            word = m.group(2)
            return f'[{word}](http://{word.replace(" ", "-")}.urbanup.com)'

        ret = regex.sub(repl, definition)
        if len(ret) >= 2048:
            return ret[0:2000] + ' [...]'
        return ret

    def format_page(self, menu, entry):
        maximum = self.get_max_pages()
        title = f'{entry["word"]}: {menu.current_page + 1} / {maximum}' if maximum else entry[
            'word']
        embed = discord.Embed(title=title,
                              colour=0x00ff6a,
                              url=entry['permalink'])
        embed.set_footer(text=f'By {entry["author"]}')
        embed.description = self.cleanup_definition(
            f"**Definition:**\n {entry['definition']}\n**Example:**\n{entry['example']}"
        )

        try:
            up, down = entry['thumbs_up'], entry['thumbs_down']
        except KeyError:
            pass
        else:
            embed.add_field(name='Votes',
                            value=f"Thumbs Up {up} Thumbs Down {down}",
                            inline=False)

        try:
            date = discord.utils.parse_time(entry['written_on'][0:-1])
        except (ValueError, KeyError):
            pass
        else:
            embed.timestamp = date

        return embed

class fun(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.talk_channels = []

    async def get_quote(self):
        async with self.bot.session.get("https://leksell.io/zen/api/quotes/random") as resp:
            quotes = await resp.json()
        return quotes["quote"]

    async def getmeme(self):
        async with self.bot.session.get("https://meme-api.herokuapp.com/gimme") as resp:
            meme = await resp.text()
            meme = json.loads(meme)
            if meme["nsfw"] == True:
                return True
            link = meme["postLink"]
            title = meme["title"]
            nsfw = meme["nsfw"]
            image = meme["preview"][-1]
            return link, title, nsfw, image

    async def hug_(self):
        gifs = []
        async with self.bot.session.get(
                f"https://api.tenor.com/v1/search?q=animehug&key={tenor_API_key}&limit=50&contentfilter=low"
        ) as resp:
            text = await resp.text()
            text = json.loads(text)
            for i in text["results"]:
                for x in i["media"]:
                    gifs.append(x["gif"]["url"])
        return random.choice(gifs)

    async def tenor_(self, search):
        tenor_ = []
        async with self.bot.session.get(
                f"https://api.tenor.com/v1/search?q={search}&key={tenor_API_key}&limit=50&contentfilter=low"
        ) as resp:
            text = await resp.text()
            text = json.loads(text)
            for i in text["results"]:
                for x in i["media"]:
                    tenor_.append(x["gif"]["url"])
        return random.choice(tenor_)

    async def reddit_(self, text):
        async with self.bot.session.get(
                    f"https://meme-api.herokuapp.com/gimme/{text}") as resp:
            meme = await resp.text()
            meme = json.loads(meme)
            if meme["nsfw"] == True:
                return True
            link = meme["postLink"]
            title = meme["title"]
            nsfw = meme["nsfw"]
            image = meme["preview"][-1]
            return link, title, nsfw, image

    @staticmethod
    def bottoms(mode, text):
        if mode == "to_bottom":
            return to_bottom(text)
        else:
            return from_bottom(text)

    @commands.command()
    async def pic(self, ctx, animal: str):
        async with self.bot.session.get(f"https://some-random-api.ml/img/{animal}") as resp:
            if resp.status == 404:
                return await ctx.send("we can't find picture of that animal")
            pic = await resp.json()
            async with self.bot.session.get(pic["link"]) as resp:
                pic = BytesIO(await resp.read())
                await ctx.send(file=discord.File(pic, filename=animal+".png"))

    @commands.command()
    async def fact(self, ctx, animal: str):
        async with self.bot.session.get(f"https://some-random-api.ml/facts/{animal}") as resp:
            if resp.status == 404:
                return await ctx.send("we can't find fact about that animal")
            fact = await resp.json()
            await ctx.send(fact["fact"])

    @commands.command()
    async def hi(self, ctx):
        await ctx.send("H")

    @commands.command()
    async def http(self, ctx, *, code: str = "404"):
        async with self.bot.session.get(
                f"https://http.cat/{code}") as resp:
            buffer = await resp.read()
        await ctx.send(
            file=discord.File(BytesIO(buffer), filename=f"{code}.png"))

    @commands.command()
    async def robtea(self, ctx):
        embed = discord.Embed(
            description="Click it in 10 seconds to get your tea in perfect tempature",
            color=0x00ff6a)
        message = await ctx.send(embed=embed)
        await message.add_reaction("\U0001f375")
        start = time.time()

        def check(payload):
            return payload.message_id == message.id and payload.emoji.name == "\U0001f375" and payload.user_id == ctx.author.id

        payload = await self.bot.wait_for("raw_reaction_add", check=check)
        end = time.time()
        embed = discord.Embed(
            description=f"You robbed the tea in {round(end-start, 3)} seconds",
            color=0x00ff6a)
        await message.edit(embed=embed)

    @commands.command(aliases=["balls"])
    async def ball(self, ctx, *, question):
        await ctx.send(self.bot.ball.response(question))

    # @commands.command()
    async def spamclick(self, ctx):
        counter = 0
        embed = discord.Embed(
            color=0x00ff6a,
            description="Rules:\nafter the countdown end you will spam click the reaction as fast as you can"
        )
        message = await ctx.send(embed=embed)
        await asyncio.sleep(5)
        embed = discord.Embed(color=0x00ff6a, description="3")
        await message.edit(embed=embed)
        await asyncio.sleep(1)
        embed = discord.Embed(color=0x00ff6a, description="2")
        await message.edit(embed=embed)
        await asyncio.sleep(1)
        embed = discord.Embed(color=0x00ff6a, description="1")
        await message.edit(embed=embed)
        await asyncio.sleep(1)
        embed = discord.Embed(color=0x00ff6a, description="NOW")
        await message.edit(embed=embed)
        await message.add_reaction("<:stab:744345955637395586>")

        def check(payload):
            return payload.emoji.id == 744345955637395586 and payload.message_id == message.id

        async with async_timeout.timeout(10):
            while True:
                tasks = [
                    asyncio.ensure_future(
                        self.bot.wait_for('raw_reaction_add', check=check)),
                    asyncio.ensure_future(
                        self.bot.wait_for('raw_reaction_remove', check=check))
                ]
                done, pending = await asyncio.wait(
                    tasks, return_when=asyncio.FIRST_COMPLETED)
                counter += 1
                for task in pending:
                    task.cancel()
        await ctx.send(f"You clicked {counter} times")

    @commands.command()
    @commands.max_concurrency(1, commands.BucketType.user)
    async def latest(self, ctx, user: discord.Member = None):
        async with ctx.typing():
            user1 = user
            if user1 is None:
                user1 = ctx.author
            async for message in ctx.channel.history(limit=10000):
                if message.author.id == user1.id:
                    msg = message
                    break
            embed = discord.Embed(color=0x00ff6a, timestamp=msg.created_at)
            embed.set_author(name=msg.author,
                             icon_url=str(msg.author.avatar_url))
            embed.set_footer(text=f"id: {msg.id} Created at: ")
            if msg.embeds != []:
                content = "Embed"
            elif msg.attachments != []:
                content = "Attachment"
            else:
                content = msg.content
            embed.add_field(name="Content", value=content, inline=False)
            embed.add_field(name="Jump link",
                            value=f"[url]({msg.jump_url})",
                            inline=False)
            await ctx.send(embed=embed)
            if msg.attachments != []:
                await ctx.send(msg.attachments[0].url)
            if msg.embeds != []:
                await ctx.send(embed=msg.embeds[0])

    @commands.command(aliases=["rm"])
    @commands.max_concurrency(1, commands.BucketType.user)
    async def randommessage(self, ctx, limit=300):
        limit = min(limit, 10000)
        if limit <= 0:
            limit = 300
        async with ctx.typing():
            async for message in ctx.channel.history(limit=limit):
                # if user:
                #   lists = []
                #   counter = 0
                #   if message.author.id == user.id:
                #     lists.append(message)
                #     counter += 1
                #   if counter == 10:
                #     msg = random.choice(lists)
                #     break
                # else:
                if random.randint(0, 100) == 1:
                    msg = message
                    break
            # if user != None:
            #   lists = []
            #   for i in msg:
            #     if i.author.id == user.id:
            #       lists.append(i)
            # else:
            #   lists = msg
            # if lists == []:
            #   return await ctx.send(f"Can not find message that is send by {user}")
            # msg = random.choice(lists)
            embed = discord.Embed(color=0x00ff6a, timestamp=msg.created_at)
            embed.set_author(name=msg.author,
                             icon_url=str(msg.author.avatar_url))
            embed.set_footer(text=f"id: {msg.id} Created at: ")
            if msg.embeds != []:
                content = "Embed"
            elif msg.attachments != []:
                content = "Attachment"
            else:
                content = msg.content
            embed.add_field(name="Content", value=content, inline=False)
            embed.add_field(name="Jump link",
                            value=f"[url]({msg.jump_url})",
                            inline=False)
            await ctx.send(embed=embed)
            if msg.attachments != []:
                await ctx.send(msg.attachments[0].url)
            if msg.embeds != []:
                await ctx.send(embed=msg.embeds[0])

    @commands.command()
    async def reddit(self, ctx, *, text):
        await ctx.trigger_typing()
        link, title, nsfw, image = await self.reddit_(text)
        if nsfw == True:
            return
        embed = discord.Embed(color=0x00ff6a)
        embed.set_author(name=title, url=link)
        embed.set_image(url=image)
        embed.set_footer(
            text=f"requested by {ctx.author} response time : {round(self.bot.latency * 1000)} ms",
            icon_url=ctx.author.avatar_url)
        await ctx.reply(embed=embed)

    @commands.command()
    async def bottomdecode(self, ctx, *, text):
        bottoms = await self.bot.loop.run_in_executor(None, self.bottoms,
                                                      "from_bottom", text)
        if len(bottoms) > 500:
            return await ctx.send(str(await self.bot.mystbin.post(bottoms)))
        await ctx.send(bottoms)

    @commands.command()
    async def bottomencode(self, ctx, *, text):
        bottoms = await self.bot.loop.run_in_executor(None, self.bottoms,
                                                      "to_bottom", text)
        if len(bottoms) > 500:
            return await ctx.send(str(await self.bot.mystbin.post(bottoms)))
        await ctx.send(bottoms)

    @staticmethod
    def render_emoji(text):
        return text.replace("0", "\U00002b1b").replace(
            "1", "\U00002b1c").replace("2", "\U0001f7e6").replace(
                "3", "\U0001f7eb").replace("4", "\U0001f7e9").replace(
                    "5", "\U0001f7e7").replace("6", "\U0001f7ea").replace(
                        "7",
                        "\U0001f7e5").replace("8",
                                              "\U0001f7e8").replace("9", "")

    @commands.command(aliases=["grid", "toemoji"])
    async def renderemoji(self, ctx, *, codes: int):
        codes_ = await self.bot.loop.run_in_executor(None, self.render_emoji,
                                                     str(codes))
        await ctx.reply(codes_)

    @commands.command()
    async def urban(self, ctx, *, search: str):
        if ctx.channel.nsfw == False:
            lists = [
                "dick", "pussy", "horny", "porn", "cum", "cunt", "cock",
                "penis", "hole", "fuck", "shit", "bitch"
            ]
            if any(i in search for i in lists):
                return await ctx.send(
                    "Can not search nsfw words in non nsfw channel")
        async with self.bot.session.get(
                f"http://api.urbandictionary.com/v0/define?term={search}"
        ) as resp:
            if resp.status != 200:
                return await ctx.send(
                    f'An error occurred: {resp.status} {resp.reason}')
            js = await resp.json()
            data = js.get('list', [])
            if not data:
                return await ctx.send('No results found, sorry.')

        pages = AnimePages(UrbanDictionaryPageSource(data))
        try:
            await pages.start(ctx)
        except menus.MenuError as e:
            await ctx.send(e)

    @commands.command(aliases=["chat"])
    @commands.max_concurrency(1,
                              commands.cooldowns.BucketType.channel,
                              wait=False)
    async def talk(self, ctx):
        """
    Chat with the bot you might stop by saying `end`
    """
        # for i in self.talk_channels:
        #   if i == ctx.message.channel.id:
        #     embed = discord.Embed(color=0x00ff6a, description="A chat session has already been established in this channel")
        #     return await ctx.reply(embed=embed)
        self.talk_channels.append(ctx.message.channel.id)
        embed = discord.Embed(
            color=0x00ff6a, description="A chat session has been established")
        await ctx.reply(embed=embed)

        def check(m):
            return m.author == ctx.author and (3 <= len(m.content) <= 60)

        talking = True
        while talking:
            chats = ["Hii", "helooo"]
            try:
                message = await self.bot.wait_for("message",
                                                  timeout=60,
                                                  check=check)
                chats.append(message.content)
                if message.content == "end":
                    self.talk_channels.remove(ctx.message.channel.id)
                    embed = discord.Embed(color=0x00ff6a, description="Ended")
                    await ctx.reply(embed=embed)
                    talking = False
                    return False
                payload = {
                    "text": message.content,
                    "context": [chats[-2], chats[-1]]
                }
                async with ctx.channel.typing(), self.bot.session.post(
                        "https://public-api.travitia.xyz/talk",
                        json=payload,
                        headers={"authorization": talk_token}) as res:
                    await message.reply((await res.json())["response"])
            except asyncio.TimeoutError:
                self.talk_channels.remove(ctx.message.channel.id)
                embed = discord.Embed(color=0x00ff6a, description="Ended")
                await message.reply(embed=embed)
                talking = False
                return False

    @talk.error
    async def talk_error(self, ctx, error):
        if isinstance(error, commands.errors.MaxConcurrencyReached):
            embed = discord.Embed(
                color=0x00ff6a,
                description="A chat session has already been established in this channel")
            return await ctx.reply(embed=embed)

    @commands.command()
    async def sob(self, ctx, level: int = 1):
        if level > 70:
            embed = discord.Embed(
                color=0x00ff6a,
                description=f"The level must be 70 or lower then 70")
            return await ctx.send(embed=embed)
        emojis2 = ["<:rooSob:744345453923139714>" for _ in range(level)]
        emojis = " ".join(emojis2)
        embed = discord.Embed(color=0x00ff6a, description=f"{emojis}")
        await ctx.send(embed=embed)

    # @commands.command(aliases=["tr", "typerace"])
    async def typeracer(self, ctx):
        quote = await self.get_quote()
        font = ImageFont.truetype("lexiereadable-bold.ttf", 16)
        img = Image.new("RGB", (400, 100), color="black")
        draw = ImageDraw.Draw(img)
        draw.text((0, 0), '\n'.join(textwrap.wrap(quote, 46)), font=font)
        buffer = BytesIO()
        img.save(buffer, "png")
        file_ = discord.File(buffer, filename="quote.png")
        message = await ctx.reply(file=file_)

        def check(m):
            return m.channel == ctx.message.channel and m.content == quote

        start = time.perf_counter()
        msg = await self.bot.wait_for("message", check=check)
        end = time.perf_counter()
        final_ = end - start
        final_ = round(final_)
        embed = await embedbase.embed(self, ctx)
        embed.set_author(name=f"{msg.author} got it in {final_} seconds")
        embed2 = await embedbase.embed(self, ctx)
        embed2.set_author(name=f"{msg.author} got it in {final_} seconds")
        embed2.set_image(url="attachment://quote.png")
        await message.edit(embed=embed2)
        await ctx.send(embed=embed)

    @commands.command()
    async def tenor(self, ctx, *, search):
        gif = await self.tenor_(search)
        embed = await embedbase.embed(self, ctx)
        embed.set_image(url=gif)
        await ctx.send(embed=embed)

    @commands.command(aliases=["sw", "speedwatch"])
    async def speedwatcher(self, ctx, member: discord.Member = None):
        member1 = member
        if member1 is None:
            member1 = ctx.author
        variable = random.randint(1, 2)
        variable2 = random.randint(0, 10)
        random.seed(member1.id)
        speed_ = random.random()
        speed = round(speed_ * 100)
        speed = speed + variable2 if variable == 1 else speed - variable2
        if speed < 0:
            bar_ = "\u2800"
        elif speed <= 10:
            bar_ = "<:angery:747680299311300639>"
        elif speed <= 20:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 30:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 40:
            bar_ = "<:angery:747680299311300639> <:angery:747680299311300639> <:angery:747680299311300639> <:angery:747680299311300639>"
        elif speed <= 50:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 60:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 70:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 80:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed <= 90:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"
        elif speed >= 100:
            bar_ = "<:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639><:angery:747680299311300639>"

        embed = await embedbase.embed(self, ctx)
        embed.add_field(name=f"{member1} is",
                        value=f"`{speed}%` anime speedwatcher\n{bar_}")
        await ctx.send(embed=embed)

    @commands.command()
    async def hug(self, ctx, member: discord.Member = None):
        gif = await self.hug_()
        member1 = member
        if member1 is None:
            member1 = "themself"
        embed = await embedbase.embed(self, ctx)
        embed.set_author(name=f"{ctx.author} just hugged {member1}")
        embed.set_image(url=gif)
        await ctx.send(embed=embed)

    @staticmethod
    @asyncexe()
    def tts_(text):
        t = gtts.gTTS(text=text)
        buffer = BytesIO()
        t.write_to_fp(buffer)
        buffer.seek(0)
        return discord.File(buffer, filename="audio.mp3")

    @commands.command()
    async def tts(self, ctx, *, text="enter something "):
        async with ctx.typing():
            file = await self.tts_(text)
            await ctx.send(file=file)

    @commands.command()
    async def sushi(self, ctx):
        embed = await embedbase.embed(self, ctx)
        embed.add_field(name="Get the sushi", value="3")
        message = await ctx.send(embed=embed)
        await asyncio.sleep(1)
        embed = await embedbase.embed(self, ctx)
        embed.add_field(name="Get the sushi", value="2")
        await message.edit(embed=embed)
        await asyncio.sleep(1)
        embed = await embedbase.embed(self, ctx)
        embed.add_field(name="Get the sushi", value="1")
        await message.edit(embed=embed)
        await asyncio.sleep(1)
        embed = await embedbase.embed(self, ctx)
        embed.add_field(name="Get the sushi", value="**NOW**")
        await message.edit(embed=embed)
        await message.add_reaction("\U0001f363")
        start = time.perf_counter()

        def check(reaction, user):
            return reaction.message.id == message.id and user != self.bot.user and str(
                reaction.emoji) == "\U0001f363"

        reaction, user = await self.bot.wait_for('reaction_add', check=check)
        end = time.perf_counter()
        users = await reaction.users().flatten()
        for i in users:
            if i.bot == True:
                users.remove(i)
        lists = []
        for i in users:
            lists.append(str(i.name))
        # await functions.in_lb(user)
        # score = await functions.get_lb(user)
        final = end - start
        # final = int(final)
        # if final == None or final == "null":
        #   await functions.update_lb(user, final)
        #   embed = await embedbase.embed(self, ctx)
        #   embed.add_field(name="Get the sushi", value=f"**{user} got it in {round(final * 1000)} ms new person record**")
        #   await message.edit(embed=embed)
        #   return
        # if final < score:
        #   await functions.update_lb(user, final)
        #   embed = await embedbase.embed(self, ctx)
        #   embed.add_field(name="Get the sushi", value=f"**{user} got it in {round(final * 1000)} ms new person record**")
        #   await message.edit(embed=embed)
        #   return

        embed = await embedbase.embed(self, ctx)
        embed.add_field(
            name="Get the sushi",
            value=f"**{user.mention} got it in {round(final * 1000)} ms **",
            inline=False)
        embed.add_field(name="participant",
                        value="\n".join(lists),
                        inline=False)
        await message.edit(embed=embed)

        def check(payload):
            return payload.message_id == message.id

        while True:
            payload = await self.bot.wait_for("raw_reaction_add", check=check)
            msg = await self.bot.get_message(payload.message_id)
            if not msg:
                break
            reactions = msg.reactions[0]
            users = await reactions.users().flatten()
            print(users)
            for i in users:
                if i.bot == True:
                    users.remove(i)
            lists = []
            for i in users:
                lists.append(str(i.name))
            embed = await embedbase.embed(self, ctx)
            embed.add_field(
                name="Get the sushi",
                value=f"**{user.mention} got it in {round(final * 1000)} ms **",
                inline=False)
            embed.add_field(name="participant",
                            value="\n".join(lists),
                            inline=False)
            await message.edit(embed=embed)

    @commands.command()
    async def meme(self, ctx):
        await ctx.trigger_typing()
        link, title, nsfw, image = await self.getmeme()
        if nsfw == True:
            return
        embed = discord.Embed(color=0x00ff6a)
        embed.set_author(name=title, url=link)
        embed.set_image(url=image)
        embed.set_footer(
            text=f"requested by {ctx.author} response time : {round(self.bot.latency * 1000)} ms",
            icon_url=ctx.author.avatar_url)
        await ctx.reply(embed=embed)

    @commands.command()
    async def decode(self, ctx, *, text):
        await ctx.trigger_typing()
        text1 = text
        key = os.getenv("key")
        f = Fernet(key)
        try:
            if text1.startswith("https://mystb.in/"):
                text1 = str(await self.bot.mystbin.get(text))
            new = bytes(text1, "utf-8")
            decrypted = f.decrypt(new)
            decrypted = str(decrypted, 'utf-8')
            await ctx.reply(decrypted)
        except:
            await ctx.send("You provided a invalid link")

    @commands.command()
    async def encode(self, ctx, *, text: str):
        await ctx.trigger_typing()
        key = os.getenv("key")
        f = Fernet(key)
        newtext = bytes(text, "utf-8")
        new_token = f.encrypt(newtext)
        new_token = str(new_token, 'utf-8')
        if len(new_token) > 0:
            paste = await self.bot.mystbin.post(new_token)
            new_token = str(paste)
        await ctx.reply(new_token)

    @commands.command()
    async def ovoly(self, ctx, *, text):
        ovo = text.replace("l",
                           "v").replace("L",
                                        "v").replace("r",
                                                     "v").replace("R", "v")
        await ctx.reply(f"{ovo} ovo")

    @commands.command()
    async def roast(self, ctx, member: discord.Member = None):
        if member is None:
            member = ctx.author
        if member == self.bot.user or member.id == 590323594744168494:
            return await ctx.send("nope")
        await ctx.trigger_typing()
        async with self.bot.session.get(
                "https://evilinsult.com/generate_insult.php") as resp:
            response = await resp.text()
        async with self.bot.session.get(
                "https://insult.mattbas.org/api/insult") as resp:
            response3 = await resp.text()
        response2 = await self.bot.dag.roast()
        choice = random.randint(1, 3)
        if choice == 1:
            response = response
        elif choice == 2:
            response == response2
        else:
            response == response3
        text = f"{member.mention}, {response}"
        await ctx.send(text)

def setup(bot):
    bot.add_cog(fun(bot))


#!/usr/bin/env python3
import argparse
import dataclasses
import sys
import os
from pathlib import Path
from typing import Dict, List, Tuple, Type

import trunner
from trunner import resolve_project_path
from trunner.extensions import ExtensionError, load_extensions
from trunner.host import EmulatorHost, Host, RpiHost
from trunner import TestRunner
from trunner.dut import PortError
from trunner.target import (
    IMXRT106xEvkTarget,
    IMXRT117xEvkTarget,
    HostPCGenericTarget,
    IA32GenericQemuTarget,
    RISCV64GenericQemuTarget,
    ARMv7A9Zynq7000QemuTarget,
    STM32L4x6Target,
    Zynq7000ZedboardTarget,
    IMX6ULLEvkTarget,
)
from trunner.ctx import TestContext
from trunner.target.base import TargetBase
from trunner.types import is_github_actions

def args_file(arg):
    path = Path(arg).resolve()
    return path

def is_raspberry_pi() -> bool:
    if os.name != "posix":
        return False

    try:
        with open("/sys/firmware/devicetree/base/model", "r") as f:
            model = f.read().lower()
            return "raspberry pi" in model
    except Exception:
        pass

    return False

def parse_args(targets: Dict[str, Type[TargetBase]], hosts: Dict[str, Type[Host]]):
    """Parses and returns program arguments.

    Arguments:
        targets: Dictionary of available targets.
        hosts: Dictionary of available hosts.

    """

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-T",
        "--target",
        default="ia32-generic-qemu",
        choices=targets.keys(),
        help=(
            "Set target on which tests will be run. "
            "By default runs tests on %(default)s target. "
            "Targets can be extended using extension feature."
        ),
    )

    parser.add_argument(
        "-H",
        "--host",
        default="rpi" if is_raspberry_pi() else "pc",
        choices=hosts.keys(),
        help=(
            'Set host that run tests. "pc" host is recommended for running tests on emulators. '
            'To control physical boards you can use "rpi" host or pc '
            "(but it requires restarting board manually by yourself). By default runs tests on %(default)s. "
            "Hosts can be extended using extension feature."
        ),
    )

    parser.add_argument(
        "-t",
        "--test",
        default=[],
        action="append",
        type=args_file,
        help=(
            "Specify directory in which test will be searched. "
            "If flag is not used then runner searches for tests in "
            "phoenix-rtos-project directory. Flag can be used multiple times."
        ),
    )

    parser.add_argument(
        "-S",
        "--stream",
        default=True if is_github_actions() else False,
        action="store_true",
        help="Stream the DUT output during the test execution. Defaults to %(default)s",
    )

    parser.add_argument(
        "-O",
        "--output",
        action="store",
        const="report.xml",
        nargs='?',
        help=("Write machine-readable test results as csv and xml file. "
              "When no value is provided uses %(const)s"),
    )

    parser.add_argument(
        "-p",
        "--port",
        help="Specify serial to communicate with device board. Default value depends on the target",
    )

    parser.add_argument(
        "-b",
        "--baudrate",
        default=115200,
        help="Specify the connection speed of serial. By default uses %(default)d",
    )

    parser.add_argument(
        "--no-flash",
        default=False,
        action="store_true",
        help="Board will not be flashed by runner.",
    )

    parser.add_argument(
        "--no-test",
        default=False,
        action="store_true",
        help=(
            "Tests will be not run by runner. This option may be helpful to only flash the device "
            "or check if yamls are parsed correctly."
        ),
    )

    parser.add_argument(
        "-v",
        "--verbose",
        action="count",
        default=0,
        help="Increate result verbosity level (0={FAIL}, 1={FAIL, SKIP}, 2={FAIL, SKIP, OK})",
    )

    parser.add_argument(
        "--nightly",
        default=False,
        action="store_true",
        help="Nightly tests will be run",
    )

    def is_dir(dirpath):
        """Check whether the provided path is a directory (if exists)"""
        if os.path.exists(dirpath) and not os.path.isdir(dirpath):
            raise argparse.ArgumentTypeError(f"{dirpath} is not a directory!")
        return dirpath

    parser.add_argument(
        "--logdir",
        default=None,
        const="./phoenix_test_campaign_logs",
        help="Directory path where log files from the test campaign will be stored. "
        "By default log files will not be created. "
        "When only --logdir without a value is set, uses %(const)s",
        nargs="?",
        type=is_dir,
    )

    class keyValue(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            kwargs = getattr(namespace, self.dest)
            if kwargs is None:
                kwargs = dict()

            if values is None:
                parser.error()

            for item in values:
                try:
                    key, val = item.split("=", 1)
                except ValueError:
                    parser.error(f"expected key=value format, got: {item}")

                kwargs[key] = val

            setattr(namespace, self.dest, kwargs)

    parser.add_argument(
        "--kwargs",
        nargs="+",
        default=dict(),
        action=keyValue,
        help=(
            "Pass extra arguments in key=value format to use them in extensions or in harnesses. Caution: do not use"
            " '=' character in the `key` string! Runner just splits the word on the first occurrence of `=` character."
        ),
    )

    args = parser.parse_args()

    if not args.test:
        args.test = [resolve_project_path()]

    if args.output and "." in args.output:
        # remove extension for output stem if possibly exists
        args.output = args.output.rsplit(".", 1)[0]

    return args

def resolve_targets_and_hosts() -> Tuple[Dict[str, Type[TargetBase]], Dict[str, Type[Host]]]:
    """
    Returns a tuple of dictionaries that map host and target names to an equivalent class.

    Load external targets and hosts defined by user in extensions and combine them
    with internal runnner targets.
    """

    targets: List[Type[TargetBase]] = [
        HostPCGenericTarget,
        IA32GenericQemuTarget,
        RISCV64GenericQemuTarget,
        ARMv7A9Zynq7000QemuTarget,
        STM32L4x6Target,
        IMXRT106xEvkTarget,
        IMXRT117xEvkTarget,
        Zynq7000ZedboardTarget,
        IMX6ULLEvkTarget,
    ]

    hosts: List[Type[Host]] = [EmulatorHost, RpiHost]

    try:
        ext_targets, ext_hosts = load_extensions()
    except ExtensionError as e:
        print(e)
        sys.exit(4)

    targets.extend(ext_targets)
    hosts.extend(ext_hosts)

    # NOTE default targets/hosts can be overwritten if extensions have the same name!
    targets_dict = {t.name: t for t in targets}
    hosts_dict = {h.name: h for h in hosts}

    return targets_dict, hosts_dict

def main():
    targets, hosts = resolve_targets_and_hosts()

    args = parse_args(targets, hosts)

    ctx = TestContext(
        port=args.port,
        baudrate=args.baudrate,
        project_path=resolve_project_path(),
        nightly=args.nightly,
        logdir=args.logdir,
        should_flash=not args.no_flash,
        should_test=not args.no_test,
        verbosity=args.verbose,
        stream_output=args.stream,
        output=args.output,
        kwargs=args.kwargs,
    )

    host_cls = hosts[args.host]
    host = host_cls.from_context(ctx)
    ctx = dataclasses.replace(ctx, host=host)

    target_cls = targets[args.target]
    try:
        target = target_cls.from_context(ctx)
    except PortError as e:
        # TODO Make port finding in the global scope
        print(e)
        return 2

    ctx = dataclasses.replace(ctx, target=target)
    ctx = host.add_to_context(ctx)

    # Set global context
    trunner.ctx = ctx

    runner = TestRunner(
        ctx=ctx,
        test_paths=args.test,
    )

    ok = runner.run()
    if not ok:
        return 1

    return 0

if __name__ == "__main__":
    sys.exit(main())


import imp
from multiprocessing import context
from django.shortcuts import render
import requests

# Create your views here.

def home(request):

    city = request.GET.get('city', "Lucknow")
    url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=22093d6a3f26e74036ac481b4eed0935'
    data = requests.get(url).json()
    #print(data)

    payload = {
    'city' : data['name'],
    'weather': data['weather'][0]['main'],
    'icon' : data['weather'][0]['icon'],
    'kelvin_temprature' : data['main']['temp'],
    'celcius_temprature' : int(data['main']['temp']-273),
    'pressure' : data['main']['pressure'],
    'humidity' : data['main']['humidity'],
    'description' : data['weather'][0]['description']
    }

    context = {'data' : payload}
    print(data)

    return render(request,'home.html',context)


import matplotlib.pyplot as plt
from casadi import cos, sin, pi, sqrt, linspace
import matplotlib
from pandas import read_csv
import numpy as np

def latexify(fig_width=None, fig_height=None):
    """Set up matplotlib's RC params for LaTeX plotting.
    Call this before plotting a figure.

    Parameters
    ----------
    fig_width : float, optional, inches
    fig_height : float,  optional, inches
    columns : {1, 2}
    """

    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples

    # Width and max height in inches for IEEE journals taken from
    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf

    if fig_width is None:
        fig_width = 5  # width in inches

    if fig_height is None:
        golden_mean = (sqrt(5)-1.0)/2.0    # Aesthetic ratio
        fig_height = fig_width*golden_mean # height in inches

    params = {'backend': 'ps',
              'text.latex.preamble': r"\usepackage{gensymb} \usepackage{amsmath}",
              'axes.labelsize': 10, # fontsize for x and y labels (was 10)
              'axes.titlesize': 10,
              'legend.fontsize': 10, # was 10
              'xtick.labelsize': 10,
              'ytick.labelsize': 10,
              'text.usetex': True,
              'figure.figsize': [fig_width, fig_height],
              'font.family': 'serif'
    }

    matplotlib.rcParams.update(params)

def visualize_trajectory(x, y, phi, L, obstacles=None, save_fig=False, fig_name=None):
    latexify(fig_width=3, fig_height=3)
    marker_size = 5
    fig, ax = plt.subplots()
    ax.scatter(9, 9, marker='x')
    for (xk, yk, phik) in zip(x, y, phi):
        r_propeller_x = xk + L*cos(phik)
        r_propeller_y = yk + L*sin(phik)

        l_propeller_x = xk - L*cos(phik)
        l_propeller_y = yk - L*sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    if obstacles != None:
        for o in obstacles:
            px_obst_k = o[0][0]
            py_obst_k = o[0][1]
            r_obst_k = o[1]
            theta = linspace(0, 2*pi, 100)
            xobst1 = px_obst_k + r_obst_k*cos(theta)
            xobst2 = py_obst_k + r_obst_k*sin(theta)
            plt.plot(xobst1, xobst2, 'r')

    ax.set_xlim([0, 10])
    ax.set_ylim([0, 10])
    ax.set_xlabel('X (m)')
    ax.set_ylabel('Y (m)')
    ax.set_aspect(1)
    plt.show()

    if save_fig:
        fig.savefig(fig_name + '.svg', format='svg', dpi=1200)

def plot_controls(tgrid, u, save_fig=False, fig_name=None):
    latexify(fig_width=2, fig_height=1.5)
    fig, ax = plt.subplots()
    ax.step(tgrid[0:-1], u[0,:], where='post', label=r'$F_1$')
    ax.step(tgrid[0:-1], u[1,:], where='post', label=r'$F_2$')
    ax.set_xlabel(r'$k$ (iteration)')
    ax.set_ylabel(r'$F$ (N)')
    ax.legend()
    ax.grid()
    plt.show()

    if save_fig:
        fig.savefig(fig_name + '.svg', format='svg', dpi=1200)

def plot_pose(tgrid, pose, save_fig=False):
    latexify()
    fig, ax = plt.subplots()
    ax.plot(tgrid, pose[0,:], label=r'$x$')
    ax.plot(tgrid, pose[1,:], label=r'$y$')
    ax.plot(tgrid, pose[2,:], label=r'$\phi$')
    ax.set_xlabel(r'$t$ (sec)')
    ax.set_ylabel(r'$u$ (N)')
    ax.legend()
    ax.grid()
    plt.show()

    if save_fig:
        fig.savefig('drone_pose.svg', format='svg', dpi=1200)

def plot_RL_statistics(save_fig=False):
    latexify(fig_width=11, fig_height=3)

    # load trainig statistics
    sac_reward = read_csv('report/SAC7_reward.csv')
    td3_reward = read_csv('report/TD37_reward.csv')

    sac_actor_loss = read_csv('report/SAC7_actor_loss.csv')
    td3_actor_loss = read_csv('report/TD37_actor_loss.csv')

    sac_critic_loss = read_csv('report/SAC7_critic_loss.csv')
    td3_critic_loss = read_csv('report/TD37_critic_loss.csv')

    fig, ax = plt.subplots(1,3)
    ax[0].plot(1e-5*sac_reward.values[:,1], 1e-3*sac_reward.values[:,2], label='SAC')
    ax[0].plot(1e-5*td3_reward.values[:,1], 1e-3*td3_reward.values[:,2], label='TD3')
    ax[0].set_xlabel(r'time steps $\times\ 10^5$')
    ax[0].set_ylabel(r'episode return $\times\ 10^3$')
    ax[0].set_ylim(-14, -4)
    ax[0].legend()

    ax[1].plot(1e-5*sac_actor_loss.values[:,1], 1e-3*sac_actor_loss.values[:,2], label='SAC')
    ax[1].plot(1e-5*td3_actor_loss.values[:,1], 1e-3*td3_actor_loss.values[:,2], label='TD3')
    ax[1].set_xlabel(r'time steps $\times\ 10^5$')
    ax[1].set_ylabel(r'actor loss $\times\ 10^3$')
    ax[1].set_ylim(0, 8)
    ax[1].legend()

    ax[2].plot(1e-5*sac_critic_loss.values[:,1], 1e-4*sac_critic_loss.values[:,2], label='SAC')
    ax[2].plot(1e-5*td3_critic_loss.values[:,1], 1e-4*td3_critic_loss.values[:,2], label='TD3')
    ax[2].set_xlabel(r'time steps $\times\ 10^5$')
    ax[2].set_ylabel(r'critic loss $\times\ 10^4$')
    ax[2].set_ylim(-1, 25)
    ax[2].legend()

    plt.show()

    if save_fig:
        fig.savefig('report/RL_statistics.svg', format='svg', dpi=1200)

def plot_controls_RL(t_grid_td3, u_traj_td31, t_grid_sac, u_traj_sac1, save_fig=False):
    latexify(fig_width=2, fig_height=1.5)
    fig, ax = plt.subplots()
    ax.step(t_grid_td3[0:-1], u_traj_td31[:,0], where='post', label=r'$F_1$ TD3')
    ax.step(t_grid_td3[0:-1], u_traj_td31[:,1], where='post', label=r'$F_2$ TD3')
    ax.step(t_grid_sac[0:-1], u_traj_sac1[:,0], '--', where='post', label=r'$F_1$ SAC')
    ax.step(t_grid_sac[0:-1], u_traj_sac1[:,1], '--', where='post', label=r'$F_2$ SAC')
    ax.set_xlabel(r'$k$ (iteration)')
    ax.set_ylabel(r'$F$ (N)')
    ax.legend(loc='upper right')
    ax.grid()
    plt.show()
    if save_fig:
            fig.savefig('report/controls_RL.svg', format='svg', dpi=1200)

def visualize_trajectory_RL(x_traj_td31, x_traj_td32, x_traj_sac1, x_traj_sac2, L, save_fig=False):
    latexify(fig_width=3, fig_height=3)
    marker_size = 5
    fig, ax = plt.subplots()
    ax.scatter(9, 9, marker='x')
    for (xk, yk, phik) in zip(x_traj_td31[::15,0], x_traj_td31[::15,1], x_traj_td31[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    for (xk, yk, phik) in zip(x_traj_td32[::15,0], x_traj_td32[::15,1], x_traj_td32[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    for (xk, yk, phik) in zip(x_traj_sac1[::15,0], x_traj_sac1[::15,1], x_traj_sac1[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'r')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'r')

    for (xk, yk, phik) in zip(x_traj_sac2[::15,0], x_traj_sac2[::15,1], x_traj_sac2[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'r')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'r')

    ax.set_xlim([0, 10])
    ax.set_ylim([0, 10])
    ax.set_xlabel('X (m)')
    ax.set_ylabel('Y (m)')
    ax.set_aspect(1)
    plt.show()

    if save_fig:
            fig.savefig('report/trajectory_RL.svg', format='svg', dpi=1200)


import numpy as np
from imutils.video import FPS
import argparse, imutils
import time, dlib, cv2, datetime
from itertools import zip_longest
from functions.mailer import Mailer
from functions import config
import time, schedule, csv
import smtplib, ssl
from scipy.spatial import distance as dist
from collections import OrderedDict

timer0 = time.time()

class trackable_object:
	def __init__(self, objectID, centroid):
		# Defining the new centriods from the old and storing the ID
		self.objectID = objectID
		self.centroids = [centroid]
		# Checking if the object is counted or not
		self.counted = False

class CentroidTracker:
	def __init__(self, vanish=50, max_distance=50):

		self.nextObjectID = 0
		self.objects = OrderedDict()
		self.disappeared = OrderedDict()
		self.vanish = vanish
		self.max_distance = max_distance

	def register(self, centroid):

		self.objects[self.nextObjectID] = centroid
		self.disappeared[self.nextObjectID] = 0
		self.nextObjectID += 1

	def deregister(self, objectID):

		del self.objects[objectID]
		del self.disappeared[objectID]

	def update(self, rects):

		if len(rects) == 0:

			for objectID in list(self.disappeared.keys()):
				self.disappeared[objectID] += 1
				if self.disappeared[objectID] > self.vanish:
					self.deregister(objectID)
			return self.objects

		inputCentroids = np.zeros((len(rects), 2), dtype="int")

		for (i, (startX, startY, endX, endY)) in enumerate(rects):

			cX = int((startX + endX) / 2.0)
			cY = int((startY + endY) / 2.0)
			inputCentroids[i] = (cX, cY)
		if len(self.objects) == 0:
			for i in range(0, len(inputCentroids)):
				self.register(inputCentroids[i])
		else:

			objectIDs = list(self.objects.keys())
			objectCentroids = list(self.objects.values())
			D = dist.cdist(np.array(objectCentroids), inputCentroids)
			rows = D.min(axis=1).argsort()
			cols = D.argmin(axis=1)[rows]
			usedRows = set()
			usedCols = set()

			for (row, col) in zip(rows, cols):

				if row in usedRows or col in usedCols:
					continue

				if D[row, col] > self.max_distance:
					continue

				objectID = objectIDs[row]
				self.objects[objectID] = inputCentroids[col]
				self.disappeared[objectID] = 0

				usedRows.add(row)
				usedCols.add(col)

			unusedRows = set(range(0, D.shape[0])).difference(usedRows)
			unusedCols = set(range(0, D.shape[1])).difference(usedCols)
			if D.shape[0] >= D.shape[1]:

				for row in unusedRows:

					objectID = objectIDs[row]
					self.disappeared[objectID] += 1

					if self.disappeared[objectID] > self.vanish:
						self.deregister(objectID)
			else:
				for col in unusedCols:
					self.register(inputCentroids[col])

		return self.objects

class Mailer:

    def __init__(self):

        self.EMAIL = "saisandeep876@gmail.com"
        self.PASS = ""
        self.PORT = 465
        self.server = smtplib.SMTP_SSL('smtp.gmail.com', self.PORT)

    def send(self, mail):
        self.server = smtplib.SMTP_SSL('smtp.gmail.com', self.PORT)
        self.server.login(self.EMAIL, self.PASS)
        # message to be sent
        SUBJECT = 'More number of people inside'
        TEXT = f'Maximum limit exceeded in the building!'
        message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)

        # sending the mail
        self.server.sendmail(self.EMAIL, mail, message)
        self.server.quit()

def run():

	# arguments parser
	a_parser = argparse.ArgumentParser()
	a_parser.add_argument("-p", "--prototxt", required=False,
		help="Caffe 'deploy' prototxt file path")
	a_parser.add_argument("-m", "--model", required=True,
		help="pre-trained model's path")
	a_parser.add_argument("-i", "--input", type=str,
		help="input video file path")
	a_parser.add_argument("-o", "--output", type=str,
		help="output video file path")
	# setting the mark_confidence to  0.35
	a_parser.add_argument("-c", "--mark_confidence", type=float, default=0.35,
		help="Filtering poor detections with the lowest possible probability")
	a_parser.add_argument("-s", "--skip-frames", type=int, default=30,
		help="No of frames that are skipped")
	args = vars(a_parser.parse_args())

	# Classes that our Single Shot Detector is trained
	CLASSES = ["background", "cow", "bicycle", "tvmonitor", "horse", "sofa", "sheep", "car", "cat", "boat", "aeroplane", "diningtable", "dog", "chair", "motorbike", "person", "pottedplant", "bus",
		"bottle", "train", "bird"]

	# Load the model
	model = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

	# Playing the video
	print("Getting the video started")
	source = cv2.VideoCapture(args["input"])
	editor = None

	# we are setting the frame dimentions as of now
	W = None
	H = None

	# Defining the Centroid tracker and trackable objects
	ct = CentroidTracker(vanish=50, max_distance=55)
	trackerobjects_list = []
	objects_track = {}

	# Defining the frames and the position of objects i.e, up or down
	frames = 0
	down_frames = 0
	up_frames = 0
	x = []
	up_clear_frames=[]
	down_clear_frames=[]

	# defining and starting the FPS
	fps = FPS().start()

	while True:
		# reading all the frames in order
		frame = source.read()
		frame = frame[1] if args.get("input", False) else frame

		# breaking the video
		if args["input"] is not None and frame is None:
			break

		# Converting the BGR frames to RGB frames for deep learning librabries
		frame = imutils.resize(frame, width = 500)
		rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

		if W is None or H is None:
			(H, W) = frame.shape[:2]

		if args["output"] is not None and editor is None:
			o_video = cv2.VideoWriter_fourcc(*"mp4v")
			editor = cv2.VideoWriter(args["output"], o_video, 30, (W, H), True)

		# defining  the detector Status

		Detector = "Stand_by"
		detector_list = []

		# Defining the object detection method
		if frames % args["skip_frames"] == 0:

			# Defining the new status of the detector
			Detector = "Identifying"
			trackerobjects_list = []

			# Defining the mark from the frame
			mark = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)
			model.setInput(mark)
			detections = model.forward()

			# Finding the mark_confidence
			for i in np.arange(0, detections.shape[2]):

				mark_confidence = detections[0, 0, i, 2]

				# Removing the weak mark_confidence marks of the objects

				if mark_confidence > args["mark_confidence"]:

					idx = int(detections[0, 0, i, 1])

					if CLASSES[idx] != "person":
						continue

					# Finding the (x,y) coordinates for the Objects that is the people
					coordinates = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
					(Begin_X, Begin_Y, Finish_X, Finish_Y) = coordinates.astype("int")

					# Setting a rectangle box around the object and tracking it
					tracker = dlib.correlation_tracker()
					rectangle = dlib.rectangle(Begin_X, Begin_Y, Finish_X, Finish_Y)
					tracker.start_track(rgb, rectangle)

					# Appending the tracker to list
					trackerobjects_list.append(tracker)

		else:

			for tracker in trackerobjects_list:
				# Defining the new Detector of the tracker to Tracking
				Detector = "Tracking"

				# Updating the tracker
				tracker.update(rgb)
				tracker_position = tracker.get_position()

				Begin_X = int(tracker_position.left())
				Begin_Y = int(tracker_position.top())
				Finish_X = int(tracker_position.right())
				Finish_Y = int(tracker_position.bottom())

				# Appending the coordinates to the list
				detector_list.append((Begin_X, Begin_Y, Finish_X, Finish_Y))

		# Defining a line for a reference

		cv2.line(frame, (0, H // 2), (W, H // 2), (0, 0, 0), 3)
		cv2.putText(frame, " -- Reference Line -- ", (10, H - ((i * 20) + 200)),
			cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)

		# Using the Centroid Tracker to compute the centroid coordinates from the old objects
		objects = ct.update(detector_list)

		for (objectID, centroid) in objects.items():
			# checking that the object is in the list
			to = objects_track.get(objectID, None)

			# Creating new object tracker and appending it to the list
			if to is None:
				to = trackable_object(objectID, centroid)

			else:
				y = [c[1] for c in to.centroids]
				direction = centroid[1] - np.mean(y)
				to.centroids.append(centroid)

				# Counting Objects
				if not to.counted:
					# The value is negative, it means the object is moving up otherwise down
					if direction < 0 and centroid[1] < H // 2:
						up_frames += 1
						up_clear_frames.append(up_frames)
						to.counted = True

					elif direction > 0 and centroid[1] > H // 2:
						down_frames += 1
						down_clear_frames.append(down_frames)

						# If the count of people are grater than threshold then alert the owner
						if sum(x) >= config.Threshold:
							cv2.putText(frame, "-ALERT: limit exceeded-", (10, frame.shape[0] - 80),
								cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 2)
							if config.ALERT:
								print("Preparing to send the email alert.")
								Mailer().send(config.MAIL)
								print("The Alert had been sent")

						to.counted = True

					x = []
					# total people inside
					x.append(len(down_clear_frames)-len(up_clear_frames))

			# storing the trackable object
			objects_track[objectID] = to

			# Defining ID and a rectangle box
			text = "ID:{}".format(objectID)
			cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
			cv2.circle(frame, (centroid[0], centroid[1]), 4, (255, 255, 255), -1)

		# Printing the frames and the ID
		info = [
		("Out", up_frames),
		("In", down_frames),
		("Detector", Detector),
		]
        # Printing the count
		info2 = [
		("People count inside", x),
		]

        # Displaying the output
		for (i, (k, v)) in enumerate(info):
			text = "{}: {}".format(k, v)
			cv2.putText(frame, text, (10, H - ((i * 20) + 20)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)

		for (i, (k, v)) in enumerate(info2):
			text = "{}: {}".format(k, v)
			cv2.putText(frame, text, (265, H - ((i * 20) + 60)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)

		# Saving the output count in the excel sheet
		if config.Log:
			d_t = [datetime.datetime.now()]
			d = [d_t, down_clear_frames, up_clear_frames, x]
			export_data = zip_longest(*d, fillvalue = '')

			with open('Log.csv', 'w', newline='') as myfile:
				wr = csv.editor(myfile, quoting=csv.QUOTE_ALL)
				wr.editorow(("End Time", "In", "Out", "Total Inside"))
				wr.editorows(export_data)

		# Writing to the file, if not written
		if editor is not None:
			editor.write(frame)

		# Output frame
		cv2.imshow("Monitor/Analyze in Real-Time", frame)
		key = cv2.waitKey(1) & 0xFF

		# In case to break out press s
		if key == ord("s"):
			break

		# Update the FPS
		frames += 1
		fps.update()

		if config.Timer:
			# Intitialzing the video to stop analyzing after 30000s.
			timer = time.time()
			count_sec=(timer-timer0)
			if count_sec > 30000:
				break

	# Display FPS and Time
	fps.stop()
	print(" Duration: {:.2f}".format(fps.elapsed()))
	print(" FPS: {:.2f}".format(fps.fps()))

	# Intialize closing of all the opened windows
	source.release()
	cv2.destroyAllWindows()

if config.Scheduler:
	while 1:
		schedule.run_pending()

else:
	run()


import hashlib

import tweepy
from flask import jsonify, redirect, session, request

from main import api
from settings import SETTINGS

from database import tweet_db_session, user_db_session
from models.eroiine import Tweet
from models.user import User

from exception import cannotAuthTwitterException

@api.route('/')
def page_top():
    eroiine_dict = get_eroiines_from_db()
    return jsonify(eroiine_dict)

@api.route('/auth/twitter', methods=['GET'])
def page_auth_twitter():
    auth = get_auth_twitter()
    redirect_url = auth.get_authorization_url()
    session['request_token'] = auth.request_token
    return redirect(redirect_url)

@api.route('/auth/twitter/save_data', methods=['GET'])
def page_save_tokens():
    hashed_id = save_token_twitter()
    save_eroiines_to_db(hashed_id)
    return redirect('/')

def get_eroiines_from_db() -> dict:
    """get all-eroiines from database.
    Returns:
        dict: ero-iine with tweet-id as key.
    """
    response = {}
    for t in tweet_db_session.query(Tweet).all():
        response[t.tweet_id] = {
            'user_id': t.user_id,
            'text': t.tweet_text,
            'image_url1': t.image_url_1,
            'image_url2': t.image_url_2,
            'image_url3': t.image_url_3,
            'image_url4': t.image_url_4,
        }

    return response

def get_auth_twitter() -> tweepy.OAuthHandler:
    """auth twitter with saved tokens.
    Returns:
        tweepy.OAuthHandler:
    """
    return tweepy.OAuthHandler(SETTINGS['TWITTER_API_KEY'], SETTINGS['TWITTER_API_SECRET_KEY'])

def get_auth_twitter_consumer(hashed_twitter_id: str) -> tweepy.OAuthHandler:
    """auth twitter with saved tokens.
    Args:
        hashed_twitter_id(str):
    Returns:
        tweepy.OAuthHandler:
    """
    user = user_db_session.query(User.token, User.token_secret).filter(User.hashed_user_id == hashed_twitter_id).one()
    auth = get_auth_twitter()
    auth.set_access_token(user.token, user.token_secret)
    twitter_api = tweepy.API(auth)
    return twitter_api

def get_eroiines_from_twitter():
    pass

def save_eroiines_to_db(hashed_twitter_id: str):
    """save eroiines from user-twitter-favolites.
    """
    twitter_api = get_auth_twitter_consumer(hashed_twitter_id)
    exist_keys = [key[0] for key in tweet_db_session.query(Tweet.tweet_id).all()]

    fav_list = []
    for fav in twitter_api.favorites():
        t = fav._json
        if is_img_tweet(t):
            media = t['entities']['media']
            image_urls = [media[i]['media_url'] if len(media) > i else None for i in range(4)]
            if t['id'] not in exist_keys:
                tweet = Tweet(t['id'], t['user']['id'], t['text'], image_urls)
                fav_list.append(tweet)

    if len(fav_list) > 0:
        tweet_db_session.add_all(fav_list)
        tweet_db_session.commit()

def is_img_tweet(tweet: dict):
    """determine img tweet.
    Returns:
        bool:
    """
    try:
        media = tweet['entities']['media']
        if len(media) > 0:
            if media[0]['type'] == 'photo':
                return True
    except Exception:
        pass
    return False

def hash_twitter_id(twitter_id: int):
    """for cookie injection(wip)
    Returns:
        str: sha256-hex-hashed twitter_id
    """
    return hashlib.sha256(str(twitter_id).encode()).hexdigest()

def save_token_twitter():
    """save auth-tokens
    Returns:
        str: hashed twitter id
    """
    token = session.pop('request_token', None)
    verifier = request.args.get('oauth_verifier')
    if token is None or verifier is None:
        return False

    auth = get_auth_twitter()
    auth.request_token = token
    auth.get_access_token(verifier)

    consumer_key = auth.access_token
    consumer_key_secret = auth.access_token_secret

    try:
        auth = get_auth_twitter()
        auth.set_access_token(consumer_key, consumer_key_secret)
        twitter_api = tweepy.API(auth)

        user = twitter_api.me()

        hashed_id = hash_twitter_id(user.id)

        exist_users = [user[0] for user in user_db_session.query(User.hashed_user_id).all()]

        if hashed_id not in exist_users:
            user_db_session.add(User(hashed_id, consumer_key, consumer_key_secret))
            user_db_session.commit()

        return hashed_id

    except Exception:
        raise cannotAuthTwitterException