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

"""
This file shares some constants and classes
"""

from cleep.exception import InvalidMessage
import copy

__all__ = ['CORE_MODULES', 'CATEGORIES', 'PeerInfos',
           'ExecutionStep', 'MessageResponse', 'MessageRequest']

"""
CONSTANTS
"""
CORE_MODULES = [
    'system',
    'update',
    'audio',
    'network',
    'cleepbus',
    'parameters'
]

class CATEGORIES(object):
    """
    Cleep application categories
    """
    # generic application
    APPLICATION = 'APPLICATION'
    # mobile application for car, bike, hiking...
    MOBILE = 'MOBILE'
    # application to configure and use hardware (soundcard, display...)
    DRIVER = 'DRIVER'
    # home automation application (shutter, light...)
    HOMEAUTOMATION = 'HOMEAUTOMATION'
    # media application (music player, video player...)
    MEDIA = 'MEDIA'
    # application based on online service (sms broker, weather provider...)
    SERVICE = 'SERVICE'
    # fun application like christmas tree, halloween stuff...
    HOBBY = 'HOBBY'

    ALL = ['APPLICATION', 'MOBILE', 'DRIVER', 'HOMEAUTOMATION', 'MEDIA', 'SERVICE', 'HOBBY']

class RENDERERS(object):
    """
    Cleep renderer application types
    """
    # audio renderer
    AUDIO = 'audio'
    # display renderer
    DISPLAY = 'display'

    ALL = ['audio', 'display']

class ExecutionStep(object):
    """
    Cleep execution steps
    """
    #boot step (init logger, brokers...)
    BOOT = 0
    #init modules (constructor)
    INIT = 1
    #configure modules (_configure)
    CONFIG = 2
    #application and all modules are running
    RUN = 3
    #stopping cleep
    STOP = 4

    def __init__(self):
        self.step = self.BOOT

class PeerInfos():
    """
    Stores peer informations
    """
    def __init__(self,
                 uuid=None,
                 ident=None,
                 hostname=None,
                 ip=None,
                 port=80,
                 ssl=False,
                 macs=None,
                 cleepdesktop=False,
                 extra={},
                ):
        """
        Constructor

        Args:
            uuid (string): peer uuid provided by cleep
            ident (string): peer identifier provided by external bus
            hostname (string): peer hostname
            ip (string): peer ip
            port (int): peer access port
            ssl (bool): peer has ssl enabled
            macs (list): list of macs addresses
            cleepdesktop (bool): is cleepdesktop peer
            extra (dict): extra peer informations (about hardware...)

        Note:
            Uuid is mandatory because device can change identifier after each connection.

            Id is the identifier provided by your external bus implementation.

            Hostname is mandatory because it is used to display user friendly peer name

            Mac addresses are mandatory because they are used to identify a peer that has been reinstalled (and
            has lost its previous uuid)
        """
        self.uuid = uuid
        self.ident = ident
        self.hostname = hostname
        self.ip = ip
        self.port = port
        self.ssl = ssl
        self.macs = macs
        self.cleepdesktop = cleepdesktop
        self.online = False
        self.extra = extra

    def to_dict(self, with_extra=False):
        """
        Return peer infos as dict

        Args:
            with_extra (bool): add extra data

        Returns:
            dict: peer infos
        """
        out = {
            'uuid': self.uuid,
            'ident': self.ident,
            'hostname': self.hostname,
            'ip': self.ip,
            'port': self.port,
            'ssl': self.ssl,
            'macs': self.macs,
            'cleepdesktop': self.cleepdesktop,
            'online': self.online,
        }
        with_extra and out.update({'extra': self.extra})
        return out

    def __str__(self):
        """
        To string method

        Returns:
            string: peer infos as string
        """
        return 'PeerInfos(uuid:%s, ident:%s, hostname:%s, ip:%s port:%s, ssl:%s, macs:%s, cleepdesktop:%s, online:%s)' % (
            self.uuid,
            self.ident,
            self.hostname,
            self.ip,
            self.port,
            self.ssl,
            self.macs,
            self.cleepdesktop,
            self.online
        )

    def fill_from_dict(self, peer_infos):
        """
        Fill infos from dict

        Args:
            peer_infos (dict): peer informations
        """
        if not isinstance(peer_infos, dict):
            raise Exception('Parameter "peer_infos" must be a dict')
        self.uuid = peer_infos.get('uuid', None)
        self.ident = peer_infos.get('ident', None)
        self.hostname = peer_infos.get('hostname', None)
        self.ip = peer_infos.get('ip', None)
        self.port = peer_infos.get('port', None)
        self.ssl = peer_infos.get('ssl', False)
        self.macs = peer_infos.get('macs', None)
        self.cleepdesktop = peer_infos.get('cleepdesktop', False)
        self.extra = copy.deepcopy(peer_infos.get('extra', {}))

class MessageResponse(object):
    """
    Object that holds message response

    A response is composed of:

        * an error flag: True if error, False otherwise
        * a message: a message about request
        * some data: data returned by the request

    """
    def __init__(self, error=False, message='', data=None, broadcast=False):
        """
        Constructor

        Args:
            error (bool): error flag (default False)
            message (string): response message (default empty string)
            data (any): response data (default None)
            broadcast (bool): response comes from broadcast (default False)
        """
        self.error = error
        self.message = message
        self.data = data
        self.broadcast = broadcast

    def __str__(self):
        """
        Stringify
        """
        return 'MessageResponse(error:%r, message:"%s", data:%s, broadcast:%r)' % (
            self.error,
            self.message,
            str(self.data),
            self.broadcast
        )

    def to_dict(self):
        """
        Return message response
        """
        return {'error':self.error, 'message':self.message, 'data':self.data}

    def fill_from_response(self, response):
        """
        Fill from other response

        Args:
            response (MessageResponse): message response instance
        """
        if not isinstance(response, MessageResponse):
            raise Exception('Parameter "response" must be a MessageResponse instance')

        self.error = response.error
        self.message = response.message
        self.data = copy.deepcopy(response.data)
        self.broadcast = response.broadcast

    def fill_from_dict(self, response):
        """
        Fill from dict

        Args:
            response (dict): response as dict
        """
        if not isinstance(response, dict):
            raise Exception('Parameter "response" must be a dict')

        self.error = response.get('error', False)
        self.broadcast = response.get('broadcast', False)
        self.message = response.get('message', '')
        self.data = response.get('data', None)

class MessageRequest(object):
    """
    Object that holds message request

    A message request is composed of:

        * in case of a command:

            * a command name
            * command parameters
            * the command sender

        * in case of an event:

            * an event name
            * event parameters
            * propagate flag to say if event can be propagated out of the device
            * a device id
            * a startup flag that indicates this event was sent during cleep startup

    Attribute peer_infos is filled when message comes from oustide. This field must also be filled when
    message is intented to be sent to outside.

    Members:
        command (string): command name
        event (string): event name
        propagate (bool): True if event can be propagated out of the device [event only]
        params (dict): list of event or command parameters
        to (string): message module recipient
        sender (string): message sender [command only]
        device_id (string): internal virtual device identifier [event only]
        peer_infos (PeerInfos): peer informations. Must be filled if message comes from outside the device

    Note:
        A message cannot be a command and an event, priority to command if both are specified.
    """
    def __init__(self, command=None, event=None, params={}, to=None):
        """
        Constructor

        Args:
            command (string): request command
            event (string): request event
            params (dict): message parameter if any
            to (string): message recipient if any
        """
        self.command = command
        self.event = event
        self.params = params
        self.to = to
        self.propagate = False
        self.sender = None
        self.device_id = None
        self.peer_infos = None
        self.command_uuid = None
        self.timeout = None

    def __str__(self):
        """
        Stringify function
        """
        if self.command:
            return 'MessageRequest(command:%s, params:%s, to:%s, sender:%s, device_id:%s, peer_infos:%s, command_uuid:%s, timeout:%s)' % (
                self.command,
                str(self.params),
                self.to,
                self.sender,
                self.device_id,
                self.peer_infos.to_dict() if self.peer_infos else None,
                self.command_uuid,
                self.timeout,
            )
        elif self.event:
            return 'MessageRequest(event:%s, propagate:%s, params:%s, to:%s, device_id:%s, peer_infos:%s, command_uuid:%s, propagate:%s)' % (
                self.event,
                self.propagate,
                str(self.params),
                self.to,
                self.device_id,
                self.peer_infos.to_dict() if self.peer_infos else None,
                self.command_uuid,
                self.propagate,
            )

        return 'MessageRequest(Invalid message)'

    def is_broadcast(self):
        """
        Return broadcast status

        Returns:
            bool: True if the request is broadcast
        """
        return True if self.to is None else False

    def is_command(self):
        """
        Return true if message is a command. If not it is an event

        Returns:
            bool: True if message is a command, otherwise it is an event
        """
        return True if self.command else False

    def is_external_event(self):
        """
        Return True if event comes from external device

        Returns:
            bool: True if event comes from external device
        """
        return True if self.peer_infos is not None else False

    def to_dict(self, startup=False, external_sender=None):
        """
        Convert message request to dict object

        Params:
            startup (bool): True if the message is startup message
            external_sender (string): specify module name that handles message from external bus

        Raise:
            InvalidMessage if message is not valid
        """
        if self.command and not self.peer_infos:
            # internal command
            return {
                'command': self.command,
                'params': self.params,
                'to': self.to,
                'sender': self.sender,
                'broadcast': self.is_broadcast(),
            }

        elif self.event and not self.peer_infos:
            # internal event
            return {
                'event': self.event,
                'to': self.to,
                'params': self.params,
                'startup': startup,
                'device_id': self.device_id,
                'sender': self.sender,
                'propagate': self.propagate,
            }

        elif self.command and self.peer_infos:
            # external command
            return {
                'command': self.command,
                'params': self.params,
                'to': self.to,
                'sender': external_sender or self.sender,
                'broadcast': self.is_broadcast(),
                'peer_infos': self.peer_infos.to_dict(),
                'command_uuid': self.command_uuid,
                'timeout': self.timeout,
            }

        elif self.event and self.peer_infos:
            # external event
            return {
                'event': self.event,
                'params': self.params,
                'startup': False,
                'device_id': None,
                'sender': external_sender or self.sender,
                'peer_infos': self.peer_infos.to_dict(),
                'command_uuid': self.command_uuid,
            }

        else:
            raise InvalidMessage()

    def fill_from_request(self, request):
        """
        Fill instance from other request

        Args:
            request (MessageRequest): message request instance
        """
        if not isinstance(request, MessageRequest):
            raise Exception('Parameter "request" must be a MessageRequest instance')

        self.command = request.command
        self.event = request.event
        self.propagate = request.propagate
        self.params = copy.deepcopy(request.params)
        self.to = request.to
        self.sender = request.sender
        self.device_id = request.device_id
        self.peer_infos = None
        self.command_uuid = request.command_uuid
        if request.peer_infos:
            self.peer_infos = PeerInfos()
            self.peer_infos.fill_from_dict(request.peer_infos.to_dict(True))

    def fill_from_dict(self, request):
        """
        Fill instance from other request

        Args:
            request (dict): message request infos
        """
        if not isinstance(request, dict):
            raise Exception('Parameter "request" must be a dict')

        self.command = request.get('command', None)
        self.event = request.get('event', None)
        self.propagate = request.get('propagate', False)
        self.params = copy.deepcopy(request.get('params', {}))
        self.to = request.get('to', None)
        self.sender = request.get('sender', None)
        self.device_id = request.get('device_id', None)
        self.command_uuid = request.get('command_uuid', None)
        self.timeout = request.get('timeout', 5.0)
        self.peer_infos = None
        if request.get('peer_infos', None):
            self.peer_infos = PeerInfos()
            self.peer_infos.fill_from_dict(request.get('peer_infos'))


from comparandum import Comparandum
from alpha import Alpha

#===================================== C L A S S 2/2 ==================================================================
class Analogy(Comparandum):
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
        if len(x) == len(y) == len(z):
            if len(x) == len(y) == len(z) == 1:
                self.f1()
            elif len(x) == len(y) == len(z) == 2:
                self.f2()
            elif len(x) == len(y) == len(z) == 3:
                self.f3()
            else:
                print("Error, too weird for me.")
        else:
            print("Error, too weird for me.")

    def f1(self):
        if self.x.i1 <= self.y.i1 <= self.z.i1:
            i = self.y.i1 - self.x.i1 + self.z.i1
        elif self.y.i1 > self.z.i1 > self.x.i1:
            i = Alpha.len() - self.z.i1
        else:
            i = self.y.i1 + (self.x.i1 - self.z.i1)
        print("Meow: ", Alpha.get(i))
        print("This cat ♥ pretending to be smart.")

    def f2(self):
        r1 = abs(self.x.i2 - self.x.i1)
        r2 = abs(self.y.i2 - self.y.i1)
        r3 = abs(self.z.i2 - self.z.i1)
        d1 = abs(self.y.i2 - self.x.i1)
        d0 = abs(self.y.i1 - self.x.i2)
        d1_vert1 = abs(self.y.i1 - self.x.i1)
        d1_vert2 = abs(self.x.i2 - self.y.i2)
        iu1 = self.z.i2 + d0
        iu2 = iu1 + r2
        r4 = abs(iu2 - iu1)
        d2 = abs(iu1 - self.z.i2)
        if self.z.i2 >= self.z.i1 >= self.y.i2 >= self.y.i1 >= self.x.i2 >= self.x.i1:
            if (r1 + d1 + r2 + d0 + r3 + d2 + r4) <= Alpha.len():
                if d1_vert1 == d1_vert2:
                    print("Meow = ", Alpha.get(iu1) + Alpha.get(iu2))
                else:
                    iu2 += r1
                    print("Meow = ", Alpha.get(iu1) + Alpha.get(iu2))
            else:
                print("Meow = ", Alpha.get(iu1 - Alpha.len()) + Alpha.get((iu2 - Alpha.len())))
            print("This cat ♥ pretending to be smart.")

        elif self.x.i2 > self.y.i2 > self.z.i2 and self.x.i1 < self.y.i1 < self.z.i1:
            r1 = abs(self.y.i1 - self.x.i1)
            iu1 = self.z.i1 + r1
            iu2 = self.z.i2 - r1
            if d1_vert1 == d1_vert2:
                print("Meow = ", Alpha.get(iu1) + Alpha.get(iu2))
            else:
                iu2 -= d12_vert
                print("Meow = ", Alpha.get(iu1) + Alpha.get(iu2))
            print("This cat ♥ pretending to be smart.")
        else:
            # applying to symmetric relations where the answer lies in the interval determined by, say, the first comparandum
            print(
                "I think this requires stochastic reasoning. Are you sure you know what a correct answer would look like?")
    def f3(self):
        r1i = abs(self.x.i2 - self.x.i1)
        r1ii = abs(self.x.i3 - self.x.i2)
        r2i = abs(self.y.i2 - self.y.i1)
        r2ii = abs(self.y.i3 - self.y.i2)
        # defining distances between pair-comparanda
        d1 = abs(self.y.i1 - self.x.i3)
        d0 = abs(self.z.i1 - self.y.i3)
        # defining the index-location ingredients for i comparandum and corresponding char u, s.t. alpha[u]=i
        iu1 = self.z.i3 + d1
        iu2 = iu1 + r1i
        iu3 = iu2 + r1ii
        if r1i == r2i and r1ii == r2ii:
            print("Meow = ", Alpha.get(iu1) + Alpha.get(iu2) + Alpha.get(iu3))
        else:
            print("I'm confused but I know I'm in the primary else clause. So there.")
#======================================================================================================================


import time
import threading
import logging
try:
    import queue
except ImportError:
    import Queue as queue

log = logging.getLogger(__name__)

class Task(object):

    """
    A scheduled task that will be executed by the scheduler
    after a given time interval has passed.

    Attributes:
        name     -- The name of the task.
        seconds  -- The number of seconds to wait before executing.
        callback -- The function to execute.
        args     -- The arguments to pass to the callback.
        kwargs   -- The keyword arguments to pass to the callback.
        repeat   -- Indicates if the task should repeat.
                    Defaults to False.
        qpointer -- A pointer to an event queue for queuing callback
                    execution instead of executing immediately.

    Methods:
        run   -- Either queue or execute the callback.
        reset -- Reset the task's timer.
    """

    def __init__(self, name, seconds, callback, args=None,
                 kwargs=None, repeat=False, qpointer=None):
        """
        Create a new task.

        Arguments:
            name     -- The name of the task.
            seconds  -- The number of seconds to wait before executing.
            callback -- The function to execute.
            args     -- The arguments to pass to the callback.
            kwargs   -- The keyword arguments to pass to the callback.
            repeat   -- Indicates if the task should repeat.
                        Defaults to False.
            qpointer -- A pointer to an event queue for queuing callback
                        execution instead of executing immediately.
        """
        self.name = name
        self.seconds = seconds
        self.callback = callback
        self.args = args or tuple()
        self.kwargs = kwargs or {}
        self.repeat = repeat
        self.next = time.time() + self.seconds
        self.qpointer = qpointer

    def run(self):
        """
        Execute the task's callback.

        If an event queue was supplied, place the callback in the queue;
        otherwise, execute the callback immediately.
        """
        if self.qpointer is not None:
            self.qpointer.put(('schedule', self.callback, self.args))
        else:
            self.callback(*self.args, **self.kwargs)
        self.reset()
        return self.repeat

    def reset(self):
        """
        Reset the task's timer so that it will repeat.
        """
        self.next = time.time() + self.seconds

class Scheduler(object):

    """
    A threaded scheduler that allows for updates mid-execution unlike the
    scheduler in the standard library.

    http://docs.python.org/library/sched.html#module-sched

    Attributes:
        addq        -- A queue storing added tasks.
        schedule    -- A list of tasks in order of execution times.
        thread      -- If threaded, the thread processing the schedule.
        run         -- Indicates if the scheduler is running.
        parentqueue -- A parent event queue in control of this scheduler.

    Methods:
        add     -- Add a new task to the schedule.
        process -- Process and schedule tasks.
        quit    -- Stop the scheduler.
    """

    def __init__(self, parentqueue=None, parentstop=None):
        """
        Create a new scheduler.

        Arguments:
            parentqueue -- A separate event queue controlling this scheduler.
        """
        self.addq = queue.Queue()
        self.schedule = []
        self.thread = None
        self.run = False
        self.parentqueue = parentqueue
        self.parentstop = parentstop

    def process(self, threaded=True):
        """
        Begin accepting and processing scheduled tasks.

        Arguments:
            threaded -- Indicates if the scheduler should execute in its own
                        thread. Defaults to True.
        """
        if threaded:
            self.thread = threading.Thread(name='sheduler_process',
                                           target=self._process)
            self.thread.daemon = True
            self.thread.start()
        else:
            self._process()

    def _process(self):
        """Process scheduled tasks."""
        self.run = True
        try:
            while self.run and (self.parentstop is None or \
                                not self.parentstop.isSet()):
                    wait = 1
                    updated = False
                    if self.schedule:
                        wait = self.schedule[0].next - time.time()
                    try:
                        if wait <= 0.0:
                            newtask = self.addq.get(False)
                        else:
                            if wait >= 3.0:
                                wait = 3.0
                            newtask = self.addq.get(True, wait)
                    except queue.Empty:
                        cleanup = []
                        for task in self.schedule:
                            if time.time() >= task.next:
                                updated = True
                                if not task.run():
                                    cleanup.append(task)
                            else:
                                break
                        for task in cleanup:
                            x = self.schedule.pop(self.schedule.index(task))
                    else:
                        updated = True
                        self.schedule.append(newtask)
                    finally:
                        if updated:
                            self.schedule = sorted(self.schedule,
                                                   key=lambda task: task.next)
        except KeyboardInterrupt:
            self.run = False
            if self.parentstop is not None:
                log.debug("stopping parent")
                self.parentstop.set()
        except SystemExit:
            self.run = False
            if self.parentstop is not None:
                self.parentstop.set()
        log.debug("Quitting Scheduler thread")
        if self.parentqueue is not None:
            self.parentqueue.put(('quit', None, None))

    def add(self, name, seconds, callback, args=None,
            kwargs=None, repeat=False, qpointer=None):
        """
        Schedule a new task.

        Arguments:
            name     -- The name of the task.
            seconds  -- The number of seconds to wait before executing.
            callback -- The function to execute.
            args     -- The arguments to pass to the callback.
            kwargs   -- The keyword arguments to pass to the callback.
            repeat   -- Indicates if the task should repeat.
                        Defaults to False.
            qpointer -- A pointer to an event queue for queuing callback
                        execution instead of executing immediately.
        """
        self.addq.put(Task(name, seconds, callback, args,
                           kwargs, repeat, qpointer))

    def quit(self):
        """Shutdown the scheduler."""
        self.run = False


# %%
# Imports
from src.environments import procgen_names, ProcgenEnvironment
import tensorflow as tf
import numpy as np

# %%
# Requirements
"""
    All The environments must:
        - Load completely
        - Have a observation_spec and action_spec
        - Run parallel
        - be accessable with the interface
"""

# %%
# Simulate run

def test_load_environments():
    for env_name in procgen_names:
        print(f"Testing {env_name}")

        tf_env = ProcgenEnvironment(env_name).to_tf_env()

        time_step = tf_env.reset()
        rewards = []
        steps = []
        num_episodes = 1

        for _ in range(num_episodes):
            episode_reward = 0
            episode_steps = 0

            action = tf.random.uniform([1], 0, 2, dtype=tf.int32)
            time_step = tf_env.step(action)
            episode_steps += 1
            episode_reward += time_step.reward.numpy()  # type: ignore

            rewards.append(episode_reward)
            steps.append(episode_steps)
            time_step = tf_env.reset()

        num_steps = np.sum(steps)
        avg_length = np.mean(steps)
        avg_reward = np.sum(rewards) / 5

        print("num_episodes:", num_episodes, "num_steps:", num_steps)
        print("avg_length", avg_length, "avg_reward:", avg_reward)

def test_tracking_interface():
    class TestTracker:
        testing_rendering_env = False
        rendering_env = True
        def reset(self, **kwargs):
            print(f"is and episode in progress:{kwargs['episode_in_progress']()}")

            kwargs["switch_to_default_env"
                    if self.testing_rendering_env
                    else "switch_to_render_env"]()

            self.testing_rendering_env = not self.testing_rendering_env

        def __call__(self, step_data, **kwargs):
            assert self.testing_rendering_env == ("rgb" in step_data[-1].keys())

    env = ProcgenEnvironment("coinrun")
    tracker = TestTracker()

    env.add_tracker(tracker)

    env.reset()
    env.step(0)
    env.step(0)
    env.step(0)
    env.step(0)

    env.reset()
    env.step(0)
    env.step(0)
    env.step(0)
# %%


import random

r = random.randint(1,10)
max_tries = 3
tries = 0

def checkNumber(number):
    global tries, max_tries
    if number == r:
        print(f'Awesome! You got it in {tries + 1} guesses!')
        return True

    tries += 1
    if number > r:
        print(f'Missed it.  Your number is too high.')
    else:
        print(f'Missed it.  Your number is too low.')

    if tries == max_tries:
        print(f'GAME OVER.  The number was {r}.')

    return False

def guess():
    global tries, max_tries
    while(tries < max_tries):
        n = int(input())

        if checkNumber(n):
            exit()

print('Welcome to the number guessing game.')
print('Guess a number between 1 - 10')
print('You will get three tries to guess the correct number.')

guess()


'''
This is a comment
'''

# Comments are used to explain our codes
# Comments are also used to removed a portion or part of the written code we want to exclude from a block of code

def my_function(age, height):
    print('I am ', age, 'years old and I am', height, ' feet tall.')

age = input('Enter your age: ')
height = input('Enter your height.')

my_function(age, height)


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

from __future__ import absolute_import
def acoustics(problem='figure 9.4'):
    """
    This example solves the 1-dimensional variable-coefficient acoustics
    equations in a medium with a single interface.
    """
    from numpy import sqrt, abs
    from clawpack import pyclaw
    from clawpack import riemann

    solver = pyclaw.ClawSolver1D(riemann.acoustics_variable_1D)

    solver.limiters = pyclaw.limiters.tvd.MC
    solver.bc_lower[0] = pyclaw.BC.extrap
    solver.bc_upper[0] = pyclaw.BC.extrap
    solver.aux_bc_lower[0] = pyclaw.BC.extrap
    solver.aux_bc_upper[0] = pyclaw.BC.extrap

    x = pyclaw.Dimension(-5.0,5.0,500,name='x')
    domain = pyclaw.Domain(x)
    num_eqn = 2
    num_aux = 2
    state = pyclaw.State(domain, num_eqn, num_aux)

    if problem == 'figure 9.4':
        rhol = 1.0
        cl   = 1.0
        rhor = 2.0
        cr   = 0.5
    elif problem == 'figure 9.5':
        rhol = 1.0
        cl   = 1.0
        rhor = 4.0
        cr   = 0.5
    zl = rhol*cl
    zr = rhor*cr
    xc = domain.grid.x.centers

    state.aux[0,:] = (xc<=0)*zl + (xc>0)*zr  # Impedance
    state.aux[1,:] = (xc<=0)*cl + (xc>0)*cr  # Sound speed

    # initial condition: half-ellipse
    state.q[0,:] = sqrt(abs(1.-(xc+3.)**2))*(xc>-4.)*(xc<-2.)
    state.q[1,:] = state.q[0,:] + 0.

    claw = pyclaw.Controller()
    claw.solution = pyclaw.Solution(state, domain)
    claw.solver = solver
    claw.tfinal = 5.0
    claw.num_output_times   = 10

    # Solve
    return claw

if __name__=="__main__":
    from clawpack.pyclaw.util import run_app_from_main
    output = run_app_from_main(acoustics)


import os

# deletes the file
# os.remove("demo.txt")

# checks if the given file exist or not
# is_exists = os.path.exists("edyoda.txt")
# print(is_exists)

# deletes the folder . Please note : Empty needs to be empty
# os.rmdir("C:\\Users\\vashi\\OneDrive\\Documents\\DS291022B\\DS291022B\\Python\\test")

# file = open("C:\\FileHandling\\test.txt","w")

# x mode - creates the file and if file already exist then it will throw an error
file_name = "aryan.txt"
if os.path.exists(file_name) == False:
    file = open(file_name,"x")
    print("File got created!")
else:
    print("File already exist")


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        numbers = []
        stack = deque()
        stack.append((root, ""))

        while stack:
            cur, number = stack.pop()
            new_number = number + str(cur.val)

            if cur.left is None and cur.right is None:
                numbers.append(new_number)
                continue

            if cur.left is not None:
                stack.append((cur.left, new_number))
            if cur.right is not None:
                stack.append((cur.right, new_number))

        val = 0

        for number in numbers:
            val += int(number)

        return val


# You are given a rhyme (a multiline string), in which lines
# are separated by "newline" (\n). Casing does not matter
# for your search, but whitespaces should be removed before
# your search. You should find the word inside the rhyme in
# the horizontal (from left to right) or vertical (from up
# to down) lines. For this you need envision the rhyme as a
# matrix (2D array). Find the coordinates of the word in the
# cut rhyme (without whitespaces).
# The result must be represented as a list --
# [row_start,column_start,row_end,column_end], where
# row_start is the line number for the first letter of the word.
# column_start is the column number for the first letter of the word.
# row_end is the line number for the last letter of the word.
# column_end is the line number for the last letter of the word.
# Counting of the rows and columns start from 1.
# Input: Two arguments. A rhyme as a string and a word as a string (lowercase).
# Output: The coordinates of the word.
# Precondition: The word is given in lowercase
# 0 < |word| < 10
# 0 < |rhyme| < 300

def checkio(text, word):
    matrix_text = text.replace(' ', '').lower().split('\n')
    word_len = len(word)
    num_rows = len(matrix_text)

    # Check horizontal
    for row_num, text_line in enumerate(matrix_text):
        for col_num in range(len(text_line)-word_len):
            if text_line[col_num:col_num+word_len] == word:
                return [row_num+1, col_num+1, row_num+1, col_num+word_len]

    # Check vertical
    for row_num in range(num_rows - word_len + 1):
        min_len = min([len(matrix_text[i]) for i in range(row_num, row_num+word_len)])
        for col_num in range(min_len):
            vertical = ''.join([matrix_text[i][col_num] for i in range(row_num, row_num+word_len)])
            if vertical == word:
                return [row_num+1, col_num+1, row_num+word_len, col_num+1]
    return []

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(u"""DREAMING of apples on a wall,
And dreaming often, dear,
I dreamed that, if I counted all,
-How many would appear?""", u"ten") == [2, 14, 2, 16]
    assert checkio(u"""He took his vorpal sword in hand:
Long time the manxome foe he sought--
So rested he by the Tumtum tree,
And stood awhile in thought.
And as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!""", u"noir") == [4, 16, 7, 16]


import os
import subprocess
import time
from datetime import datetime

def check_host_status(ip):
    command = ['ping', '-c', '1', ip]
    response = subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return response == 0

def main():
    ip = '8.8.8.8'  # Replace with the IP address you want to test

    while True:
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        status = 'Network Active' if check_host_status(ip) else 'Network Down'
        print(f'{timestamp} {status} to {ip}')
        time.sleep(2)

if __name__ == '__main__':
    main()


"""
Application base classes.

.. inheritance-diagram::
   Computer
   Memoizer
   :parts: 1

"""

import pprint
import sys

from .base import deepmixdicts, setnestedattr
from .descriptors import Choice
from .executables import Assembler
from .parser import make_parser, process_assignment_options, parseargs, \
    load_any

def print_full_help(app):
    if app.__doc__ is not None:
        print(app.__doc__)
        print("\n")
    print("Parameters:\n")
    pprint.pprint(app.params(nested=True))

class Computer(Assembler):

    r"""
    Application base class.

    Everything needed for save/load functions are implemented by
    plugins (see: :attr:`.magics`).  Only the method :meth:`run` is
    needed to be implemented most of the cases.

    """

    def cli(self, args=None):
        """
        Run Command Line Interface of this class.

        Examples
        --------
        ::

            myapp.py --datastore.dir OUT
            myapp.py --sub.floats[0] 10
            myapp.py --sub.plotters[0].bin 100
            myapp.py --params parameters.yaml

        If multiple parameter files are given, they will be mixed together
        before given to the class::

            myapp.py --params base.yaml extension.yaml

        Data file for nested classes (``:file=`` modifier)::

            myapp.py --simulator:file=param.yaml --plotter:file=plotter.json

        Literal eval (``:leval=`` modifier)::

            myapp.py --alpha:leval='2**3'

        Regular help::

            myapp.py -h
            myapp.py --help

        Full Help (include full list of parameters)::

            myapp.py -H
            myapp.py --help-all

        """
        parser = self.get_parser()
        parser.add_argument('--params', nargs='+', default=[])
        ns, opts, poss = parseargs(parser, args)
        if ns.help_full:
            print_full_help(self)
            sys.exit()
        if ns.params:
            setnestedattr(self, deepmixdicts(*map(load_any, ns.params)))
        process_assignment_options(self, opts)
        self.execute(*poss)
        return self

    @classmethod
    def get_parser(cls):
        return make_parser(cls.__doc__)

    @classmethod
    def from_param(cls, param, require_all=False, filter_param=False):
        """
        Create an instance based on `param` and `execute` it.

        Parameters
        ----------
        param : dict
        require_all : bool
            If true, a `ValueError` is raised if `param` does not have
            all parameters for this and nested `Parametric` classes.
        filter_param : bool
            If true, keys and sub-keys in `param` which is not valid
            to this class are removed.

        Returns
        -------
        self : Computer

        """
        self = cls(**param)
        self.execute()
        return self

class Memoizer(Computer):

    """
    `Computer` with `.HashDataStore`.

    Examples
    --------

    .. Run the code below in a clean temporary directory:
       >>> getfixture('cleancwd')

    >>> class UpStream1(Memoizer):
    ...
    ...     parameter = 1
    ...     isrun = None
    ...
    ...     def run(self):
    ...         self.results.data = 'result of intense computation'
    ...         self.results.name = type(self).__name__
    ...         self.isrun = True
    ...
    ...     def load(self):
    ...         self.isrun = False
    ...
    >>> class UpStream2(UpStream1):
    ...     pass
    ...
    >>> class DownStream(UpStream1):
    ...     up1 = UpStream1
    ...     up2 = UpStream2
    ...
    ...     def run(self):
    ...         self.up1.execute()
    ...         self.up2.execute()
    ...         super(DownStream, self).run()
    ...         self.results.sum = (self.up1.results.data +
    ...                             self.up2.results.data)
    ...
    >>> up1 = UpStream1()
    >>> up1.execute()
    >>> assert up1.isrun
    >>> up1 = UpStream1()
    >>> up1.execute()
    >>> assert not up1.isrun
    >>> down = DownStream()
    >>> down.execute()
    >>> assert not down.up1.isrun
    >>> assert down.up2.isrun
    >>> assert down.isrun
    >>> down.up1.results.data == 'result of intense computation'
    True

    """

    from .plugins import HashDataStore as datastore

    mode = Choice('auto', 'run', 'load', isparam=False)


from __future__ import annotations

import os
from pathlib import Path
from typing import *

import pytest

from googleapiutils2.drive import Drive
from googleapiutils2.sheets import Sheets
from googleapiutils2.utils import Credentials, GoogleMimeTypes, get_oauth2_creds

@pytest.fixture(scope="session", autouse=True)
def creds():
    config_path = Path(
        os.environ.get("GOOGLE_API_CREDENTIALS", "auth/credentials.json")
    )
    return get_oauth2_creds(client_config=config_path)

@pytest.fixture(scope="session", autouse=True)
def drive(creds: Credentials):
    return Drive(creds=creds)

@pytest.fixture(scope="session", autouse=True)
def sheets(creds: Credentials):
    return Sheets(creds=creds)

@pytest.fixture(scope="session", autouse=True)
def google_folders(drive: Drive):
    test_folder_path = Path(os.environ.get("GOOGLE_API_TEST_PATH", "googleapiutils2"))

    sheets_folder = test_folder_path / "sheets"
    drive_folder = test_folder_path / "drive"

    folder_paths = [sheets_folder, drive_folder]

    google_folders = {
        folder_path.name: drive.create(
            name=folder_path,
            mime_type=GoogleMimeTypes.folder,
            get_extant=True,
            recursive=True,
        )
        for folder_path in folder_paths
    }

    yield google_folders

    for folder in google_folders.values():
        drive.delete(folder["id"])


import pandas as pd
import numpy as np
from sklearn.linear_model import SGDClassifier, LogisticRegression
from sklearn.preprocessing import normalize
from sklearn.metrics import precision_score, recall_score, f1_score
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from scipy.stats import pearsonr

def test(n, data):
  X = np.zeros((n, 1))
  Y = []
  i = 0
  prices = []
  for index, hit in data.iterrows():
    price = int(hit['price'])
    prices.append(price)
    X[i, :] = np.array(price)
    points = int(hit['points'])
    Y.append(points)
    i += 1
  return X, Y, prices

if __name__ == '__main__':
	data = pd.read_csv('train.csv')

	X_train, Y_train, p = test(109789, data)
	print('Retrieved data')
	print('Correlation: ' + str(pearsonr(p, Y_train)[0]))
	model = LogisticRegression().fit(X_train, Y_train)
	print('Training complete')

	datat = pd.read_csv('test.csv')
	X_test, Y_test, p = test(13707, datat)
	Y_pred = model.predict(X_test)

	print('F1: {}'.format(f1_score(Y_test, Y_pred, average='micro')))
	print(Y_pred)

	with open('test_output_price.txt' ,'w') as f:
	  for i in Y_pred:
	    f.write(str(i) + '\n')


# https://leetcode.com/problems/longest-turbulent-subarray/
# tags: #array, #dp, #sliding_window
#
# Solution 1: Sliding window
# Keep track of the last flip and current flip, if they are the same then reset start_index to i - 1
# Edge case when arr[i] == arr[i - 1], in this case reset start_index to i as last_flip is invalid
# Time Complexity: O(n), Space complexity: O(1)
#
# Solution 2: dp
# We use the counter to track the sub array size.
# Our counter is positive  if we expect '>', and '<' otherwise. For each turn we flip the sign
# Time complexity: O(n), Space complexity: O(1)
from typing import List

class Solution:
    def maxTurbulenceSize(self, arr: List[int]) -> int:
        max_length, start_index, last_flip = 1, 0, None
        for i in range(1, len(arr)):
            if arr[i] == arr[i - 1]:
                start_index = i
                last_flip = None
                continue

            current_flip = 1 if arr[i] > arr[i - 1] else -1
            if last_flip is None or last_flip == current_flip * -1:
                max_length = max(max_length, i - start_index + 1)
            else:
                start_index = i - 1

            last_flip = current_flip

        return max_length

    def maxTurbulenceSize_dp(self, arr: List[int]) -> int:
        max_length, counter = 0, 0
        for i in range(1, len(arr)):
            if arr[i] > arr[i - 1]:
                counter = counter + 1 if counter > 0 else 1
            elif arr[i] < arr[i - 1]:
                counter = counter - 1 if counter < 0 else -1
            else:
                counter = 0

            max_length = max(max_length, abs(counter))
            counter *= -1

        return max_length + 1

if __name__ == "__main__":
    sol = Solution()
    print(sol.maxTurbulenceSize_dp(arr=[9, 4, 2, 10, 7, 8, 8, 1, 9]))  # 5
    print(sol.maxTurbulenceSize_dp(arr=[4, 8, 12, 16]))  # 2
    print(sol.maxTurbulenceSize_dp(arr=[100]))  # 1


import re

T = int(input())

for t in range(1, T+1):
    N = int(input())
    P = { input() for i in range(N) }
    print('Case #{}: '.format(t), end='')

    pure = { p for p in P if '*' not in p }
    if len(pure) > 1:
        print('*')
        continue

    if len(pure):
        ans = pure.pop()
        P.remove(ans)
        patterns = [re.compile(p.replace('*', '.*')) for p in P]
        if all(p.match(ans) for p in patterns):
            print(ans)
        else:
            print('*')
        continue

    prefixes = { p[:p.index('*')] for p in P }
    middles = ''.join({ p[p.index('*')+1:p.rindex('*')].replace('*', '') for p in P })
    suffixes = { p[p.rindex('*')+1:] for p in P }

    longest_prefix = max(prefixes, key=lambda x: len(x))
    longest_suffix = max(suffixes, key=lambda x: len(x))

    if not all(longest_prefix.startswith(prefix) for prefix in prefixes):
        # print(longest_prefix, prefixes)
        print('*')
        continue

    if not all(longest_suffix.endswith(suffix) for suffix in suffixes):
        # print(longest_suffix, suffixes)
        print('*')
        continue

    print(longest_prefix + middles + longest_suffix)


#lab 8
"""Contains the hash table class and all of its implemented functions. In my implementation, I use the SlotEntry
class to store both the key and item and there is a list of these items per slot
"""

class SlotEntry:
	def __init__(self, key = None, item = None):
		self.key = key
		self.item = item

class MyHashTable:
	def __init__(self, table_size = 11):
		self.table_size = table_size
		self.table = [[] for _ in range(table_size)]
		#create a blank class for each list
		for slot in self.table:
			startingslot = SlotEntry()
			slot.append(startingslot)

		self.num_items = 0
		self.num_collisions = 0

	def insert(self, key, item):
		#get the insert spot
		insertspot = key%self.table_size
		#check the insert spot for that key
		if(self.table[insertspot][0].key == None):
			# insert at spot since it is empty
			self.table[insertspot][0].key = key
			self.table[insertspot][0].item = item
			#newentry = SlotEntry(key, item)
			#self.table[insertspot].append(newentry)
			self.num_items+=1
		else:
			#there are other keys present, increase collisions
			#first check if they key is already in the list
			check = False
			for i in range(len(self.table[insertspot])):
				if(self.table[insertspot][i].key == key):
					#if it is the same, replacing the item with the new item
					self.table[insertspot][i].item = item
					check = True

			if(check is False):
				#then the key is not in that slot in the hash table, so adding it
				self.num_collisions +=1
				newentry = SlotEntry(key, item)
				self.table[insertspot].append(newentry)
				self.num_items +=1

		if(self.load_factor() > 1.5):
			#rehash the entire table
			self.grow_table()

	def grow_table(self):
		oldtable = self.table
		self.table_size = self.table_size*2+1
		self.table = [[] for _ in range(table_size)]
		for i in range(len(oldtable)):
			for x in i:
				key = x.key
				item = x.item
				self.insert(key, item)

	def get(self, key):
		try:
			spot = key%self.table_size
			for i in range(len(self.table[spot])):
				if(self.table[spot][i].key == key):
					return (self.table[spot][i].key, self.table[spot][i].item)

		except:
			raise LookupError("Key is not found")

	def remove(self, key):
		try:
			for i in range(len(self.table)):
				for x in range(len(self.table[i])):
					if(self.table[i][x].key == key):
						itemremoved = self.table[i][x]
						self.table[i][x] = None
			return (itemremoved.key, itemremoved.item)

		except:
			raise LookupError("Key is not found")

	def size(self):
		return self.num_items

	def load_factor(self):
		load = self.num_items/self.table_size
		return float(load)

	def collisions(self):
		#increase when you hash to an occupied spot
		return self.num_collisions


# HTTP Verbs
# GET, POST, PUT, PATCH, DELETE

import requests

url = "https://icanhazdadjoke.com/"
response = requests.get(url, headers= { "Accept": 'application/json' })
# print(response.text)
# print(response.json())
data = response.json()
print(data['joke'])


class Member:
    def __init__(self, name: str, amount: int, hasChildren=False):
        self.name = name
        self.amount = amount
        self.hasChildren = hasChildren
        self.children: list[Member] = []

name = input("Enter parent-member name: ")
choice = input(f"Does {name} have child members [y/n]: ")
head = Member(name, 0, True if choice == "y" else False)

def getChildDetails(node):
    q = [node]
    while len(q):
        cur = q.pop()
        if cur.hasChildren:
            childrenNames = input(f"Enter children of {cur.name}: ").replace(
                " ", "").split(",")

            for childName in childrenNames:
                choice = input(f"Does {childName} have child members [y/n]: ")
                member = Member(childName, 0, True if choice == "y" else False)
                cur.children.append(member)
                q.append(member)

def setAmount(node):
    if not node.hasChildren:
        node.amount = 250
        return

    for child in node.children:
        node.amount += 500
        setAmount(child)

getChildDetails(head)

def printTree(node, level):
    if not node:
        return
    print("   "*level, node.name, node.amount)
    for child in node.children:
        printTree(child, level+1)

printTree(head, 0)


import requests
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import numpy as np
import re

#from basketball_reference_scraper.teams import get_roster, get_team_stats, get_opp_stats, get_roster_stats, get_team_misc
from basketball_reference_scraper.players import get_stats
#, get_game_logs, get_player_headshot
#from basketball_reference_scraper.seasons import get_schedule, get_standings
#from basketball_reference_scraper.box_scores import get_box_scores
from basketball_reference_scraper.pbp import get_pbp
from basketball_reference_scraper.shot_charts import get_shot_chart
#from basketball_reference_scraper.injury_report import get_injury_report
#from basketball_reference_scraper.drafts import get_draft_class

date = '2022-04-10'
home = 'HOU'
away = 'ATL'
d = get_shot_chart(date, home, away)
homesize = len(d[home])
awaysize = len(d[away])

class Shot():
    x = 0
    y = 0
    quarter = 0
    timeleft = 0
    player = ""
    make_miss = ""
    value = 0
    distance = 0
    team = ""
    def __init__(self, _x,_y,qtr,time,_player,made,val,dist,_team):
        self.x = _x
        self.y = _y
        self.quarter = qtr
        self.timeleft = time
        self.player = _player
        self.make_miss = made
        self.value = val
        self.distance = dist
        self.team = _team

    def setX(self, int):
        self.x = int

    def getX(self):
        return self.x

    def setY(self, int):
        self.y = int

    def getY(self):
        return self.y

    def getQuarter(self):
        return self.quarter

    def getTime(self):
        return self.timeleft

    def getPlayer(self):
        return self.player

    def getMake(self):
        return self.make_miss

    def getValue(self):
        return self.value

    def getDistance(self):
        return self.distance

    def getTeam(self):
        return self.team

def doesitwork():

    x_arrA = [0.0 for i in range(len(d[away]))]
    y_arrA = [0.0 for i in range(len(d[away]))]
    shotArr = [0.0 for i in range(len(d[away]) + len(d[home]))]

    for i in range(awaysize):
        x = d[away].iloc[i].get('x')
        y = d[away].iloc[i].get('y')
        x = x[0:4:1]
        x = float(x)
        y = y[0:4:1]
        y = float(y)
        quarter = d[away].iloc[i].get('QUARTER')
        tr = d[away].iloc[i].get('TIME_REMAINING')
        plr = d[away].iloc[i].get('PLAYER')
        made = d[away].iloc[i].get('MAKE_MISS')
        val = d[away].iloc[i].get('VALUE')
        dist = d[away].iloc[i].get('DISTANCE')
        dist = dist[0:2:1]
        team = away
        s = Shot(x,y,quarter,tr,plr,made,val,dist,team)
        shotArr[i] = s

    for i in range(homesize):
        x = d[home].iloc[i].get('x')
        y = d[home].iloc[i].get('y')
        x = x[0:4:1]
        x = float(x)
        y = y[0:4:1]
        y = float(y)
        quarter = d[home].iloc[i].get('QUARTER')
        tr = d[home].iloc[i].get('TIME_REMAINING')
        plr = d[home].iloc[i].get('PLAYER')
        made = d[home].iloc[i].get('MAKE_MISS')
        val = d[home].iloc[i].get('VALUE')
        dist = d[home].iloc[i].get('DISTANCE')
        dist = float(dist[0:2:1])
        team = home
        s = Shot(x,y,quarter,tr,plr,made,val,dist,team)
        shotArr[i + awaysize] = s

    shotArr.sort(reverse = True, key = sortFunc)
    plotpoint(shotArr)

def sortFunc(shot):
    return shot.getTime()

# Function to draw basketball court
def create_court(ax, color):
    # Short corner 3PT lines
    ax.plot([-220, -220], [0, 140], linewidth=2, color=color)
    ax.plot([220, 220], [0, 140], linewidth=2, color=color)

    # 3PT Arc
    ax.add_artist(mpl.patches.Arc((0, 140), 440, 315, theta1=0, theta2=180, facecolor='none', edgecolor=color, lw=2))

    # Lane and Key
    ax.plot([-80, -80], [0, 190], linewidth=2, color=color)
    ax.plot([80, 80], [0, 190], linewidth=2, color=color)
    ax.plot([-60, -60], [0, 190], linewidth=2, color=color)
    ax.plot([60, 60], [0, 190], linewidth=2, color=color)
    ax.plot([-80, 80], [190, 190], linewidth=2, color=color)
    ax.add_artist(mpl.patches.Circle((0, 190), 60, facecolor='none', edgecolor=color, lw=2))

    # Rim
    ax.add_artist(mpl.patches.Circle((0, 60), 15, facecolor='none', edgecolor=color, lw=2))

    # Backboard
    ax.plot([-30, 30], [40, 40], linewidth=2, color=color)

    # Remove ticks
    ax.set_xticks([])
    ax.set_yticks([])

    # Set axis limits
    ax.set_xlim(-275, 275)
    ax.set_ylim(0, 470)

    # General plot parameters
    mpl.rcParams['font.family'] = 'Avenir'
    mpl.rcParams['font.size'] = 18
    mpl.rcParams['axes.linewidth'] = 2

def plotpoint(shotArr):
    x_arr = [0.0 for i in range(awaysize + homesize)]
    y_arr = [0.0 for i in range(awaysize + homesize)]
    for i in range(len(shotArr)):
        x_arr[i] = shotArr[i].getX()
        y_arr[i] = shotArr[i].getY()

    # Draw basketball court
    fig = plt.figure(figsize=(4, 3.76))
    ax = fig.add_axes([0, 0, 1, 1])
    ax = create_court(ax, 'black')

    with cbook.get_sample_data('toycen.jpg') as image_file:
        image = plt.imread(image_file)

    plt.imshow(image, origin='upper', extent=(-275, 275, 0, 470))

    #x_num = np.array(x_arr)
    #y_num = np.array(y_arr)
    #plt.hexbin(x_num * 10 - 275, y_num * 10 + 60, gridsize=(15, 15), extent=(-275, 275, 0, 470), bins='log', cmap='Blues')

    makes = 0
    shots = 0
    TPmakes = 0
    TPshots = 0
    longest = 0
    indexLong = 0
    team = ''
    homepoints = 0
    awaypoints = 0

    for i in range(len(shotArr)):
        if int(shotArr[i].getDistance()) > int(longest):
            if shotArr[i].getMake() == 'MAKE':
                longest = shotArr[i].getDistance()
                indexLong = i

    for i in range(len(shotArr)):
        plt.pause(0.1)
        if i == indexLong:
            #image = plt.imread(get_player_headshot(shotArr[i].getPlayer()))
            #plt.imshow(image, origin='upper', extent=((x_arr[i] * 10 - 265), (x_arr[i] * 10 - 285), (y_arr[i] * 10 + 50), (y_arr[i] * 10 + 70)))
            plt.plot((x_arr[i] * 10 - 275), y_arr[i] * 10 + 60, 'y*--', linewidth=2, markersize=15, mec='black')
        if shotArr[i].getMake() == 'MAKE':
            if i != indexLong:
                if shotArr[i].getTeam() == home:
                    plt.plot((x_arr[i] * 10 - 275), y_arr[i] * 10 + 60, 'bo--', linewidth=2, markersize=12, mec='black')
                else:
                    plt.plot((x_arr[i] * 10 - 275), y_arr[i] * 10 + 60, 'ro--', linewidth=2, markersize=12, mec='black')
            shots += 1
            makes += 1
            if shotArr[i].getValue() == 3:
                if int(shotArr[i].getDistance()) > 27:
                    print(shotArr[i].getPlayer() + " makes a DEEEEEP " + str(shotArr[i].getValue()) + "!")
                else:
                    print(shotArr[i].getPlayer() + " makes a " + str(shotArr[i].getValue()) + "!")
            elif int(shotArr[i].getDistance()) > 5:
                print(shotArr[i].getPlayer() + " makes a midrange " + str(shotArr[i].getValue()) + "!")
            else:
                print(shotArr[i].getPlayer() + " makes a layup " + str(shotArr[i].getValue()) + "!")

            if shotArr[i].getValue() == 3:
                TPshots += 1
                TPmakes += 1
                if shotArr[i].getTeam() == home:
                    homepoints += 3
                else:
                    awaypoints += 3
            else:
                if shotArr[i].getTeam() == home:
                    homepoints += 2
                else:
                    awaypoints += 2
        else:
            if shotArr[i].getTeam() == home:
                plt.plot((x_arr[i] * 10 - 275), y_arr[i] * 10 + 60, 'bx--', linewidth=2, markersize=12)
            else:
                plt.plot((x_arr[i] * 10 - 275), y_arr[i] * 10 + 60, 'rx--', linewidth=2, markersize=12)
            shots += 1
            if shotArr[i].getValue() == 3:
                print(shotArr[i].getPlayer() + " misses a " + str(shotArr[i].getValue()) + "...")
                TPshots += 1
            elif int(shotArr[i].getDistance()) > 5:
                print(shotArr[i].getPlayer() + " misses a midrange " + str(shotArr[i].getValue()) + "...")
            else:
                print(shotArr[i].getPlayer() + " misses a layup " + str(shotArr[i].getValue()) + "...")

    fgm = int((makes/shots) * 100)
    TPfgm = int((TPmakes/TPshots) * 100)
    print(str(fgm) + " FG%")
    print(str(TPfgm) + " 3PT%")
    print("Home: " + str(homepoints) + "\nAway: " + str(awaypoints))
    plt.show()

if __name__ == "__main__":
    doesitwork()


#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals

__license__   = 'GPL v3'
__copyright__ = '2020, Bennett Kanuka <bkanuka@gmail.com>'
__docformat__ = 'restructuredtext en'

# The class that all interface action plugins must inherit from
from calibre.gui2.actions import InterfaceAction

class InterfacePlugin(InterfaceAction):

    name = 'Hide Statusbar'
    action_spec = ('Toggle Statusbar', 'dialog_information.png',
                        'Toggle Statusbar', 'Ctrl+Shift+S')

    def gui_layout_complete(self):
        self.gui.status_bar.hide()
        self.qaction.triggered.connect(self.toggle)

    def toggle(self):
        if self.gui.status_bar.isVisible():
            self.gui.status_bar.hide()
        else:
            self.gui.status_bar.show()


#Json
import json

x = 1, 'simple', 'lista', 'clases'

x = json.dumps(x) #Modifica a un Json

diccionario = dict(Legolas = 'Bosque negro', Aragorn = 'Gondor', Gimli = 'Montañas Nubladas')

with open('texto.txt', 'r+') as f:
    #json.dump(diccionario, f) # Escribe el diccionario formato Json
    #No se puede lanzar un dump y luego un load

    data = json.load(f) #Solo se puede hacer load de un json bien formado
    print(data)


"""
Модуль настройки бота
"""

import os

from dotenv import load_dotenv, find_dotenv

if not find_dotenv():
    exit('Ошибка! Файл ".env" не найден.')
else:
    load_dotenv()

EXECUTE_CMD = os.getenv('EXECUTE_CMD')
BOT_TOKEN = os.getenv('BOT_TOKEN')
DATABASE = os.getenv('DATABASE')
API_HOST = os.getenv('API_HOST')
API_KEY = os.getenv('API_KEY')


class Solution:
    def totalFruit(self, tree):
        l, nums, res = 0, collections.Counter(), 0
        for r in range(len(tree)):
            nums[tree[r]] += 1
            while len(nums) > 2:
                nums[tree[l]] -= 1
                if not nums[tree[l]]:
                    nums.pop(tree[l])
                l += 1
            res = max(res, r - l + 1)
        return res


from utils import ListNode

def mergeTwoLists(l1, l2):
    """
    Straight forward merge
    Time: O(m+n), m = len(l1), n = len(l2)
    Space: O(1)
    """
    # Assignment such as a = l1 (l1 is a ListNode)
    # will assign the address to start, change of a's `next` or `val` will result in change in l1's `next` or `val`
    # because the changes were made to the object stored in the common address
    # similarly if two assignments were made of the same variable: a, b =l1, l1
    # then change of a's `next` or `val` will result in change in b's and l1's
    # If reassign a to another ListNode say l2, a = l2, then change of a will not affect that of b and l1

    # Summary: Changing an object's properties through one of its assigned variable will change the object itself and
    # all the other assigned variables

    curr = ListNode(-1)  # auxiliary head pointer to retrieve the whole list
    start = curr
    while l1 is not None or l2 is not None:
        # if one of them is empty and then append the other to the end of the result and return
        if l1 is None:
            curr.next = l2
            return start.next
        elif l2 is None:
            curr.next = l1
            return start.next
        # if both are non-empty
        if l1.val < l2.val:
            # below will append all nodes of l1 to curr, `start` will change at the same time
            # e.g. curr = [3, 5], l1 = [4, 6], l2 = [5], start = [-1, 1, 2, 3, 5]
            # then after the execution, curr = [3, 4, 6], start = [-1, 1, 2, 3, 4, 6]
            curr.next = l1
            # below will advance l1 by 1 node
            # following the above example, after execution, l1 = [6]
            l1 = l1.next
            # below will advance curr by 1 node, and has no effect on `start`
            # since curr will be assigned to a new ListNode (curr.next)
            # and no changes were made to existing nodes
            # following the above example, after execution, curr = [4, 6], l1 = [6], l2 = [5]
            # in the next iteration, enter l2.val < l1.val and curr will be [4, 5]...
            curr = curr.next
        else:
            curr.next = l2
            l2 = l2.next
            curr = curr.next

    return start.next

def mergeTwoLists_recur(l1, l2):
    """
    Recursion
    Time: O(m+n), m = len(l1), n = len(l2)
    Space: O(m+n), size of the recursion stack
    """
    # res =
    # 1) l1[0] + merge(l1[1:], l2) if (l1[0] < l2[0])
    # 2) l2[0] + merge(l1, l2[1:]) if (l1[0] >= l2[0])
    # if l1 or l2 empty, append the non-empty list
    # recursion ends if either one of the two is empty
    if l1 is None:
        return l2
    elif l2 is None:
        return l1
    elif l1.val < l2.val:
        l1.next = mergeTwoLists_recur(l1.next, l2)
        # return the merged list
        return l1
    else:
        l2.next = mergeTwoLists_recur(l1, l2.next)
        # return the merged list
        return l2


# inter alea
# ebkt 2023

import time # time library for sleep timer
import board # import board info
from adafruit_motorkit import MotorKit
import random # random library

kit = MotorKit(i2c=board.I2C()) #create kit variable
order = [kit.motor1, kit.motor2, kit.motor3, kit.motor4] # store each motor in an array so we can randomise the order

sleep1 = 0.5 # period for how long solenoids will be ON
sleep2 = 0.5 # period for how long solenoids will be OFF

# randomisation function
def randomise():
    print("changing sleep time")                            # tell us what's happening
    _sleep1 = random.random()                               # new variable _sleep1 to avoid using globals, will be returned and used as sleep1
    _sleep2 = random.random()                               # same for _sleep2
    _order = sorted(order, key = lambda _: random.random()) # reorder the array of solenoids
    print(_order)                                           # print the new array order
    return _sleep1, _sleep2, _order                         # return the two sleep values and new array

while True:
    for i in range(len(order)):                 # loop through however many motors we have in the order array
        order[i].throttle = 1.0                 # each time through the for loop, check which motor is currently stored at that index in order[] and fire it
        time.sleep(sleep1)                      # rest sleep1 (motor is on)
        order[i].throttle = 0                   # turn this motor off
        time.sleep(sleep2)                      # rest sleep2 (motor is off)
        # do the above for all 4 motors
        # if we're at the end of the for loop/array, randomly decide whether to randomise and all sleep for a bit
        if i==len(order)-1 and random.random() < 0.3:
            print("sleeping")                   # tell us the motors are sleeping
            sleep1, sleep2, order = randomise() # adjust variables (this line only works because the function returns 3 values)
            time.sleep(random.randint(1, 10))   # now all motors sleep


from django.db import models
from users.models import Profesional, Paciente
from historia.models import HistoriaClinica

# Create your models here.
"""
class Ejemplo(models.Model o lo que necesites heredar):
    campo1 = models.CharField(verbose_name='Nombre del campo', max_length=50)
    campo2 = models.ForeingKey(Para Relacionar Modelos)

    class Meta:
        verbose_name = 'Ejemplo'
        verbose_name_plural = 'Ejemplos'

    def __str__(self):
        return f'Lo que se vaya a mostrar en el admin'
"""

class Seguimiento(models.Model):
    # Relacion
    historia = models.ForeignKey(to=HistoriaClinica, on_delete=models.CASCADE)

    class Meta:
        abstract = True

    def __str__(self):
        return f"Seguimiento"

class SeguimientoEspecialidad(Seguimiento):
    class Meta:
        verbose_name = "Seguimiento Especialidad"
        verbose_name_plural = "Seguimientos Especialidad"

    def __str__(self):
        return f"Seguimiento Especialidad:{self.id}"

class SeguimientoMedicinaGeneral(Seguimiento):
    class Meta:
        verbose_name = "Seguimiento Medicina General"
        verbose_name_plural = "Seguimientos Medicina General"

    def __str__(self):
        return f"Seguimiento Medicina General:{self.id}"

class SeguimientoEnfermeria(Seguimiento):
    class Meta:
        verbose_name = "Seguimiento Enfermeria"
        verbose_name_plural = "Seguimientos Enfermeria"

    def __str__(self):
        return f"Seguimiento Enfermeria:{self.id}"

class Estrategia(models.Model):
    # Relacion
    seguimiento_especialidad = models.ForeignKey(
        to=SeguimientoEspecialidad, on_delete=models.CASCADE
    )

    # Campos
    objetivo = models.TextField(verbose_name="Objetivo")
    subjetivo = models.TextField(verbose_name="Subjetivo")
    analisis = models.TextField(verbose_name="Analisis")
    plan = models.TextField(verbose_name="Plan")

    class Meta:
        verbose_name = "Estrategia"
        verbose_name_plural = "Estrategias"

    def __str__(self):
        return f"Estrategias:{self.id}"

class Formulario(models.Model):
    # Relaciones
    profesional = models.ForeignKey(to=Profesional, on_delete=models.CASCADE)
    paciente = models.ForeignKey(to=Paciente, on_delete=models.CASCADE)
    seguimiento_especialidad = models.ForeignKey(
        to=SeguimientoEspecialidad, on_delete=models.CASCADE
    )
    seguimiento_medicina_general = models.ForeignKey(
        to=SeguimientoMedicinaGeneral, on_delete=models.CASCADE
    )
    seguimiento_enfermeria = models.ForeignKey(
        to=SeguimientoEnfermeria, on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = "Formulario"
        verbose_name_plural = "Formularios"

    def __str__(self):
        return f"Formulario: {self.paciente}"

class SignosVitales(models.Model):
    # Relaciones
    formulario = models.ForeignKey(to=Formulario, on_delete=models.CASCADE)

    # Campos
    tension_arterial_sistolica = models.IntegerField(
        verbose_name="Tension Arterial Sistolica"
    )
    tension_diastolica = models.IntegerField(verbose_name="Tension Diastolica")
    frecuencia_respiratoria = models.IntegerField(
        verbose_name="Frecuencia Respiratoria"
    )
    saturacion_oxigeno = models.IntegerField(verbose_name="Saturacion Oxigeno")
    frecuencia_cardiaca = models.IntegerField(verbose_name="Frecuencia Cardiaca")

    class Meta:
        verbose_name = "Signos Vitales"
        verbose_name_plural = "Signos Vitales"

    def __str__(self):
        return f"Signos Vitales: {self.id}"

class DatosAntropometricos(models.Model):
    # Relaciones
    formulario = models.ForeignKey(to=Formulario, on_delete=models.CASCADE)

    # Campos
    talla = models.IntegerField(verbose_name="Talla")
    peso = models.IntegerField(verbose_name="Peso")
    observaciones = models.TextField(verbose_name="Observaciones Generales")

    class Meta:
        verbose_name = "Datos Antropometricos"
        verbose_name_plural = "Datos Antropometricos"

    def __str__(self):
        return f"Datos Antropometricos: {self.id}"

class Observaciones(models.Model):
    # Relaciones
    formulario = models.ForeignKey(to=Formulario, on_delete=models.CASCADE)

    # Campos
    observaciones = models.TextField(verbose_name="Observaciones")

    class Meta:
        verbose_name = "Observaciones"
        verbose_name_plural = "Observaciones"

    def __str__(self):
        return f"Observaciones:{self.id}"

class NotasAclaratorias(models.Model):
    # Relaciones
    formulario = models.ForeignKey(to=Formulario, on_delete=models.CASCADE)
    profesional = models.ForeignKey(to=Profesional, on_delete=models.CASCADE)
    historia = models.ForeignKey(to=HistoriaClinica, on_delete=models.CASCADE)

    # Campos
    contexto = models.TextField(verbose_name="Contexto")
    especialidad = models.CharField(verbose_name="Especialidad", max_length=50)
    fecha = models.DateField(auto_now_add=True)

    class Meta:
        verbose_name = "Nota Aclaratoria"
        verbose_name_plural = "Notas Aclaratorias"

    def __str__(self):
        return f"{self.fecha} Profesional:{self.profesional} Historia:{self.historia}"


"""
small_matrix_app.matrix_app.main_window.py
Window is the display window for the matrix_app.
The same instance of this class is used throughout the entire lifetime of the app.
The different "screens" of the application are achieved by changing out Window's central widget.
The Main Window is responsible for hooking up change-screen buttons in whichever widget it sets as its centralwidget.
"""

import sys

from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QAction, QDesktopWidget, QMessageBox
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QStatusBar
from PyQt5.QtWidgets import QToolBar

from matrix_app.all_exceptions import (
    CriticalFailure,
    FailureMessage,
    InternalDbError,
)
from matrix_app.db_widget import DatabaseModel, DisplayData, RunData
from matrix_app.display_stats_widget import DisplayStatsPage
from matrix_app.home_screen_widget import HomeScreenPage
from matrix_app.saved_runs_widget import SavedRunsPage
from matrix_app.matrix_entry_widget import MatrixEntryPage

# from matrix_app.matrix_entry_widget import MatrixEntryPage

from typing import List

class Window(QMainWindow):
    """Main Window."""

    def __init__(self, db_name="SavedRuns", parent=None):
        """Sets up and display Window and places Homepage  Widget as the central widget"""
        super().__init__(parent)
        self._init_db(db_name)
        self._initUi()
        self.show()

    def _initUi(self):
        self.resize(QDesktopWidget().availableGeometry(self).size() * 0.7)
        self.setWindowTitle("Matrix Stats")
        self._create_tool_bar()
        self._create_status_bar()
        self._display_home_screen_page()
        # self.displayMatrixEntryPage()

    def _init_db(self, db_name) -> object:
        try:
            self.data_run_model = DatabaseModel(db_name)
        except CriticalFailure as err:
            ok = QMessageBox().question(
                self,
                "Info Box",
                str(err) + " System will shut down.",
                QMessageBox.Ok,
            )
            self.close()

    # Main Menu UI Components
    def _create_tool_bar(self):
        self.tools = QToolBar()
        self.addToolBar(self.tools)
        self.tools.addAction("Exit", self.close)

        self.home_screen_page_action = QAction("Return to Home Scren", self)
        self.home_screen_page_action.setStatusTip(
            "Click me to go back to the home screen!"
        )
        self.home_screen_page_action.triggered.connect(self._display_home_screen_page)
        self.tools.addAction(self.home_screen_page_action)

        self.saved_runs_page_action = QAction("View Saved Runs", self)
        self.saved_runs_page_action.setStatusTip("Click me to view your saved runs!")
        self.saved_runs_page_action.triggered.connect(self._display_saved_runs_page)
        self.tools.addAction(self.saved_runs_page_action)

        self.resize_screen_action = QAction("Default Screensize")
        self.resize_screen_action.setStatusTip(
            "Click me to make me 70% of your screen!"
        )
        self.resize_screen_action.triggered.connect(self.resize_me)
        self.tools.addAction(self.resize_screen_action)

    def _create_status_bar(self):
        status = QStatusBar()
        status.showMessage("hi!")
        self.setStatusBar(status)

    def resize_me(self):
        """ Sets the Window size to 70% of the current screen"""
        self.resize(QDesktopWidget().availableGeometry(self).size() * 0.7)

    # Controller-View
    # Choose to instantiate a new central widget for each screen change since
    # there is no reason to remember widget state

    def _display_matrix_entry(self):
        self.matrix_entry_page = MatrixEntryPage()

        self.matrix_entry_page.calculate_button.clicked.connect(
            self._matrix_entry_page_on_submit_matrices_button_clicked
        )

        self.setCentralWidget(self.matrix_entry_page)

    def _display_home_screen_page(self):
        self.home_screen_page = HomeScreenPage()

        self.home_screen_page.create_run_button.clicked.connect(
            self._display_matrix_entry
        )
        self.home_screen_page.saved_runs_button.clicked.connect(
            self._display_saved_runs_page
        )

        self.setCentralWidget(self.home_screen_page)

    def _display_saved_runs_page(self):
        self.saved_runs_page = SavedRunsPage(
            self.data_run_model.get_previous_runs(),
            self._saved_runs_page_on_display_button_clicked,
        )

        self.setCentralWidget(self.saved_runs_page)

    def _display_display_stats_page(
        self, matrices: List[DisplayData] = None, run_data: RunData = None
    ):
        self.display_stats_page = DisplayStatsPage(matrices=matrices, run_data=run_data)

        self.display_stats_page.save_button.clicked.connect(
            lambda state, x=self.data_run_model.save_run: self.display_stats_page.save_display(
                x
            )
        )
        self.display_stats_page.calculate_new_stats_button.clicked.connect(
            self._display_matrix_entry
        )

        self.setCentralWidget(self.display_stats_page)

    # Passing Data Across Central Widgets Functions

    def _saved_runs_page_on_display_button_clicked(self, saved_run_name: str):
        try:
            run_data = self.data_run_model.load_run(saved_run_name)
            self._display_display_stats_page(run_data=run_data)
        except InternalDbError as fm:
            msg = QMessageBox()
            self.x = msg
            self.x.setText("ERROR: Run not saved: " + str(fm))
            self.x.exec_()
        except Exception as e:
            msg = QMessageBox()
            self.x = msg
            self.x.setText("ERROR: Run not saved: " + str(e))
            self.x.exec_()

    def _matrix_entry_page_on_submit_matrices_button_clicked(self):
        dd, err = self.matrix_entry_page.calculate_matrix()
        if err is not None:
            pass
        else:
            self._display_display_stats_page(matrices=dd)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())


# January 28th code, going to be working on Data Structures practices & Implementations

# Q2, implementing stack

# part 1: Linked List & array-based list

# Linked List implementation (implement through class)

# Linked List looks like: [A, B] --> [B, C] --> [C, NULL]

# composed of 1) head and tail, the head is being pointed to, tail contains data (in DLL tail is prev elem)

# Advantage of LL, Dynamic size and Easy Insertion/deletion

# Disadvantages of LL, No random access allowed, extra memory space for pointer required w/ each element in list, not cache friendly

class Node:
    #each node contains data and a pointer to the next part of the list
    def __init__(self, data):
        self.data = data # data definition
        self.next = None # point to next datapoint

        # constructor in this case can be thought of as assigning default values for variables not included in object calls

class LinkedList:
    def __init__(self):
        self.head = None # defining what the head looks like. At each point, head is null

    def show(self):
        # function to print out linked list
        temp = self.head # current value
        while (temp): #while current value
            print(temp.data, end = " ") # print data
            temp = temp.next # go to next

if __name__ == "__main__":

    # classic array implementation
    print("array based implementation")
    array = [1, 2, 3, 4]
    print(array)
    array.append(5)
    print(array)
    array.remove(5)
    print(array)

    lList = LinkedList() # define linked list
    lList.head = Node(1) # LL sets default head to none, so if we are actually implemnting LL, must define head
    item2 = Node(2) # define second node
    item3 = Node(3) # define item three

    # Currently we have:  [1, NONE] --> [2, NONE] --> [3, NONE]

    # we want: [1, 2] --> [2, 3] --> [3, NONE]

    # Link the list together

    lList.head.next =  item2 # remember that next points to next data type, so we define it as such. Link item 1 and 2

    item2.next = item3 # Link Item 2 and 3

    print("Linked List traversal")
    lList.show()


from pythonds.basic.stack import Stack

def divideBy2(num):
    st = Stack()

    while num > 0:
        rem = num % 2
        st.push(rem)
        num = num //2

    binStr = ""

    while not st.isEmpty():
        binStr += str(st.pop())

    return binStr

print(divideBy2(23))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from detectron.core.config import cfg
from detectron.utils.c2 import const_fill
from detectron.utils.c2 import gauss_fill
from detectron.utils.net import get_group_gn
import detectron.utils.blob as blob_utils

# ---------------------------------------------------------------------------- #
# Fast R-CNN outputs and losses
# ---------------------------------------------------------------------------- #

def add_fast_rcnn_outputs(model, blob_in, dim):
    """Add RoI classification and bounding box regression output ops."""
    # Box classification layer
    model.FC(
        blob_in,
        'cls_score',
        dim,
        model.num_classes,
        weight_init=gauss_fill(0.01),
        bias_init=const_fill(0.0)
    )
    if not model.train:  # == if test
        # Only add softmax when testing; during training the softmax is combined
        # with the label cross entropy loss for numerical stability
        model.Softmax('cls_score', 'cls_prob', engine='CUDNN')
    # Box regression layer
    num_bbox_reg_classes = (
        2 if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG else model.num_classes
    )
    model.FC(
        blob_in,
        'bbox_pred',
        dim,
        num_bbox_reg_classes * 4,
        weight_init=gauss_fill(0.001),
        bias_init=const_fill(0.0)
    )

def add_fast_rcnn_losses(model):
    """Add losses for RoI classification and bounding box regression."""
    cls_prob, loss_cls = model.net.SoftmaxWithLoss(
        ['cls_score', 'labels_int32'], ['cls_prob', 'loss_cls'],
        scale=model.GetLossScale()
    )
    loss_bbox = model.net.SmoothL1Loss(
        [
            'bbox_pred', 'bbox_targets', 'bbox_inside_weights',
            'bbox_outside_weights'
        ],
        'loss_bbox',
        scale=model.GetLossScale()
    )
    loss_gradients = blob_utils.get_loss_gradients(model, [loss_cls, loss_bbox])
    model.Accuracy(['cls_prob', 'labels_int32'], 'accuracy_cls')
    model.AddLosses(['loss_cls', 'loss_bbox'])
    model.AddMetrics('accuracy_cls')
    return loss_gradients

# ---------------------------------------------------------------------------- #
# Box heads
# ---------------------------------------------------------------------------- #

def add_roi_2mlp_head(model, blob_in, dim_in, spatial_scale):
    """Add a ReLU MLP with two hidden layers."""
    hidden_dim = cfg.FAST_RCNN.MLP_HEAD_DIM
    roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION
    roi_feat = model.RoIFeatureTransform(
        blob_in,
        'roi_feat',
        blob_rois='rois',
        method=cfg.FAST_RCNN.ROI_XFORM_METHOD,
        resolution=roi_size,
        sampling_ratio=cfg.FAST_RCNN.ROI_XFORM_SAMPLING_RATIO,
        spatial_scale=spatial_scale
    )
    model.FC(roi_feat, 'fc6', dim_in * roi_size * roi_size, hidden_dim)
    model.Relu('fc6', 'fc6')
    model.FC('fc6', 'fc7', hidden_dim, hidden_dim)
    model.Relu('fc7', 'fc7')
    return 'fc7', hidden_dim

def add_roi_Xconv1fc_head(model, blob_in, dim_in, spatial_scale):
    """Add a X conv + 1fc head, as a reference if not using GroupNorm"""
    hidden_dim = cfg.FAST_RCNN.CONV_HEAD_DIM
    roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION
    roi_feat = model.RoIFeatureTransform(
        blob_in,
        'roi_feat',
        blob_rois='rois',
        method=cfg.FAST_RCNN.ROI_XFORM_METHOD,
        resolution=roi_size,
        sampling_ratio=cfg.FAST_RCNN.ROI_XFORM_SAMPLING_RATIO,
        spatial_scale=spatial_scale
    )

    current = roi_feat
    for i in range(cfg.FAST_RCNN.NUM_STACKED_CONVS):
        current = model.Conv(
            current, 'head_conv' + str(i + 1), dim_in, hidden_dim, 3,
            stride=1, pad=1,
            weight_init=('MSRAFill', {}),
            bias_init=('ConstantFill', {'value': 0.}),
            no_bias=0)
        current = model.Relu(current, current)
        dim_in = hidden_dim

    fc_dim = cfg.FAST_RCNN.MLP_HEAD_DIM
    model.FC(current, 'fc6', dim_in * roi_size * roi_size, fc_dim)
    model.Relu('fc6', 'fc6')
    return 'fc6', fc_dim

def add_roi_Xconv1fc_gn_head(model, blob_in, dim_in, spatial_scale):
    """Add a X conv + 1fc head, with GroupNorm"""
    hidden_dim = cfg.FAST_RCNN.CONV_HEAD_DIM
    roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION
    roi_feat = model.RoIFeatureTransform(
        blob_in, 'roi_feat',
        blob_rois='rois',
        method=cfg.FAST_RCNN.ROI_XFORM_METHOD,
        resolution=roi_size,
        sampling_ratio=cfg.FAST_RCNN.ROI_XFORM_SAMPLING_RATIO,
        spatial_scale=spatial_scale
    )

    current = roi_feat
    for i in range(cfg.FAST_RCNN.NUM_STACKED_CONVS):
        current = model.ConvGN(
            current, 'head_conv' + str(i + 1), dim_in, hidden_dim, 3,
            group_gn=get_group_gn(hidden_dim),
            stride=1, pad=1,
            weight_init=('MSRAFill', {}),
            bias_init=('ConstantFill', {'value': 0.}))
        current = model.Relu(current, current)
        dim_in = hidden_dim

    fc_dim = cfg.FAST_RCNN.MLP_HEAD_DIM
    model.FC(current, 'fc6', dim_in * roi_size * roi_size, fc_dim)
    model.Relu('fc6', 'fc6')
    return 'fc6', fc_dim


def main():
    from collections import Counter

    count = Counter()

    count.update('ABCDEFGHIABCDEF')

    print('%s:%d'%('A',count['A']))

    print('\n')

    for char in 'ABCDEFABCDE':
        print('%s:%d'%(char,count[char]))

if __name__ == '__main__':
    main()


import logging
from abc import ABCMeta, abstractmethod

from .process_nodes import (
    AccessCustomTemplate,
    AccessNode,
    AuthProjectDataNode,
    CleanNode,
    CleanTemplate,
    DataModelInstNode,
    DataModelNode,
    IgniteStorageNode,
    IgniteStorageTemplate,
    SimpleTemplate,
)

logger = logging.getLogger()

class BaseProcessor(metaclass=ABCMeta):
    """
    数据处理基类
    """

    @abstractmethod
    def build(self):
        """
        构建数据处理流程
        """
        pass

class BKDFlowProcessor(BaseProcessor):

    """
    数据平台数据流构建流程，可以按需注册处理节点和参数模型，比如

    - 1. 数据接入节点
    - 2. 数据清洗节点
    - 3. 数据计算节点
            - 3.1 DataFlow 计算节点
            - 3.2 数据模型计算节点
    """

    mapping_process_node = dict()
    mapping_process_template = dict()

    @classmethod
    def regiter_process_node(cls, node):
        cls.mapping_process_node[node.__name__] = node

    @classmethod
    def regiter_process_template(cls, template):
        cls.mapping_process_template[template.__name__] = template

    def __init__(self, pipeline: list):
        self.pipeline = pipeline

    def build(self):
        node_output = dict()

        for index, node in enumerate(self.pipeline):
            logger.info(f"[BKDFlowProcessor] Start to process node({node})")

            process_node = self.mapping_process_node[node["process_node"]]
            process_template = self.mapping_process_template[node["process_template"]]
            process_context = self.handle_node_context(
                node["process_context"], node_output
            )

            logger.info(
                f"[BKDFlowProcessor] Using {process_node} & {process_template} & {process_context} "
            )

            params_template = process_template(process_context)
            node = process_node(params_template)

            logger.info(f"[BKDFlowProcessor] Build node({node})")
            node_output[f"${index}"] = node.build()
            logger.info(f"[BKDFlowProcessor] Succeed to build node({node})")

    def handle_node_context(self, node_context, node_output):
        """
        处理节点上下文，主要是解决部分后置节点依赖前置节点，主要是替换形如 $0.raw_data_id 等占位符
        """
        for k, v in node_context.items():
            if type(v) is str and v.startswith("$"):
                node_output_index = v.split(".")[0]
                node_output_attr = v.split(".")[1]

                node_context[k] = node_output[node_output_index][node_output_attr]
        return node_context

BKDFlowProcessor.regiter_process_node(AccessNode)
BKDFlowProcessor.regiter_process_node(CleanNode)
BKDFlowProcessor.regiter_process_node(IgniteStorageNode)
BKDFlowProcessor.regiter_process_node(DataModelNode)
BKDFlowProcessor.regiter_process_node(DataModelInstNode)
BKDFlowProcessor.regiter_process_node(AuthProjectDataNode)
BKDFlowProcessor.regiter_process_template(AccessCustomTemplate)
BKDFlowProcessor.regiter_process_template(CleanTemplate)
BKDFlowProcessor.regiter_process_template(IgniteStorageTemplate)
BKDFlowProcessor.regiter_process_template(SimpleTemplate)


import csv

def getLocationsAndTravelTimesFromCsv():
    with open("..\\inputFiles\\" + "travelTimes.csv") as csvfile:
        data = list(csv.reader(csvfile))

    locationList = data[0][1:]

    travelTimes = {}
    for i,fromLoc in enumerate(locationList):
        for j, toLoc in enumerate(locationList):
            if data[j+1][i+1].isdigit() and i+1 != j+1:
                travelTimes[(fromLoc, toLoc)] = int(data[j+1][i+1])

    return locationList, travelTimes

def printToConsole(decisionVar, locationList):

    fromLoc = locationList[0]
    visited = []

    while True:

        for toLoc in locationList:

            if fromLoc != toLoc and toLoc not in visited:
                if decisionVar[fromLoc][toLoc].value() > 0.5:
                    print("Travel from " + str(fromLoc) + " to " + str(toLoc))
                    break

        if len(visited) == len(locationList) - 1:
            assert decisionVar[fromLoc][locationList[0]].value() > 0.5, "Error in logic/optimization"
            print("Travel from " + str(fromLoc) + " to " + str(locationList[0]))
            break

        visited.append(fromLoc)
        fromLoc = toLoc

    print()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 18:35:42 2021

@author: ml
"""

from code.feature_extraction.number_of_words import NumberOfWords
import pandas as pd
import unittest

class NumberOfWordsTest(unittest.TestCase):

    def setUp(self):
        self.INPUT_COLUMN = "input"
        self.number_of_words_extractor = NumberOfWords(self.INPUT_COLUMN)

    def test_amount_of_words_correct(self):
        """
        check if the amount of words is correctly counted

        Returns
        -------
        None.

        """
        #arrange
        input_texts = ["['First','Second','Third','Fourth']",
                       "[]"]
        expected_outputs = [4,0]

        df = pd.DataFrame()

        for input_text, expected_output in zip(input_texts, expected_outputs):
            df[self.INPUT_COLUMN] = [input_text]
            #act
            output=self.number_of_words_extractor.fit_transform(df)

            #assert
            self.assertEqual(output[0][0], expected_output)

if __name__ == '__main__':
    print("__[RUNNING: test.feature_extraction.test_number_of_words]__")
    unittest.main()


from django.contrib.auth.models import Permission

from tests.apps.signals.factories import CategoryFactory, StatusMessageTemplateFactory
from tests.test import SIAReadWriteUserMixin, SignalsBaseApiTestCase

class TestPrivateCategoryStatusMessages(SIAReadWriteUserMixin, SignalsBaseApiTestCase):
    link_cat_sub_templates = None

    def setUp(self):
        statusmessagetemplate_write_permission = Permission.objects.get(
            codename='sia_statusmessagetemplate_write'
        )
        self.sia_read_write_user.user_permissions.add(statusmessagetemplate_write_permission)
        self.sia_read_write_user.save()
        self.client.force_authenticate(user=self.sia_read_write_user)

        self.subcategory = CategoryFactory.create()
        self.link_cat_sub_templates = '/signals/v1/private/terms/categories/{}/sub_categories/{}/status-message-templates'.format(  # noqa
            self.subcategory.parent.slug, self.subcategory.slug
        )

        self.link_cat_parent_templates = '/signals/v1/private/terms/categories/{}/status-message-templates'.format(  # noqa
            self.subcategory.parent.slug
        )

    def test_get_no_status_message_templates(self):
        response = self.client.get(self.link_cat_sub_templates)

        self.assertEqual(200, response.status_code)
        self.assertEqual(0, len(response.json()))

    def test_get_status_message_templates(self):
        templates = StatusMessageTemplateFactory.create_batch(
            5,
            category=self.subcategory,
            state='m'
        )

        response = self.client.get(self.link_cat_sub_templates)
        self.assertEqual(200, response.status_code)

        response_json = response.json()
        self.assertEqual(1, len(response_json))
        self.assertEqual(len(templates), len(response_json[0]['templates']))

    def test_add_status_messages(self):
        response = self.client.get(self.link_cat_sub_templates)
        self.assertEqual(200, response.status_code)
        self.assertEqual(0, len(response.json()))

        data = [
            {
                'state': 'm',
                'templates': [
                    {
                        'title': 'M Title #1',
                        'text': 'M Text #1',
                    },
                    {
                        'title': 'M Title #2',
                        'text': 'M Text #2',
                    },
                ],
            },
            {
                'state': 'o',
                'templates': [
                    {
                        'title': 'O Title #1',
                        'text': 'O Text #1',
                    },
                ],
            },
        ]
        response = self.client.post(self.link_cat_sub_templates, data, format='json')
        self.assertEqual(200, response.status_code)

        response_data = response.json()
        self.assertEqual(2, len(response_data))

        self.assertEqual('m', response_data[0]['state'])
        self.assertEqual(2, len(response_data[0]['templates']))
        self.assertEqual('M Title #1', response_data[0]['templates'][0]['title'])
        self.assertEqual('M Text #1', response_data[0]['templates'][0]['text'])
        self.assertEqual('M Title #2', response_data[0]['templates'][1]['title'])
        self.assertEqual('M Text #2', response_data[0]['templates'][1]['text'])

        self.assertEqual('o', response_data[1]['state'])
        self.assertEqual(1, len(response_data[1]['templates']))
        self.assertEqual('O Title #1', response_data[1]['templates'][0]['title'])
        self.assertEqual('O Text #1', response_data[1]['templates'][0]['text'])

    def test_delete_status_messages(self):
        StatusMessageTemplateFactory.create(order=0, category=self.subcategory, state='o')
        StatusMessageTemplateFactory.create(order=0, category=self.subcategory, state='m')
        StatusMessageTemplateFactory.create(order=1, category=self.subcategory, state='m')

        response = self.client.get(self.link_cat_sub_templates)
        self.assertEqual(200, response.status_code)

        response_data = response.json()
        self.assertEqual(2, len(response_data))
        self.assertEqual(2, len(response_data[0]['templates']))
        self.assertEqual(1, len(response_data[1]['templates']))

        data = [
            {
                'state': 'm',
                'templates': [],
            },
        ]

        response = self.client.post(self.link_cat_sub_templates, data, format='json')
        self.assertEqual(200, response.status_code)

        response_data = response.json()
        self.assertEqual(1, len(response_data))
        self.assertEqual('o', response_data[0]['state'])
        self.assertEqual(1, len(response_data[0]['templates']))

    def test_get_no_status_message_templates_parent(self):
        response = self.client.get(self.link_cat_parent_templates)

        self.assertEqual(200, response.status_code)
        self.assertEqual(0, len(response.json()))

    def test_get_status_message_templates_parent(self):
        templates = StatusMessageTemplateFactory.create_batch(
            5,
            category=self.subcategory.parent,
            state='m'
        )

        response = self.client.get(self.link_cat_parent_templates)
        self.assertEqual(200, response.status_code)

        response_json = response.json()
        self.assertEqual(1, len(response_json))
        self.assertEqual(len(templates), len(response_json[0]['templates']))


'''
get follower
'''
import json
import sys

import requests_oauthlib
import yaml

def load_yaml(filepath):
    with open(filepath) as f:
        data = yaml.load(f)
    return data

def get_user_info(twitter, user_id):
    url = 'https://api.twitter.com/1.1/users/show.json'
    params = {'user_id': user_id}
    return twitter.get(url, params=params)

def show_info(user):
    print(f'name       : {user.get("name")}')
    print(f'screen_name: {user.get("screen_name")}')
    print(f'followers  : {user.get("followers_count")}')
    print(f'following  : {user.get("friends_count")}')
    print('')

def main():
    filepath = '/Users/wararaki/.twitter/credential.yaml'
    credentials = load_yaml(filepath)

    # oauth
    twitter = requests_oauthlib.OAuth1Session(**credentials)

    # get timeline
    url = "https://api.twitter.com/1.1/followers/ids.json"
    params ={'count' : 5, 'user_id': 'twitterjp'}
    response = twitter.get(url, params=params)

    data = response.json()
    for follower_id in data['ids']:
        response = get_user_info(twitter, follower_id)
        show_info(response.json())
    print("DONE")

    return 0

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