#!/usr/bin/env python3

######################## IMPORT MODULES ##########################

import numpy as np				# If you find it required
import rospy
from sensor_msgs.msg import Image 	# Image is the message type for images in ROS
from cv_bridge import CvBridge	# Package to convert between ROS and OpenCV Images
import cv2
import cv2.aruco as aruco				# OpenCV Library
from cmath import atan # If you find it required
from geometry_msgs.msg import Pose2D	# Required to publish ARUCO's detected position & orientation

############################ GLOBALS #############################

aruco_publisher = rospy.Publisher('detected_aruco', Pose2D)
pi = 3.14
marker_coords = np.array([[0, 0], [500, 0], [500, 500], [0, 500]], dtype=np.float32)

##################### FUNCTION DEFINITIONS #######################

# NOTE :  You may define multiple helper functions here and use in your code
def pose(corners,ids):
	aruco_msg = Pose2D()
	bot = corners[np.where(ids == 15)[0][0]][0]
	x_axis = (bot[1][0]-bot[0][0])
	y_axis = (bot[0][1]-bot[1][1])
	angle = atan(y_axis/x_axis)
	if x_axis<0:
		if y_axis >0:
			angle += pi
		elif y_axis  <0:
			angle -= pi
	aruco_msg.x =(bot[0][0]+bot[1][0]+bot[2][0]+bot[3][0])*0.25
	aruco_msg.y =(bot[0][1]+bot[1][1]+bot[2][1]+bot[3][1])*0.25
	aruco_msg.theta = angle.real
	return aruco_msg

def crop(corners,ids,current_frame):

	marker_coords_detected = []
	marker_coords_detected.append(corners[np.where(ids == 4)[0][0]][0][3])
	marker_coords_detected.append(corners[np.where(ids == 8)[0][0]][0][0])
	marker_coords_detected.append(corners[np.where(ids == 10)[0][0]][0][1])
	marker_coords_detected.append(corners[np.where(ids == 12)[0][0]][0][2])
	marker_coords_detected = np.array(marker_coords_detected, dtype=np.float32)
	M = cv2.getPerspectiveTransform(marker_coords_detected, marker_coords)
	img_proj = cv2.warpPerspective(current_frame, M, (500, 500))
	return img_proj

def callback(data):
	# Bridge is Used to Convert ROS Image message to OpenCV image
	br = CvBridge()
	# rospy.loginfo("receiving camera frame")
	current_frame 		= br.imgmsg_to_cv2(data, "mono8")		# Receiving raw image in a "grayscale" format
	# current_frame 	= cv2.resize(get_frame, (500, 500), interpolation = cv2.INTER_LINEAR)
	aruco_dict		= aruco.Dictionary_get(aruco.DICT_4X4_50)
	arucoParameters = aruco.DetectorParameters_create()

	corners, ids, _ = aruco.detectMarkers(current_frame , aruco_dict, parameters=arucoParameters)

	if ids is not None:
		# corners=corners
		new_frame = crop(corners,ids,current_frame)
		arucoParameters.errorCorrectionRate = 1
		arucoParameters.adaptiveThreshConstant = 10
		corners, ids, _ = aruco.detectMarkers(new_frame , aruco_dict, parameters=arucoParameters)
		# print(ids)
		# if _ is not None:
		# 	print(_[1])

		aruco_msg = pose(corners,ids)
		length = f"{aruco_msg.x}, {aruco_msg.y}"
		cv2.putText(new_frame,length, (20,40), cv2.FONT_HERSHEY_SIMPLEX,0.5,(255, 255, 255),2)
		length = f"{aruco_msg.theta}"
		cv2.putText(new_frame,length, (20,60), cv2.FONT_HERSHEY_SIMPLEX,0.5,(255, 255, 255),2)
		image = aruco.drawDetectedMarkers(new_frame,corners,ids)
		cv2.imshow('Display',image)
		cv2.waitKey(1)
	else:
		print("Aruco markers not detected in image.")

def main():
	rospy.init_node('aruco_feedback_node')
	rospy.Subscriber('usb_cam/image_rect', Image, callback)
	rospy.spin()

if __name__ == '__main__':
  main()

Real Time Version 1/Trail/seperate nodes/feedback.py


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division

import logging
import random
import time

from collections import defaultdict
from itertools import cycle

import blinker
import gevent

from gevent.event import Event
from gevent.pool import Group

from .backofftimer import BackoffTimer
from .decorators import cached_property
from .errors import NSQException, NSQRequeueMessage, NSQSocketError
from .nsqd import NsqdTCPClient
from .states import INIT, RUNNING, BACKOFF, THROTTLED, CLOSED
from .util import parse_nsqds, parse_lookupds

class Consumer(object):
    """High level NSQ consumer.

    A Consumer will connect to the nsqd tcp addresses or poll the provided
    nsqlookupd http addresses for the configured topic and send signals to
    message handlers connected to the :attr:`on_message` signal or provided by
    ``message_handler``.

    Messages will automatically be finished when the message handle returns
    unless :meth:`message.enable_async() <gnsq.Message.enable_async>` is called.
    If an exception occurs or :class:`~gnsq.errors.NSQRequeueMessage` is raised,
    the message will be requeued.

    The Consumer will handle backing off of failed messages up to a configurable
    ``max_interval`` as well as automatically reconnecting to dropped
    connections.

    Example usage::

        from gnsq import Consumer

        consumer = gnsq.Consumer('topic', 'channel', 'localhost:4150')

        @consumer.on_message.connect
        def handler(consumer, message):
            print 'got message:', message.body

        consumer.start()

    :param topic: specifies the desired NSQ topic

    :param channel: specifies the desired NSQ channel

    :param nsqd_tcp_addresses: a sequence of string addresses of the nsqd
        instances this consumer should connect to

    :param lookupd_http_addresses: a sequence of string addresses of the
        nsqlookupd instances this consumer should query for producers of the
        specified topic

    :param name: a string that is used for logging messages (defaults to
        ``'gnsq.consumer.{topic}.{channel}'``)

    :param message_handler: the callable that will be executed for each message
        received

    :param max_tries: the maximum number of attempts the consumer will make to
        process a message after which messages will be automatically discarded

    :param max_in_flight: the maximum number of messages this consumer will
        pipeline for processing. this value will be divided evenly amongst the
        configured/discovered nsqd producers

    :param requeue_delay: the default delay to use when requeueing a failed
        message

    :param lookupd_poll_interval: the amount of time in seconds between querying
        all of the supplied nsqlookupd instances.  A random amount of time based
        on this value will be initially introduced in order to add jitter when
        multiple consumers are running

    :param lookupd_poll_jitter: the maximum fractional amount of jitter to add
        to the lookupd poll loop. This helps evenly distribute requests even if
        multiple consumers restart at the same time.

    :param low_ready_idle_timeout: the amount of time in seconds to wait for a
        message from a producer when in a state where RDY counts are
        re-distributed (ie. `max_in_flight` < `num_producers`)

    :param max_backoff_duration: the maximum time we will allow a backoff state
        to last in seconds. If zero, backoff wil not occur

    :param backoff_on_requeue: if ``False``, backoff will only occur on
        exception

    :param **kwargs: passed to :class:`~gnsq.NsqdTCPClient` initialization
    """
    def __init__(self, topic, channel, nsqd_tcp_addresses=[],
                 lookupd_http_addresses=[], name=None, message_handler=None,
                 max_tries=5, max_in_flight=1, requeue_delay=0,
                 lookupd_poll_interval=60, lookupd_poll_jitter=0.3,
                 low_ready_idle_timeout=10, max_backoff_duration=128,
                 backoff_on_requeue=True, **kwargs):
        if not nsqd_tcp_addresses and not lookupd_http_addresses:
            raise ValueError('must specify at least one nsqd or lookupd')

        self.nsqd_tcp_addresses = parse_nsqds(nsqd_tcp_addresses)
        self.lookupds = parse_lookupds(lookupd_http_addresses)
        self.iterlookupds = cycle(self.lookupds)

        self.topic = topic
        self.channel = channel
        self.max_tries = max_tries
        self.max_in_flight = max_in_flight
        self.requeue_delay = requeue_delay
        self.lookupd_poll_interval = lookupd_poll_interval
        self.lookupd_poll_jitter = lookupd_poll_jitter
        self.low_ready_idle_timeout = low_ready_idle_timeout
        self.backoff_on_requeue = backoff_on_requeue
        self.max_backoff_duration = max_backoff_duration
        self.conn_kwargs = kwargs

        if name:
            self.name = name
        else:
            self.name = '%s.%s.%s' % (__name__, self.topic, self.channel)

        if message_handler is not None:
            self.on_message.connect(message_handler, weak=False)

        self.logger = logging.getLogger(self.name)

        self._state = INIT
        self._redistributed_ready_event = Event()
        self._connection_backoffs = defaultdict(self._create_backoff)
        self._message_backoffs = defaultdict(self._create_backoff)

        self._connections = {}
        self._workers = Group()
        self._killables = Group()

    @cached_property
    def on_message(self):
        """Emitted when a message is received.

        The signal sender is the consumer and the ``message`` is sent as an
        argument. The ``message_handler`` param is connected to this signal.
        """
        return blinker.Signal(doc='Emitted when a message is received.')

    @cached_property
    def on_response(self):
        """Emitted when a response is received.

        The signal sender is the consumer and the ``response`` is sent as an
        argument.
        """
        return blinker.Signal(doc='Emitted when a response is received.')

    @cached_property
    def on_error(self):
        """Emitted when an error is received.

        The signal sender is the consumer and the ``error`` is sent as an
        argument.
        """
        return blinker.Signal(doc='Emitted when a error is received.')

    @cached_property
    def on_finish(self):
        """Emitted after a message is successfully finished.

        The signal sender is the consumer and the ``message_id`` is sent as an
        argument.
        """
        return blinker.Signal(doc='Emitted after the a message is finished.')

    @cached_property
    def on_requeue(self):
        """Emitted after a message is requeued.

        The signal sender is the consumer and the ``message_id`` and ``timeout``
        are sent as arguments.
        """
        return blinker.Signal(doc='Emitted after the a message is requeued.')

    @cached_property
    def on_giving_up(self):
        """Emitted after a giving up on a message.

        Emitted when a message has exceeded the maximum number of attempts
        (``max_tries``) and will no longer be requeued. This is useful to
        perform tasks such as writing to disk, collecting statistics etc. The
        signal sender is the consumer and the ``message`` is sent as an
        argument.
        """
        return blinker.Signal(doc='Sent after a giving up on a message.')

    @cached_property
    def on_auth(self):
        """Emitted after a connection is successfully authenticated.

        The signal sender is the consumer and the ``conn`` and parsed
        ``response`` are sent as arguments.
        """
        return blinker.Signal(doc='Emitted when a response is received.')

    @cached_property
    def on_exception(self):
        """Emitted when an exception is caught while handling a message.

        The signal sender is the consumer and the ``message`` and ``error`` are
        sent as arguments.
        """
        return blinker.Signal(doc='Emitted when an exception is caught.')

    @cached_property
    def on_close(self):
        """Emitted after :meth:`close`.

        The signal sender is the consumer.
        """
        return blinker.Signal(doc='Emitted after the consumer is closed.')

    def start(self, block=True):
        """Start discovering and listing to connections."""
        if self._state == INIT:
            if not any(self.on_message.receivers_for(blinker.ANY)):
                raise RuntimeError('no receivers connected to on_message')

            self.logger.debug('starting %s...', self.name)
            self._state = RUNNING
            self.query_nsqd()

            if self.lookupds:
                self.query_lookupd()
                self._killables.add(self._workers.spawn(self._poll_lookupd))

            self._killables.add(self._workers.spawn(self._poll_ready))

        else:
            self.logger.warning('%s already started', self.name)

        if block:
            self.join()

    def close(self):
        """Immediately close all connections and stop workers."""
        if not self.is_running:
            return

        self._state = CLOSED

        self.logger.debug('killing %d worker(s)', len(self._killables))
        self._killables.kill(block=False)

        self.logger.debug('closing %d connection(s)', len(self._connections))
        for conn in self._connections:
            conn.close_stream()

        self.on_close.send(self)

    def join(self, timeout=None, raise_error=False):
        """Block until all connections have closed and workers stopped."""
        self._workers.join(timeout, raise_error)

    @property
    def is_running(self):
        """Check if consumer is currently running."""
        return self._state == RUNNING

    @property
    def is_starved(self):
        """Evaluate whether any of the connections are starved.

        This property should be used by message handlers to reliably identify
        when to process a batch of messages.
        """
        return any(conn.is_starved for conn in self._connections)

    @property
    def total_ready_count(self):
        return sum(c.ready_count for c in self._connections)

    @property
    def total_in_flight(self):
        return sum(c.in_flight for c in self._connections)

    def query_nsqd(self):
        self.logger.debug('querying nsqd...')
        for address in self.nsqd_tcp_addresses:
            address, port = address.split(':')
            self.connect_to_nsqd(address, int(port))

    def query_lookupd(self):
        self.logger.debug('querying lookupd...')
        lookupd = next(self.iterlookupds)

        try:
            producers = lookupd.lookup(self.topic)['producers']
            self.logger.debug('found %d producers', len(producers))

        except Exception as error:
            self.logger.warning(
                'Failed to lookup %s on %s (%s)',
                self.topic, lookupd.address, error)
            return

        for producer in producers:
            self.connect_to_nsqd(
                producer['broadcast_address'], producer['tcp_port'])

    def _poll_lookupd(self):
        try:
            delay = self.lookupd_poll_interval * self.lookupd_poll_jitter
            gevent.sleep(random.random() * delay)

            while True:
                gevent.sleep(self.lookupd_poll_interval)
                self.query_lookupd()

        except gevent.GreenletExit:
            pass

    def _poll_ready(self):
        try:
            while True:
                if self._redistributed_ready_event.wait(5):
                    self._redistributed_ready_event.clear()
                self._redistribute_ready_state()

        except gevent.GreenletExit:
            pass

    def _redistribute_ready_state(self):
        if not self.is_running:
            return

        if len(self._connections) > self.max_in_flight:
            ready_state = self._get_unsaturated_ready_state()
        else:
            ready_state = self._get_saturated_ready_state()

        for conn, count in ready_state.items():
            if conn.ready_count == count:
                self.logger.debug('[%s] RDY count already %d', conn, count)
                continue

            self.logger.debug('[%s] sending RDY %d', conn, count)

            try:
                conn.ready(count)
            except NSQSocketError as error:
                self.logger.warning(
                    '[%s] RDY %d failed (%r)', conn, count, error)

    def _get_unsaturated_ready_state(self):
        ready_state = {}
        active = []

        for conn, state in self._connections.items():
            if state == BACKOFF:
                ready_state[conn] = 0

            elif state in (RUNNING, THROTTLED):
                active.append(conn)

        random.shuffle(active)

        for conn in active[self.max_in_flight:]:
            ready_state[conn] = 0

        for conn in active[:self.max_in_flight]:
            ready_state[conn] = 1

        return ready_state

    def _get_saturated_ready_state(self):
        ready_state = {}
        active = []
        now = time.time()

        for conn, state in self._connections.items():
            if state == BACKOFF:
                ready_state[conn] = 0

            elif state == THROTTLED:
                ready_state[conn] = 1

            elif state == RUNNING:
                if (now - conn.last_message) > self.low_ready_idle_timeout:
                    self.logger.info(
                        '[%s] idle connection, giving up RDY count', conn)
                    ready_state[conn] = 1

                else:
                    active.append(conn)

        if not active:
            return ready_state

        ready_available = self.max_in_flight - sum(ready_state.values())
        connection_max_in_flight = ready_available // len(active)

        for conn in active:
            ready_state[conn] = connection_max_in_flight

        for conn in random.sample(active, ready_available % len(active)):
            ready_state[conn] += 1

        return ready_state

    def redistribute_ready_state(self):
        self._redistributed_ready_event.set()

    def connect_to_nsqd(self, address, port):
        if not self.is_running:
            return

        conn = NsqdTCPClient(address, port, **self.conn_kwargs)
        if conn in self._connections:
            self.logger.debug('[%s] already connected', conn)
            return

        self._connections[conn] = INIT
        self.logger.debug('[%s] connecting...', conn)

        conn.on_message.connect(self.handle_message)
        conn.on_response.connect(self.handle_response)
        conn.on_error.connect(self.handle_error)
        conn.on_finish.connect(self.handle_finish)
        conn.on_requeue.connect(self.handle_requeue)
        conn.on_auth.connect(self.handle_auth)

        try:
            conn.connect()
            conn.identify()

            if conn.max_ready_count < self.max_in_flight:
                msg = (
                    '[%s] max RDY count %d < consumer max in flight %d, '
                    'truncation possible')

                self.logger.warning(
                    msg, conn, conn.max_ready_count, self.max_in_flight)

            conn.subscribe(self.topic, self.channel)

        except NSQException as error:
            self.logger.warning('[%s] connection failed (%r)', conn, error)
            self.handle_connection_failure(conn)
            return

        # Check if we've closed since we started
        if not self.is_running:
            self.handle_connection_failure(conn)
            return

        self.logger.info('[%s] connection successful', conn)
        self.handle_connection_success(conn)

    def _listen(self, conn):
        try:
            conn.listen()
        except NSQException as error:
            self.logger.warning('[%s] connection lost (%r)', conn, error)

        self.handle_connection_failure(conn)

    def handle_connection_success(self, conn):
        self._connections[conn] = THROTTLED
        self._workers.spawn(self._listen, conn)
        self.redistribute_ready_state()

        if str(conn) not in self.nsqd_tcp_addresses:
            return

        self._connection_backoffs[conn].success()

    def handle_connection_failure(self, conn):
        del self._connections[conn]
        conn.close_stream()

        if not self.is_running:
            return

        self.redistribute_ready_state()

        if str(conn) not in self.nsqd_tcp_addresses:
            return

        seconds = self._connection_backoffs[conn].failure().get_interval()
        self.logger.debug('[%s] retrying in %ss', conn, seconds)

        gevent.spawn_later(
            seconds, self.connect_to_nsqd, conn.address, conn.port)

    def handle_auth(self, conn, response):
        metadata = []
        if response.get('identity'):
            metadata.append("Identity: %r" % response['identity'])

        if response.get('permission_count'):
            metadata.append("Permissions: %d" % response['permission_count'])

        if response.get('identity_url'):
            metadata.append(response['identity_url'])

        self.logger.info('[%s] AUTH accepted %s', conn, ' '.join(metadata))
        self.on_auth.send(self, conn=conn, response=response)

    def handle_response(self, conn, response):
        self.logger.debug('[%s] response: %s', conn, response)
        self.on_response.send(self, response=response)

    def handle_error(self, conn, error):
        self.logger.debug('[%s] error: %s', conn, error)
        self.on_error.send(self, error=error)

    def _handle_message(self, message):
        if self.max_tries and message.attempts > self.max_tries:
            self.logger.warning(
                "giving up on message '%s' after max tries %d",
                message.id, self.max_tries)
            self.on_giving_up.send(self, message=message)
            return message.finish()

        self.on_message.send(self, message=message)

        if not self.is_running:
            return

        if message.is_async():
            return

        if message.has_responded():
            return

        message.finish()

    def handle_message(self, conn, message):
        self.logger.debug('[%s] got message: %s', conn, message.id)

        try:
            return self._handle_message(message)

        except NSQRequeueMessage as error:
            if error.backoff is None:
                backoff = self.backoff_on_requeue
            else:
                backoff = error.backoff

        except Exception as error:
            backoff = True
            self.logger.exception(
                '[%s] caught exception while handling message', conn)
            self.on_exception.send(self, message=message, error=error)

        if not self.is_running:
            return

        if message.has_responded():
            return

        try:
            message.requeue(self.requeue_delay, backoff)
        except NSQException as error:
            self.logger.warning(
                '[%s] error requeueing message (%r)', conn, error)

    def _create_backoff(self):
        return BackoffTimer(max_interval=self.max_backoff_duration)

    def _start_backoff(self, conn):
        self._connections[conn] = BACKOFF

        interval = self._message_backoffs[conn].get_interval()
        gevent.spawn_later(interval, self._start_throttled, conn)

        self.logger.info('[%s] backing off for %s seconds', conn, interval)
        self.redistribute_ready_state()

    def _start_throttled(self, conn):
        if self._connections.get(conn) != BACKOFF:
            return

        self._connections[conn] = THROTTLED
        self.logger.info('[%s] testing backoff state with RDY 1', conn)
        self.redistribute_ready_state()

    def _complete_backoff(self, conn):
        if self._message_backoffs[conn].is_reset():
            self._connections[conn] = RUNNING
            self.logger.info('throttle complete, resuming normal operation')
            self.redistribute_ready_state()
        else:
            self._start_backoff(conn)

    def _finish_message(self, conn, backoff):
        if not self.max_backoff_duration:
            return

        try:
            state = self._connections[conn]
        except KeyError:
            return

        if state == BACKOFF:
            return

        if backoff:
            self._message_backoffs[conn].failure()
            self._start_backoff(conn)

        elif state == THROTTLED:
            self._message_backoffs[conn].success()
            self._complete_backoff(conn)

    def handle_finish(self, conn, message_id):
        self.logger.debug('[%s] finished message: %s', conn, message_id)
        self._finish_message(conn, backoff=False)
        self.on_finish.send(self, message_id=message_id)

    def handle_requeue(self, conn, message_id, timeout, backoff):
        self.logger.debug(
            '[%s] requeued message: %s (%s)', conn, message_id, timeout)
        self._finish_message(conn, backoff=backoff)
        self.on_requeue.send(self, message_id=message_id, timeout=timeout)


# coding:utf-8
# --author-- lanhua.zhou
from __future__ import print_function

import logging

import maya.cmds as cmds

import zfused_api

import zfused_maya.core.record as record

from zwidgets.assetwidget import assetmanagewidget

from zfused_maya.ui.widgets import window

import zfused_maya.node.core.attr as attr

__all__ = ["AssetManageWidget"]

logger = logging.getLogger(__name__)

class AssetManageWidget(window._Window):
    def __init__(self, parent = None):
        super(AssetManageWidget, self).__init__()
        self._build()

        self.asset_widget.reference_by_attr.connect(self._reference)

    def _reference(self, version_id, output_attr_id):
        _version = zfused_api.version.Version(version_id)

        # asset type
        _type = _version.project_entity().type()
        _type_code = _type.code()
        _type_code = "{}_group".format(_type_code)
        if not cmds.objExists(_type_code):
            cmds.createNode("transform", name = _type_code)

        _task = _version.task()
        _project_step = _task.project_step()
        _output_attr = zfused_api.attr.Output(output_attr_id)

        _production_file = _version.production_file()
        _production_file = ".".join(_production_file.split(".{:0>4d}.".format(_version.index())))

        _ori_assemblies = cmds.ls(assemblies=True)
        _ns = "{}__ns__00".format(_task.project_entity().file_code())
        rf = cmds.file(_production_file, r = True, ns = _ns)
        rfn = cmds.referenceQuery(rf, rfn = True)
        _new_assemblies = cmds.ls(assemblies=True)
        _asset_tops = list(set(_new_assemblies) - set(_ori_assemblies))
        if _asset_tops:
            for _asset_top in _asset_tops:
                try:
                    cmds.parent(_asset_top, _type_code)
                except:
                    pass

    def _build(self):
        self.resize(1600, 900)
        self.set_title_name(u"资产管理(asset management)")
        self.set_help_url("tool/utility/asset_management")

        self.asset_widget = assetmanagewidget.AssetManageWidget()
        self.set_central_widget(self.asset_widget)

    def showEvent(self, event):
        _project_id = record.current_project_id()
        _company_id = record.current_company_id()
        self.asset_widget.load_project_id(_project_id, _company_id)
        super(AssetManageWidget, self).showEvent(event)


from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter

ori_wb = load_workbook('original.xlsx')
ori_ws = ori_wb.active

rank_wb = Workbook()

branch = 'AA'

rlist = []

for row in range(1, 1367):
  rollno = ori_ws['A' + str(row)].value
  dep = rollno[2:4]
  student = ori_ws['B' + str(row)].value
  cg = float((ori_ws['C' + str(row)].value).split(' ')[0])
  data = [cg, rollno, student]
  if not dep == branch:
    rlist.sort(reverse=True)
    rank_wb.create_sheet(branch)
    thisdep = rank_wb[branch]
    thisdep.append(['Rank', 'Roll No.', 'Name', 'CGPA'])
    for rank in range(1, len(rlist) + 1):
      data = [rank, rlist[rank-1][1], rlist[rank-1][2], rlist[rank-1][0]]
      thisdep.append(data)

    branch = dep
    rlist = []

  record = [cg, rollno, student]
  rlist.append(record)

rank_wb.save('Dep-RankList.xlsx')
print('Done')


from django.db import models

# Create your models here.
from django.urls import reverse

class AuditEntity(models.Model):
    created_on = models.DateTimeField(
        auto_now_add=True,
    )
    updated_on = models.DateTimeField(
        auto_now=True,
    )

    class Meta:
        abstract = True

class Department(AuditEntity):
    name = models.CharField(
        max_length=30,
    )

    def get_absolute_url(self):
        return reverse('department details', kwargs={
            'id': self.id,
        })

class Employee(models.Model):
    WEB_DEVELOPER = 1
    QA = 2
    DEV_OPS = 3

    GOOGLE = 'Google'
    SOFT_UNI = 'Softuni'

    COMPANIES = (
        GOOGLE,
        SOFT_UNI
    )

    first_name = models.CharField(
        max_length=30,
    )
    last_name = models.CharField(
        max_length=30,
        null=True,
        blank=True,
    )
    egn = models.CharField(
        max_length=10,
        unique=True,
        verbose_name='EGN',
    )
    job_title = models.IntegerField(
        choices=(
            (WEB_DEVELOPER, 'Web Developer'),
            (QA, 'QA'),
            (DEV_OPS, 'DevOps'),
        ),
    )

    company = models.CharField(
        max_length=max(len(i) for i in COMPANIES),
        choices=((c, c) for c in COMPANIES)  # geez
    )

    # one to many
    # department = models.ForeignKey(
    #     Department,
    #     on_delete=models.CASCADE,
    # )

    image = models.ImageField(
        null=True,
        blank=True,
        upload_to='profiles'
    )

    def __str__(self):
        return self.first_name

    class Meta:
        ordering = ('company', '-first_name',)

class Project(models.Model):
    name = models.CharField(
        max_length=30,
    )
    dead_line = models.DateField(
        null=True,
        blank=True,
    )

    # employeeS --> PLURAL
    # many to many
    employees = models.ManyToManyField(
        to=Employee,
    )  # ----> many to many -> exists only in one of the tables that are related, doesn't matter which one

class User(models.Model):
    email = models.EmailField()

    # one to one
    employee = models.OneToOneField(
        to=Employee,
        on_delete=models.CASCADE,
        primary_key=True,
    )

# class TestModel(models.Model):
#     id2 = models.IntegerField(
#         auto_created=True,
#         primary_key=True,
#     )


#!/usr/bin/python3
""" BaseCaching module
"""
from base_caching import BaseCaching

class LIFOCache(BaseCaching):
    """
    caching system that implements LIFO algo
    """
    def __init__(self):
        super().__init__()
        self.cache_order = []

    def put(self, key, item):
        '''
        Puts an item in the cache
        discards the last item put if the size of the cache
        than the max number of items
        '''
        if not key or not item:
            return
        self.cache_data[key] = item
        if len(self.cache_data) > BaseCaching.MAX_ITEMS:
            if self.cache_order:
                last = self.cache_order.pop()
                del self.cache_data[last]
                print('DISCARD: {}'.format(last))

        if key not in self.cache_order:
            self.cache_order.append(key)
        else:
            self.add_to_cache_order(key)

    def get(self, key):
        """get an item from cache by key """
        if not key or key not in self.cache_data:
            return None
        else:
            return self.cache_data.get(key)

    def add_to_cache_order(self, key):
        """add key to cache order if not already in cache order"""
        length = len(self.cache_order)
        if self.cache_order[length - 1] != key:
            self.cache_order.remove(key)
            self.cache_order.append(key)


import numpy as np
from matplotlib import pyplot as plt
import time

start = time.time()

B_ex = 2
J_par = 1
J_tan = 1
# Runtime around 9 seconds with n_max = 8, almost instant for lower values.
# n_max = 10 takes quite some time.
n_max = 10
beta_const = 0.5
kb = 1.3806485279e-23

def gen_spin_conf(n):
	spin_conf = np.ones([2**n, n])
	for i in range(n):
		spin_conf.T[i] = np.array([[1]*2**(i) + [-1]*2**(i)] * ((2**n)//(2**(i+1)))).flatten()
	return spin_conf

# Generates A, B and C without prefactors Be and beta
def gen_ABC(spin_conf, Jp=J_par, Jt=J_tan):
	dim = spin_conf.shape[0]
	A = Jp * np.matmul(spin_conf, spin_conf.T)
	B = Jt * np.repeat(np.sum(spin_conf * np.apply_along_axis(np.roll, 1, spin_conf, 1), axis=1).reshape(dim,1), dim, axis=1)
	sum_vec = np.sum(spin_conf, axis=1)
	C = (1/2) * (np.tile(sum_vec, [dim, 1]).T + sum_vec.T)
	return A, B, C

def max_eigen_value(A, B, C, spin_conf, beta, Be):
	P = np.exp(beta*A + beta*B + beta*Be*C)
	e_vals = np.linalg.eigvals(P)
	return np.amax(np.real(e_vals))

beta_vals = np.linspace(0.005, 1, 100)
B_vals = np.linspace(-1, 1, 100)
T_vals = 1/(kb*beta_vals)
eigen_val_vec = np.zeros([n_max, 100])
eigen_val_vec_b = np.zeros([n_max, 100])
eigen_val_vec_d = np.zeros([n_max, 100])
spes_heat_vec = np.zeros([4, 100])

# Loop computes everything using functions and values defined above:
for i in range(n_max):
	spin_conf = gen_spin_conf(i+1)
	print("n: ",i+1)
	A, B, C = gen_ABC(spin_conf)
	for j in range(beta_vals.size):
		eigen_val_vec[i][j] = np.log(max_eigen_value(A, B, C, spin_conf, beta_vals[j], B_ex))
		eigen_val_vec_b[i][j] = np.log(max_eigen_value(A, B, C, spin_conf, beta_const, B_vals[j]))
	if i+1 <= 5 and i+1 >= 2:
		for k in range(beta_vals.size):
			spes_heat_vec[i-1] = np.gradient(np.gradient(eigen_val_vec[i], beta_vals), beta_vals)*((beta_vals[k]**2)/(i+2))
	eigen_val_vec_d[i] = np.gradient(eigen_val_vec_b[i], B_vals)/((i+2)*beta_const)
	print(i+1," done", n_max - i -1, " to go.")

end = time.time()
print("Computation time: ", end - start, " seconds")

# Computations done, plotting:
for i in range(eigen_val_vec.shape[0]):
	plt.plot(beta_vals, eigen_val_vec[i], label="n = " + str(i+1))
plt.title("Largest eigenvalues -  $B=$" + str(B_ex) + ", $Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("beta - $1/k_{b}} \dot T$")
plt.ylabel("Eigenvalue")
plt.savefig("fig1.pdf")
plt.show()

for i in range(eigen_val_vec_d.shape[0]):
	plt.plot(B_vals, eigen_val_vec_d[i], label="n=" + str(i+1))
plt.title("Magnetization per spin - $beta = $" + str(beta_const)  + ",$ Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("External magnetic field - $B$")
plt.ylabel("Magnetization per spin - $m$")
plt.savefig("fig2.pdf")
plt.show()

for i in range(spes_heat_vec.shape[0]):
	# Not sure what's best of plotting with regards to T or beta(T)
	plt.plot(T_vals, spes_heat_vec[i], label="n=" + str(i+2))
plt.title("Specific heat per spin -  $B=$" + str(B_ex) + ", $Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("Temperature - $T$")
plt.ylabel("Spesific heat per spin - $C_{B}$")
plt.savefig("fig3.pdf")
plt.show()


# Los programas inteligentes usan booleanos para tomar decisiones sobre si ejecutar lineas de codigo u omitirlas

activo = True

if activo == True:
    print("El usuario está activo")
    activo = False

cargado = True
if cargado:
    print("EL celular está cargado")
else:
    print("Conecte el cargador")

pagado = True
if cargado:
    print("El artículo está pagado")
else:
    print("Moroso, por favor pague")

nota = 80
if nota <= 80:
    print("Penales, mamei")
else:
    print("Pasaste, bien soldado")

porcentaje = 45

if porcentaje < 60:
    print("REPROBADO, HASTA LA VISTA BABY")
elif porcentaje < 70:
    print("PENALES")
else:
    print("FELICIDADES, APROBASTE")


import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
from functions import *
from utils import *

intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
Bot = commands.Bot(command_prefix='.', intents=intents)
game = Game()
bot = discord.ext.commands.Bot(command_prefix="your_prefix");

@Bot.event
async def on_ready():
    print("Let's Go ")

@Bot.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.text_channels, name="gelenler")
    await channel.send(f"{member} Sunucuya Katıldı.")
    print(f"{member} Sunucuya Katıldı.")

@Bot.event
async def on_member_remove(member):
    channel = discord.utils.get(member.guild.text_channels, name="gelenler")
    await channel.send(f"{member} Sunucudan Ayrıldı.")
    print(f"{member} Sunucudan Ayrıldı.")

@Bot.command()
# @has_permissions(administrator=True)
async def sil(ctx, amount=5):
    await ctx.channel.purge(limit=amount)
    print(f"Başarı ile temizlendi.")

    # @Bot.command()
    # async def join(ctx):
    #    channel = message.author.voice.channel
    #    await channel.connect()

    # @Bot.command(pass_content=True)
    # async def join(ctx):
    #    channel = ctx.author.voice.channel
    #    await channel.connect()

@Bot.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.author.voice.channel
        await channel.connect()
        await ctx.send('Bot joined')
    else:
        await ctx.send("You must be in a voice channel first so I can join it.")

@Bot.command()
async def leave(
        ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send('Bot left')
    else:
        await ctx.send("I'm not in a voice channel, use the join command to make me join")

# @Bot.command(pass_content=True)
# async def leave(ctx):
#   channel = ctx.message.author

# await ctx.send(f'Bot Herhangi Bir Odada Değil')py
# return

@Bot.command(aliases=["kopyala"])
@has_permissions(administrator=True)
async def clone_channel(ctx, amount=1):
    for i in range(amount):
        await ctx.channel.clone()

@Bot.command(pass_context=True)
@has_permissions(administrator=True)
async def kick(ctx, user: discord.Member):
    await ctx.send(f'The Kicking Hammer Has Awoken! {user.name} Has Been Banished', )
    await ctx.guild.kick(user)

@Bot.command(pass_context=True)
@has_permissions(administrator=True)
async def ban(ctx, user: discord.Member):
    await ctx.send(
        f'Ban Çekicini Kafasına Yedi! {user.name} Artık Uzaklarda!' 'https://media1.giphy.com/media/fe4dDMD2cAU5RfEaCU/giphy.gif?cid=ecf05e47kie7ltgktey7bkzrng32arpvxbfuk6fyd3niq0da&rid=giphy.gif')
    await ctx.guild.ban(user)
    return

@Bot.command()
@has_permissions(administrator=True)
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for bans in banned_users:
        user = bans.user

        if (user.name, member_discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(
                f'Geri Getirme Büyüsü Yapıldı! {user.name} Artık Aramıza Gelebilir!' 'https://media0.giphy.com/media/MB6OMCu3uQQrgVIsSu/giphy.gif')
            return

@Bot.command()
async def komutlar(ctx):
    await ctx.send('amcıemre1 amcıemre2 join leave zar at')

@Bot.command()
async def amciemre1(ctx, *args):
    await ctx.send('https://tenor.com/view/polis-emre-amcık-görüyor-gif-19133767')

@Bot.command()
async def amciemre2(ctx, *args):
    await ctx.send('https://tenor.com/view/seemih-fidan-emre-amcıemre-31-gif-19753463')

@Bot.command()
async def yarra(ctx):
    await ctx.send('https://tenor.com/view/yarra-yarra-beni-yarra-aşkına-beter-beter-ali-gif-16749214')

@Bot.command()
async def fcukyou(ctx):
    await ctx.send('https://media.discordapp.net/attachments/763053037332725790/805519690617192518/image0-34.gif')

@Bot.command()
@has_permissions(administrator=True)
async def aktif(ctx):
    await ctx.send('https://cdn.discordapp.com/attachments/814893842469617665/817484594706251776/giphy.gif')

@Bot.command(aliases=["zar"])
async def lafıkoyunca(ctx, *args):
    if "at" in args:
        await ctx.send(game.at_dice())
    else:
        await ctx.send(
            '@everyone,https://tenor.com/view/kerpeten-ali-kerpeten-ali-kerpeten-dans-hip-hop-dans-gif-19947997')

@Bot.command()
async def lspd(ctx,):
        await ctx.send(
            'https://media.giphy.com/media/QUY2pzDAKVpX3QacCg/giphy.gif')

@Bot.command()
async def ip(ctx, ):
        await ctx.send(
            'F8 connect 185.88.174.226 TS3 IP : navyts3')

@Bot.command()
async def woul(ctx, ):
        await ctx.send(
            'connect 185.126.178.26 TeamSpeak: woulroleplay')

Bot.run(TOKEN)


import cv2

def resize_and_save(image_path, output_path):
    # 读取图像
    img = cv2.imread(image_path)

    # 检查是否正确读取图像
    if img is None:
        print(f"Error: Unable to open image file: {image_path}")
        return

    # 调整图像大小
    resized_img = cv2.resize(img, (320, 240))

    # 保存调整后的图像
    cv2.imwrite(output_path, resized_img)

# 使用方式
resize_and_save('path_to_input_image', 'path_to_output_image')
"""
if（第一位等于 0x05 && 第二位等于）
{
    左转的GPIO
    while(1)
    {
        6050
        if （大于一定值）
        {
            break;
        }
    }
}
else if （第一位等于 0x05 && 第二位等于）
    {
        右转的GPIO
    while(1)
    {
        6050
        if （大于一定值）
        {
            break;
        }
    }
    }

"""


import random

########################################################## Classes #################################################################

class Zombie():

    def __init__(self):

        self.character = "Z"

        self.location = None
        self.fromBrain = None

    def __repr__(self):

        return "Z"

    def __str__(self):

        return "zombie"

class Brain():

    def __init__(self):

        self.location = None
        self.character = "@"
        self.fromBrain = 0

    def __repr__(self):

        return "@"

    def __str__(self):

        return "brain"

class Cell():

    def __init__(self):

        self.fromBrain = None
        self.contains = None
        self.character = "-"

    def __repr__(self):

        return "-"

    def __str__(self):

        if self.contains == None:

            return "Empty"

        return self.contains

############################################################ Map ###################################################################

def SimpleZombieAI():

    map = [Cell() for num in range(144)]

    def addEntities(zombieNum, brainNum): # Automatically adding entities to the map.

        # I need it to choose a random index in map, not what's in it.

        for num in range(int(zombieNum)): # Choose a random number. Then, pop it and insert a zombie/brain there.

            randomNum = random.choice(range(len(map)))

            if map[randomNum].contains == None: # I need to make this a loop, rerandomizing the number over and over again if map[currentNum] isn't None.

                map.pop(randomNum)

                map.insert(randomNum, Zombie())

                map[randomNum].contains = "zombie"

        for num in range(int(brainNum)):

            randomNum = random.choice(range(len(map)))

            if map[randomNum].contains == None:

                map.pop(randomNum)

                map.insert(randomNum, Brain())

                map[randomNum].contains = "brain"

    addEntities(1, 1)

    ######################################################### Functions ################################################################

    def checkMapSquareSize(): # Checking what size of square the map is.

        numsList = [num for num in range(len(map))]
        numsList.reverse()

        for num in numsList:

            if len(map) - (num ** 2) == 0: # prolly coulda used sqrRoot or some shit but ah well

                return num

        return "Not a perfect square."

    def findBrain():

        temp = None

        for cell in map:

            if type(cell) == Brain:

                temp = cell

        return map.index(temp)

    def findZombie():

        temp = None

        for cell in map:

            if type(cell) == Zombie:

                temp = cell

        return map.index(temp)

    def updateFromBrainDistances(): # I don't actually remember what this function was intended for. A small consequence of leaving your work!

        staticBrainLocation = findBrain()
        iteration = 1
        sqrt = checkMapSquareSize()

        # Alright, I'll have it radial search from the brain; the first cells it finds will be given a tag of "1". Second wave will be "2", etc.

        while iteration < sqrt:

            for horizontal in range(-iteration, iteration + 1):
                for vertical in range(-iteration, iteration + 1):

                    currentCell = staticBrainLocation + horizontal + (vertical * sqrt)

                    try:

                        if currentCell >= 0 and map[currentCell].fromBrain == None:

                            map[currentCell].fromBrain = iteration

                            # if iteration == 1:

                            #     # print(f"{currentCell} is {iteration} cell away.")

                            # else:

                            #     # print(f"{currentCell} is {iteration} cells away.")

                    except:

                        pass

            iteration += 1

    updateFromBrainDistances()

    def terminalFormatting(): # So that my terminal is way cleaner to look at from a human perspective.

        # I want it to add a newline as it prints, depending on what the square root is.
        # A way I can think of is to turn a maplist into a string, insert a \n after so many characters, and print the string instead.

        sqrt = checkMapSquareSize()

        concatCount = 0

        mapString = ""

        for cell in map:

            mapString += cell.character + " "

            concatCount += 1

            if concatCount == sqrt:

                concatCount = 0

                mapString += "\n"

        return mapString

    print(terminalFormatting())

    for cell in map:

        if type(cell) == Zombie:

            if cell.fromBrain != 1:

                print(f"There is a zombie currently {cell.fromBrain} spots away.\n")

            else:

                print(f"There is a zombie currently {cell.fromBrain} spot away.\n")

    # Now, I just need to make the Zombie object take the closest path. This can be done by checking around it for the lowest fromBrain
    # property, then switching spots with that cell. I will have my program update every cycle so that the fromBrain properties get fixed.

    def findNextStone():

        sqrt = checkMapSquareSize()
        zombieLocation = findZombie()

        leastDistance = 50
        nextStoneIndex = None

        for horizontal in range(-1, 2):
                for vertical in range(-1, 2):

                    currentCell = zombieLocation + horizontal + (vertical * sqrt)

                    try:

                        if map[currentCell].fromBrain < leastDistance:

                            leastDistance = map[currentCell].fromBrain
                            nextStoneIndex = currentCell
                    except:

                        pass

        return nextStoneIndex

    def swapCells(fromCell, toCell): # If I want to use zombie or brain specifically, I have to comb through/find the zombie and brain, and assign temporary variables to them.

        fromCellIndex = map.index(fromCell)
        toCellIndex = map.index(toCell)

        if toCell.contains == None:

            map.pop(toCellIndex)                    # toCell = fromCell
            map.insert(toCellIndex, fromCell)

            map.pop(fromCellIndex)                  # fromCell = toCell
            map.insert(fromCellIndex, toCell)

        else:

            map.pop(toCellIndex)                    # toCell = fromCell
            map.insert(toCellIndex, fromCell)

            map.pop(fromCellIndex)                  # different this time, fromCell becomes vacant.
            map.insert(fromCellIndex, Cell())

    def brainRemaining():

        for cell in map:

            if type(cell) == Brain:

                return True

        return False

    # Lastly (I think), I need to build the While loop, so my level keeps operating.

    turnCounter = 0

    while (brainRemaining()):

        print(terminalFormatting())

        turnCounter += 1

        zombieLocation = findZombie()
        nextStoneIndex = findNextStone()

        swapCells(map[zombieLocation], map[nextStoneIndex])

    print("It found the brain!")

if __name__ == "__main__":

    SimpleZombieAI()


import pandas as pd
from webScrapping import toDF
import folium
import webbrowser

pd.set_option('display.width', 340)
pd.set_option('display.max_columns', 8)
earthquakeDF = toDF()
print(earthquakeDF.to_string())
earthquakeMap = folium.Map(location=[39.16, 35.66], zoom_start=5.5, tiles="Stamen Terrain")
folium.GeoJson('https://raw.githubusercontent.com/fraxen/tectonicplates/master/GeoJSON/PB2002_boundaries.json',
               name="geojson").add_to(earthquakeMap)
folium.LayerControl().add_to(earthquakeMap)

def addCircles(df):
    for x, y, z, *a in zip(df['Latitude'], df['Longitude'], df['Magnitude [ML]'], df['Location'], df['Date'], df['Time']):
        popUp = f"
Magnitude : {z} ML
" \
                f"
Location - Date: {a}
"
        iframe = folium.IFrame(popUp, width=450, height=70)
        popup = folium.Popup(iframe, max_width=450)
        folium.CircleMarker(location=(x, y), radius=float(z) * 4, weight=2, opacity=1, popup=popup,
                            color="red", fill_color="red", fill_opacity=0.1).add_to(earthquakeMap)

addCircles(earthquakeDF)
earthquakeMap.save("map.html")
webbrowser.open("map.html")


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

u"""
Посчитать процентное соотношение букв в тексте. Заглавные и строчные приравниваются.
Вывести словарь: ключ - буква, значение - процент (до десятых),
в котором эта буква встречается в тексте.
Текст:
Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Donec rutrum congue leo eget malesuada.
"""

__author__ = "anna-karnaukh"
__email__ = "anna.karnaukh1@gmail.com"
__date__ = "2014-11-16"

def frequency_of_letters(text):
	u"""
	Подсчитывает частоту вхождения буквы в заданую строку.
	Принимает строку text, выводит словарь result (ключ - буква, значение - процент (до десятых),
	в котором эта буква встречается в тексте.).
	"""
	text = text.lower()
	value = 0
	subresult = {}
	result = {}
	length = 0
	for char in text:
		if char.isalnum() == True:
			if char not in subresult.keys():
				value = text.count(char)
				subresult[char] = value
			length += 1
	for k, v in subresult.iteritems():
		result[k] = round(float(v)/length*100, 1)
	return result


from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from random import random
from bs4 import BeautifulSoup
import pandas as pd

def to_float(x): # converts strange strings to float
    a = ""
    flag = 0 # have we met "," or "."
    for i in x:
        if ord(i) >= ord("0") and ord(i) <= ord("9"):
            a += i
        elif not flag and (i == "." or i == ","):
            a += i
            flag = 1
    a = a.replace(",", ".")
    return float(a)

options = webdriver.ChromeOptions() # setting options for window
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")

driver = webdriver.Chrome('chromedriver', options=options) # start and get target page
driver.get("https://store.steampowered.com/specials#p=0&tab=TopSellers")
html = driver.page_source
soup = BeautifulSoup(html, "html.parser")
totalpages = (soup.find("span", {"id" : "TopSellers_links"})).find_all("span", {"class" : "paged_items_paging_pagelink"})
totalpages = int(totalpages[-1].getText())

header = ["Game", "Original price", "Discount", "Final price"]
table = []
current_page = 0

while (current_page < totalpages):
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    soup = soup.find("div", {"id" : "TopSellersTable"})
    games = soup.find_all("div", {"class" : "tab_item_name"})
    original_prices = soup.find_all("div", {"class" : "discount_original_price"})
    discounts = soup.find_all("div", {"class": "discount_pct"})
    final_prices = soup.find_all("div", {"class": "discount_final_price"})
    for i in range(len(games)):
        games[i] = games[i].getText()
        original_prices[i] = to_float(original_prices[i].getText())
        discounts[i] = to_float(discounts[i].getText())
        final_prices[i] = to_float(final_prices[i].getText())
        table.append([games[i], original_prices[i], discounts[i], final_prices[i]])
    sleep(1 + 2 * random()) # 1 - 3 sec
    current_page += 1
    element = driver.find_element(By.ID, "TopSellers_btn_next")  # find and push button to increase list of games to parse
    element.click()
    sleep(1 + 2 * random())

pd.DataFrame(table).to_csv('SteamDiscounts.csv', index=False, header=header)

driver.quit()


texto = input('Digite sua frase :').upper()
textocifrado = ""

alfabeto ="ABCDEFGHIJKLMNOPQRSTUVWXYZABCD"

for letra in texto:
    localizacao = alfabeto.find(letra)
    if localizacao >= 0:
        novalocalizacao = localizacao+3
        textocifrado += alfabeto[novalocalizacao]
    else:
        textocifrado += letra
print(textocifrado)

Exercicio Manipulção de Stirng/Exercicio 1.py


import asyncore
import select
import time
import uuid

from .util import debug

TIMERS = {}

def loop(timeout=1, use_poll=False, map=None, count=None):
    if map is None:
        map = asyncore.socket_map

    if use_poll and hasattr(select, 'poll'):
        poll_fun = asyncore.poll2
    else:
        poll_fun = asyncore.poll

    if count is None:
        while map:
            poll_fun(timeout, map)
            _check_timers()
    else:
        while map and count > 0:
            poll_fun(timeout, map)
            _check_timers()
            count = count - 1

def _check_timers():
    now = time.time()
    calls = {}
    for timer_id, timer in TIMERS.items():
        if now >= timer.get('when'):
            calls[timer_id] = timer.get('what')
            if timer.get('interval') is not None:
                timer['when'] = time.time() + timer.get('interval')

    for timer_id, call in calls.items():
        try:
            call()
        except Exception as e:
            debug("ERRO", "Exception running interval callback for timer {}: ".format(timer_id), e)
            import traceback
            traceback.print_exc()

def set_timeout(callback, timeout):
    def call_and_expire():
        del TIMERS[timer_id]
        return callback()

    timer_id = uuid.uuid4()
    TIMERS[timer_id] = {
        'when': time.time() + timeout,
        'what': call_and_expire,
        'interval': None,
    }
    return timer_id

def set_interval(callback, timeout):
    timer_id = uuid.uuid4()
    TIMERS[timer_id] = {
        'when': time.time() + timeout,
        'what': callback,
        'interval': timeout,
    }
    return timer_id

def cancel_timeout(timer_id):
    if timer_id not in TIMERS:
        debug("WARN", "Trying to cancel timeout timer {} which doesn't exist. This should be fixed".format(timer_id))
        return
    del TIMERS[timer_id]

def cancel_interval(timer_id):
    if timer_id not in TIMERS:
        debug("WARN", "Trying to cancel interval timer {} which doesn't exist. This should be fixed".format(timer_id))
        return
    del TIMERS[timer_id]


from rest_framework import serializers
from rest_framework.relations import SlugRelatedField

from posts.models import Comment, Post, Group, User, Follow

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True, slug_field='username'
    )
    post = serializers.PrimaryKeyRelatedField(
        read_only=True
    )

    class Meta:
        fields = '__all__'
        model = Comment

class PostSerializer(serializers.ModelSerializer):
    author = SlugRelatedField(slug_field='username', read_only=True)
    comments = CommentSerializer(read_only=True, many=True)

    class Meta:
        fields = '__all__'
        model = Post

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username',
        default=serializers.CurrentUserDefault()
    )
    following = serializers.SlugRelatedField(
        slug_field='username',
        queryset=User.objects.all()
    )

    class Meta:
        fields = '__all__'
        model = Follow


import os
import time
import torch.backends.cudnn as cudnn
from skimage.metrics import peak_signal_noise_ratio
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from datasets import SRDataset
from model import SRResNet
from utils import *

crop_size = 291
scaling_factor = 3

large_kernel_size = 9
small_kernel_size = 3
n_channels = 64
n_blocks = 16
checkpoint_dir = 'models'
if not os.path.isdir(checkpoint_dir):
    os.mkdir(checkpoint_dir)

epoch = 0
checkpoint = checkpoint_dir
batch_size = 32
start_epoch = 0
iterations = 1e5
workers = 4
lr = 1e-3
grad_clip = True

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
writer = SummaryWriter()

cudnn.benchmark = True

def main():
    """
    Training.
    """
    global start_epoch, epoch, checkpoint

    print('Find checkpoint')
    checkpoint = torch.load('./models/best_checkpoint_srresnet.pth.tar')
    start_epoch = checkpoint['epoch'] + 1
    model = checkpoint['model']
    optimizer = checkpoint['optimizer']

    model = model.to(device)
    criterion = nn.MSELoss().to(device)

    train_dataset = SRDataset(split='train',
                              crop_size=crop_size,
                              scaling_factor=scaling_factor,
                              lr_img_type='imagenet-norm',
                              hr_img_type='[-1, 1]')

    val_dataset = SRDataset(split='val',
                            crop_size=0,
                            scaling_factor=scaling_factor,
                            lr_img_type='imagenet-norm',
                            hr_img_type='[-1, 1]')
    print('train_loader loading')
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=workers,
                                               pin_memory=True)
    print('val_loader loading')

    val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=1, shuffle=True, num_workers=workers,
                                             pin_memory=True)

    epochs = int(iterations // len(train_loader) + 1)

    max_psnr = 0
    for epoch in range(start_epoch, epochs):
        train(train_loader=train_loader,
              model=model,
              criterion=criterion,
              optimizer=optimizer,
              epoch=epoch)
        psnr = val(val_loader=val_loader,
                   model=model,
                   epoch=epoch)
        if psnr.avg > max_psnr:
            max_psnr = psnr.avg
            torch.save({'epoch': epoch,
                        'model': model,
                        'optimizer': optimizer},os.path.join(checkpoint_dir, 'best_checkpoint_srresnet.pth.tar'))

        torch.save({'epoch': epoch,
                    'model': model,
                    'optimizer': optimizer},os.path.join(checkpoint_dir, 'checkpoint_srresnet.pth.tar'))

def train(train_loader, model, criterion, optimizer, epoch):

    epochs = str(int(iterations // len(train_loader) + 1))

    model.train()

    batch_time = AverageMeter()
    data_time = AverageMeter()
    losses = AverageMeter()
    PSNRs = AverageMeter()

    start = time.time()

    for i, (lr_imgs, hr_imgs) in enumerate(train_loader):
        data_time.update(time.time() - start)

        lr_imgs = lr_imgs.to(device)
        hr_imgs = hr_imgs.to(device)

        sr_imgs = model(lr_imgs)

        sr_imgs_y = convert_image(sr_imgs, source='[-1, 1]', target='y-channel').squeeze(0)
        hr_imgs_y = convert_image(hr_imgs, source='[-1, 1]', target='y-channel').squeeze(0)
        psnr = peak_signal_noise_ratio(hr_imgs_y.cpu().detach().numpy(), sr_imgs_y.cpu().detach().numpy(), data_range=255.)
        PSNRs.update(psnr, lr_imgs.size(0))

        loss = criterion(sr_imgs, hr_imgs)

        optimizer.zero_grad()
        loss.backward()

        if grad_clip is not None:
            clip_gradient(optimizer, grad_clip)

        optimizer.step()

        losses.update(loss.item(), lr_imgs.size(0))

        batch_time.update(time.time() - start)

        start = time.time()

    writer.add_scalar('Loss/train', losses.avg, epoch)
    writer.add_scalar('PSNR/train', PSNRs.avg, epoch)
    print(
        f'Epoch: {epoch} / ' + epochs + ' -- '
        f'Batch Time: {batch_time.avg:.3f} -- '
        f'Loss: {losses.avg:.4f} -- '
        f'PSNR: {PSNRs.avg:.4f}'
    )
    del lr_imgs, hr_imgs, sr_imgs

def val(val_loader, model, epoch):
    model.eval()
    PSNRs = AverageMeter()
    with torch.no_grad():
        for i, (lr_imgs, hr_imgs) in enumerate(val_loader):

            lr_imgs = lr_imgs.to(device)
            hr_imgs = hr_imgs.to(device)

            sr_imgs = model(lr_imgs)

            sr_imgs_y = convert_image(sr_imgs, source='[-1, 1]', target='y-channel').squeeze(0)
            hr_imgs_y = convert_image(hr_imgs, source='[-1, 1]', target='y-channel').squeeze(0)
            psnr = peak_signal_noise_ratio(hr_imgs_y.cpu().numpy(), sr_imgs_y.cpu().numpy(), data_range=255.)

            PSNRs.update(psnr, lr_imgs.size(0))
    print(f'Epoch: {epoch}, PSNR: {PSNRs.avg}')
    writer.add_scalar('PSNR/val', PSNRs.avg, epoch)
    del lr_imgs, hr_imgs, sr_imgs

    return PSNRs

if __name__ == '__main__':
    main()


from . import requests
from .end_points import UserEndPoint

MIDDLE_EARTH_PURCHASED_EQUIPMENT_END_POINT = "http://middleearthitems:8002/api/items/"
MIDDLE_EARTH_USERS_ENDPOINT = "http://middleearthauth:8001/api/users/"
MIDDLE_EARTH_INVENTORY_END_POINT = "http://middleearthinventory:8003/api/inventory/"
MIDDLE_EARTH_USER_UPDATE_ENDPOINT = "http://middleearthauth:8001/api/users/"

def user_can_afford_equipment(user, equipment):
    return int(user["credit"]) >= (equipment["price"])

def get_parameters_for_purchase(user_get_response_json, purchased_equipment_get_response_json):
    parameters_for_purchase = {
        "owner_username": user_get_response_json["username"],
        "item_id": purchased_equipment_get_response_json["id"],
        "item_name": purchased_equipment_get_response_json["name"],
        "item_price": purchased_equipment_get_response_json["price"],
        "item_description": purchased_equipment_get_response_json["description"]
    }
    return parameters_for_purchase

def update_user_credit(request, user_response, equipment_response):
    reduced_credit = user_response["credit"] - equipment_response["price"]
    parameters_for_update_credit = {
        "credit": reduced_credit
    }
    requests.PatchRequest(request, end_point=UserEndPoint(request), parameters=parameters_for_update_credit)


"""
https://www.youtube.com/watch?v=nysVwISk9_c
Школа бэкенд-разработки 2021
12. Асинхронное программирование на практике – Дмитрий Орлов

https://github.com/YaBackSchool2021/homework9/blob/71f78f56eac989396eb0e5e318604f75bbb5e31b/event-loop-yield-from.py

"""

import logging
import time
from typing import Any, Callable
import heapq
import functools
import queue
from typing import NamedTuple

class Future:
    def __init__(self) -> None:
        self.result = None
        self.done = False
        self.done_callbacks: set[Callable[["Future"], Any]] = set()
        self.exception = None

    def _handle_callbacks(self):
        for cb in self.done_callbacks:
            try:
                cb(self)
            except Exception:
                logging.exception("Unhandled exception in", cb)

    def set_result(self, result):
        self.done = True
        self.result = result
        self._handle_callbacks()

    def set_exception(self, exception):
        self.exception = exception

    def get_result(self):
        if self.exception:
            raise self.exception
        return self.result

    def __iter__(self):
        while not self.done:
            yield None
        return self.get_result()

"""
# Example:

def sleep(seconds) -> Future:
    future = Future()
    loop.call_later(
        seconds,
        future.set_result,
        True
    )
    return future

yield from sleep(10)

"""

@functools.total_ordering
class TimedContainer(NamedTuple):
    time: float
    value: Any

    def __lt__(self, other):
        return self.time < other.time

    def __eq__(self, other):
        return self.time == other.time

class CallbackHandler:
    def __init__(self) -> None:
        self.heap = []

    def call_later(self, delay, func, *args) -> Future:
        future = Future()
        heapq.heappush(
            self.heap,
            TimedContainer(
                delay + time.monotonic(),
                (
                    future,
                    functools.partial(func, *args),
                ),
            ),
        )
        return future

    def step(self) -> None:
        """
        If the time is ripe for the earliest scheduled callback, then run it
         and update the Future object.
        If there's no callbacks ready to run (the heap is empty or they are
         currently all delayed), do nothing.
        """
        while self.heap:
            if self.heap[0][0] > time.monotonic():
                return
            _future, func = heapq.heappop(self.heap).value
            future: Future = _future
            try:
                future.set_result(func())
            except Exception as e:
                future.set_exception(e)

class EventLoop:
    def __init__(self):
        self.events = queue.SimpleQueue()
        self.callbacks = CallbackHandler()

    def call_later(self, delay, callback, *args) -> Future:
        return self.callbacks.call_later(delay, callback, *args)

    def step(self, coro):
        try:
            next(coro)
        except StopIteration as e:
            return e.value
        self.events.put(coro)

    def run(self):
        while not self.events.empty():
            self.callbacks.step()
            self.step(self.events.get())

    def create_task(self, coro):
        future = Future()

        def wrapper():
            try:
                result = yield from coro
                future.set_result(result)
            except Exception as e:
                future.set_exception(e)

        gen = wrapper()
        self.events.put(gen)
        return future

    def run_until_complete(self, coro):
        future = self.create_task(coro)
        self.run()
        return future.get_result()

loop = EventLoop()

def sleep(secs) -> Future:
    return loop.call_later(secs, lambda: True)

def test(s):
    yield from sleep(2 + s)
    print(time.monotonic(), "test done")

print(time.monotonic(), "start")
loop.create_task(test(0.1))
loop.create_task(test(0.2))
loop.run_until_complete(test(0.3))

print(time.monotonic(), "finished")


import numpy as np
import matplotlib.pyplot as plt

import mapsList

class Map:

    def __init__(self, F, dimension: int, param, name: str):
        ''' A class for maps.

        A map is a discrete-time dynamical system.
        It is characterized by a function F: X -> X, where X is the space in which the map acts.

        Parameters
        ----------
        F:
            The function characterizing the map such that F(x(t)) = x(t+1)
        dimension:
            the dimensionality of the space X
        param
            the parameters of the map
        name: string
            The name of the map
        '''

        self.dimension = dimension
        self.param = param
        self.F = F
        self.name = name
        self.n_iter = None

    def trajectory(self, x_0: np.array, n_iter: int) -> np.array:
        '''
        return a trajectory of the map.

        Parameters
        ----------
        x_0 : np.array[dimension]
            An arraywith the initial conditions of the system.
            Its dimension must be the same of the map.
        n_iter: int
            the number of iteration that the map has to do.

        Returns
        -------
        X : np.array
            np.array with dimensions (dimension, n_iter+1)
        '''
        self.n_iter = n_iter

        X = np.zeros((self.dimension, self.n_iter))
        X[:, 0] = x_0
        x = x_0

        for k in range(1, n_iter):
            y = self.F(x, self.param)
            X[:, k] = y
            x = y

        self.X = X
        return X

    def _repeated(self, x, n: int):
        ''' Applies the map 'n' times to a point x.
        This means computing F^n(x)

        Parameters
        ----------
        x
            The point starting from which the map is iterated
        n
            The number of iteration
        Returns
        -------
        F^n(x), i.e., the map iterated n times

        '''
        for _ in range(n):
            x = self.F(x, self.param)
            # print x
        return x

    def plot_map(self, n_iter=1, x_min=0, x_max=1):
        ''' A function plotting the graph of the map.

        The map must be 1-dimensional!
        The x-axis represent x(t) while the y-axis is x(t+1) = F(x(t)).
        It can be used to plot multiple iteration of a map, i.e., plotting G(x) = F^n(x).

        Parameters
        ----------
        n_iter : int, default=1
            number of iteration of the map.
        x_min,x_max : int, default = 0,1
            The min and max value to be visualized, for both axis.
        '''
        x = np.arange(x_min, x_max, 0.0001)
        Fig = plt.figure(figsize=(5, 5))
        ax = Fig.add_subplot(111)

        ax.plot(x, self._repeated(x, n_iter))
        ax.plot(x, x, 'k')

        ax.set_xlim(x_min, x_max)
        ax.set_ylim(x_min, x_max)

        ax.set_xlabel('x[n]')
        ax.set_ylabel('x[n+1]')

        if n_iter == 1:
            ax.set_title('{} map'.format(self.name, n_iter), fontsize=16)
        else:
            ax.set_title('{} map iterated {} times'.format(self.name, n_iter), fontsize=16)

        plt.tight_layout()
        plt.show()

# ------------------------------------------------------

class Logistic(Map):
    def __init__(self, r=3.5):
        ''' Logistic map F(x) = r*x*(1-x)

        Parameters
        ----------
        r : float, default = 3.5
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.logistic, 1, r, "Logistic")

# -----------------------------------------------------------
class Tent(Map):
    def __init__(self, r=2):
        ''' Tent map  F(x) = r*min(x, 1-x)
        Parameters
        ----------
        r : float, default = 2
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.tent, 1, r, "Tent")

# ---------------------------------------------------------------

class Shift(Map):
    def __init__(self, r=1):
        ''' Shift map F(x) = r*( 2*x mod(1) )

        Parameters
        ----------
        r: float, default = 1
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.shift, 1, r, "Shift")

# -------------------------------------------------

class Quadratic(Map):
    def __init__(self, r=2):
        ''' Quadratic map F(x) = x**2 - r

        Parameters
        ----------
        r: float, default = 2
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.quadratic, 1, r, "Quadratic")


from mimetypes import init
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import pandas as pd
import numpy as np
import time
import datetime
from tqdm import trange

"""
These rules, which compare the behavior of the automaton to real life, can be condensed into the following:

Any live cell with two or three live neighbours survives.
Any dead cell with three live neighbours becomes a live cell.
All other live cells die in the next generation. Similarly, all other dead cells stay dead.
"""
# Grid refers to the list of lists containing data
# Plot refers to the visual plot of that data

def updateGrid( grid, rowCt, colCt ):

    live_ct, death_ct = 0, 0 # how many total live cells in the grid and how many cells died

    rows, cols = grid.shape[0], grid.shape[1] # get the size of the grid
    dr, dc = [1, 0, -1, 1, -1, 1, 0, -1], [-1, -1, -1, 0, 0, 1, 1, 1] # for checking neighboring cells
    rUpdate, cUpdate = [], []  # store which cells we need to flip in this update

    for r in range(rows):
        check = False           # Only check rows where we can potentially make a change
        if rowCt[r]>0:          #   if this row has at least one live cell, we can make a change
            check = True
        if r>0:
            if rowCt[r-1]>0:    #   if the row to the left of this row has at least one live, check this row
                check = True
        if r<(rows-1):
            if rowCt[r+1]>0:    #   if the row to the right of this row has at least one live, check this row
                check = True

        if check:                       # if we need to check this row
            nbrCt = 0                   # initialize how many neigbors we have
            #print("\nr:",r)
            for i in range(3, len(dr)): # check all in-bounds neighbors
                newR = r+dr[i]
                cc = dc[i]
                #print("Checking r:",newR,"c:",cc)
                if newR >= 0 and newR < rows:
                    nbrCt += grid[newR][cc]
                    #print("Valid, adding",grid[newR][cc])
            #print("c: 0 nbrCt:",nbrCt)
            checkCol = True             # Initialize the variable for if we should check this column

            for c in range(cols):
                updateNbr = False           # check if we just skipped some columns
                if checkCol == False:
                    updateNbr = True
                else:
                    checkCol = False

                if colCt[c]>0:
                    checkCol = True
                if c>0:
                    if colCt[c-1]>0:
                        checkCol = True
                if c<(cols-1):
                    if colCt[c+1]>0:
                        checkCol = True

                if checkCol:
                    if updateNbr:
                        nbrCt = grid[r][c] - grid[r][c-1]
                        for i in range(5):
                            newR = r+dr[i]
                            newC = c+dc[i]
                            if newR>=0 and newR<rows and newC>=0 and newC<cols:
                                nbrCt += grid[newR][newC]

                    if c>0:
                        nbrCt -= grid[r][c]
                        nbrCt += grid[r][c-1]
                        for i in range(5, len(dr)):
                            newR = r+dr[i]
                            newC = c+dc[i]
                            if newR>=0 and newR<rows and newC>=0 and newC<cols:
                                nbrCt += grid[newR][newC]
                        #print("c:",c,"nbrCt:",nbrCt)
                    if grid[r][c] == 0:
                        if nbrCt == 3:
                            rUpdate.append(r)
                            cUpdate.append(c)
                            live_ct += 1
                            rowCt[r] += 1
                            colCt[c] += 1
                    else:
                        if nbrCt < 2 or nbrCt > 3:
                            rUpdate.append(r)
                            cUpdate.append(c)
                            death_ct += 1
                            rowCt[r] -= 1
                            colCt[c] -= 1
                        else:
                            live_ct += 1
                    if c>0:
                        for i in range(3):
                            newR = r+dr[i]
                            newC = c+dc[i]
                            #print("\nChecking r:",newR,"c:",newC)
                            if newR>=0 and newR<rows and newC>=0 and newC<cols:
                                nbrCt -= grid[newR][newC]
                                #print("valid, subtracting",grid[newR][newC])

    for r, c in zip(rUpdate, cUpdate):
            if grid[r][c] == 0:
                grid[r][c] = 1
            else:
                grid[r][c] = 0

    return grid, live_ct, death_ct, rowCt, colCt

def simulateGame( grid, time_steps, live_init ):
    # Initialize plot
    x, y = [], []
    for row in range(grid.shape[0]):
        for col in range(grid.shape[1]):
            if grid[row][col] == 1:
                x.append(col)
                y.append(row)

    plt.ion()
    fig, ax = plt.subplots()
    gridPlt = ax.scatter(x, y, marker='x', color='b')
    plt.xticks(ticks=[])
    plt.yticks(ticks=[])
    plt.xlim(-1, grid.shape[0])
    plt.ylim(grid.shape[1], -1)
    plt.draw()

    # Initialize row and column counts
    rCt, cCt = np.zeros(grid.shape[0]), np.zeros(grid.shape[1])
    for row in range(grid.shape[0]):
        for col in range(grid.shape[1]):
            if grid[row][col] == 1:
                rCt[row] += 1
                cCt[col] += 1

     #beginning of the simulation :
    live_ct = live_init
    death_ct = 0

    prev = -1
    start_time = time.time()

    for step in trange(time_steps):
        grid, live_update, death_update, rCt, cCt = updateGrid( grid, rCt, cCt )
        live_ct += live_update
        death_ct += death_update

        #Update plot
        x, y = [], []
        for row in range(grid.shape[0]):
            for col in range(grid.shape[1]):
                if grid[row][col] == 1:
                    x.append(col)
                    y.append(row)

        gridPlt.set_offsets(np.c_[x,y])
        fig.canvas.draw_idle()
        plt.pause(0.05)

        if (death_update == 0 and live_update == prev) or live_update == 0: #means no movement, still life, therefore we can stop the simulation
            live_ct += live_update*(time_steps-step) #live_ct is updated to predict the rest of the simulation that is stopped
            break

    #end of simulation, displays of results
    end_time = time.time()
    delta_t = (end_time - start_time)
    print('Start time:', datetime.datetime.fromtimestamp(start_time).strftime('%c'))
    print('End time:', datetime.datetime.fromtimestamp(end_time).strftime('%c'))
    print('Elapsed time:' , delta_t*1000 , 'ms')
    print('Number of frames processed:', time_steps)
    print('Total living cells: ', live_ct)
    print('Total death cells: ' , death_ct)

    print('Average Frame Per Second (FPS):', time_steps/delta_t)

"""
Your script will begin by offering the user to select from the following initial states:
•blinker
•glider gun
•random (cells are set to living with some percentage of probability).
•another pattern which interests you

Your script will then ask for a grid size (grid will always be square so just ask for a single number).

Finally, your script will ask the user how many time steps to run the simulation for.
When you script has finished, some statistics will be displayed.
You will show the start date/time of thesimulation, the end date/time of the simulation, the number of milliseconds elapsed,
the number of frames processed, the total number of living cells during processing (just sum up the number of living cells
across all timesteps of the simulation),
and the number of cells that died across all timesteps of thesimulation.

"""
#TODO: ERROR CODE FOR INPUT (ONLY VALID INPUT - GRID SIZE > 3, ETC.)

def initGame():
    #initialisation
    init_state = input('Select initial state: [b]linker , [g]lider gun, [r]andom or [i]nfinite : ')
    while init_state not in ['b', 'g', 'r', 'i']:
        init_state = input('Please enter a valid state : ')

    grid_size = int(input('Enter grid size : '))
    if init_state == 'g':
        while grid_size < 36:
            grid_size = int(input('Grid size must be at least size 36 for this type. Enter new size: '))
    elif init_state == 'b':
        while grid_size <3:
            grid_size = int(input('Grid size must be at least size 3 for this type. Enter new size: '))
    elif init_state == 'r':
        while grid_size < 1:
            grid_size = int(input('Grid size must be at least size 1 for this type. Enter new size: '))
    elif init_state == 'i':
        while grid_size < 5:
            grid_size = int(input('Grid size must be at least size 5 for this type. Enter new size: '))

    time_steps = int(input('Enter the number of time steps to run the simulation for : '))
    while time_steps < 0:
        time_steps = int(input('Please enter a value of time steps greater than 0 : '))

    total_live_ct = 0

    grid = np.zeros((grid_size, grid_size))
    mid = int(grid_size/2)
    #grid[row][column]
    #top left = grid[0][0]
    #directly below top left = grid[1][0]
    if init_state == 'b':
        # O X O
        # O X O
        # O X O
        grid[mid][mid] = 1
        grid[mid+1][mid] = 1
        grid[mid-1][mid] = 1
        total_live_ct = 3

    elif init_state == 'g':
        #Gosper Glider gun
        grid[5][1]=1
        grid[5][2]=1
        grid[6][1]=1
        grid[6][2]=1

        grid[5][11]=1
        grid[6][11]=1
        grid[7][11]=1

        grid[4][12]=1
        grid[8][12]=1

        grid[3][13]=1
        grid[9][13]=1
        grid[3][14]=1
        grid[9][14]=1

        grid[6][15]=1

        grid[4][16]=1
        grid[8][16]=1

        grid[5][17] = 1
        grid[6][17] = 1
        grid[7][17] = 1

        grid[6][18] = 1

        grid[3][22] = 1
        grid[4][22] = 1
        grid[5][22] = 1
        grid[3][21] = 1
        grid[4][21] = 1
        grid[5][21] = 1

        grid[2][23] = 1
        grid[6][23] = 1

        grid[1][25] = 1
        grid[2][25] = 1
        grid[6][25] = 1
        grid[7][25] = 1

        grid[3][35] = 1
        grid[4][35] = 1
        grid[3][36] = 1
        grid[4][36] = 1

        total_live_ct = 35

    elif init_state == 'r':
        #randomised grid
        grid = np.random.randint(2, size=(grid_size, grid_size))
        total_live_ct = np.sum(grid)

    elif init_state == 'i' and grid_size>=5 :
        # X X X O X
        # X O O O O
        # O O O X X
        # O X X O X
        # X O X O X
        grid[mid-2][mid-2] = 1
        grid[mid-2][mid-1] = 1
        grid[mid-2][mid] = 1
        grid[mid-2][mid+2] = 1
        grid[mid-1][mid-2] = 1
        grid[mid][mid+2] = 1
        grid[mid][mid+1] = 1
        grid[mid+1][mid-1] = 1
        grid[mid+1][mid] = 1
        grid[mid+1][mid+2] = 1
        grid[mid+2][mid-2] = 1
        grid[mid+2][mid] = 1
        grid[mid+2][mid+2] = 1
        total_live_ct = 13
    elif init_state == 'i' and grid_size < 5 :
        print('Grid size too small for this input')

    simulateGame(grid, time_steps, total_live_ct)

initGame()


#!/usr/bin/env python3
# --------------------------------------------------
# Fábio Sousa.
# SAVI, December 2022.
# --------------------------------------------------

import cv2
import open3d as o3d
from copy import deepcopy
import numpy as np
from point_cloud_processing import PointCloudProcessing
from matplotlib import cm
from more_itertools import locate

def main():

    #Initial view parameters
    view = {
	"class_name" : "ViewTrajectory",
	"interval" : 29,
	"is_loop" : False,
	"trajectory" :
	[
		{
			"boundingbox_max" : [ 0.90000000000000002, 0.90000000000000002, 0.5 ],
			"boundingbox_min" : [ -0.90000000000000002, -0.90000000000000002, -0.10000000000000003 ],
			"field_of_view" : 60.0,
			"front" : [ 0.57428340315845261, 0.72415504342386261, 0.38183510307530683 ],
			"lookat" : [ -0.23064077816298553, -0.2045093977126011, 0.17408966530741635 ],
			"up" : [ -0.36479928025136604, -0.19118507801017759, 0.91124626258455921 ],
			"zoom" : 0.79999999999999893
		}
	],
	"version_major" : 1,
	"version_minor" : 0
}

    # ------------------------------------------
    # Initialization
    # ------------------------------------------
    p = PointCloudProcessing() #Calls the class
    p.loadPointCloud('../data/scene.ply') #Gives the filename to class

    # ------------------------------------------
    # Execution
    # ------------------------------------------
    p.preProcess(voxel_size=0.01) #PreProcessing

    #?Center the origin in the table
    p.transform(-110, 0, 0, 0, 0, 0) #Rotate in x
    p.transform(0, 0, 52, 0, 0, 0) #Rotate in z
    p.transform(0, 0, 0, 1.1, -0.8, 0.37) #Translation in xyz

    #?Creates a bbox of points to keep
    p.crop(-0.9, -0.9, -0.3, 0.9, 0.9, 0.3)
    #Order: (x,y,z) min and (x,y,z) max

    outliers = p.findPlane() #Find the table plane
    p.inliers.paint_uniform_color([0,1,0]) #Paints the plane in green

    #?Now we isolate the objects (cluster the points for each one)
    cluster_idxs = list(outliers.cluster_dbscan(eps=0.035, min_points=60, print_progress=True))
    #Cluster returns points associated to an ID and gives the same ID for points in the defined range
    #If eps small, no object is going to be detected

    object_idxs = list(set(cluster_idxs))
    object_idxs.remove(-1) #Removes -1 cluster ID (-1 are the points not clustered)

    number_of_objects = len(object_idxs)

    #Color each cluster with a different color using colormap
    colormap = cm.Pastel1(list(range(0,number_of_objects)))

    #Create the objects list
    objects = []

    #Here we find the points for each object and reunite them
    for object_idx in object_idxs:

        #Locate the points, comparing each cluster id to the object id, grouping them and converts the result to list because it's easier
        object_point_idxs = list(locate(cluster_idxs, lambda x: x == object_idx))
        object_points = outliers.select_by_index(object_point_idxs)

        #Create a dictionary to define the objects
        d = {}
        d['idx'] = str(object_idx)
        d['points'] = object_points
        d['color'] = colormap[object_idx, 0:3]
        d['points'].paint_uniform_color(d['color']) #Paints the point in the defined color
        d['center'] = d['points'].get_center()
        objects.append(d) #Add the dict of this object to the list

    # ------------------------------------------
    # Visualization
    # ------------------------------------------

    #Create a list of entities to draw
    entities = []

    #Create a frame with the orthogonal directions
    frame = o3d.geometry.TriangleMesh().create_coordinate_frame(size=0.5, origin=np.array([0., 0., 0.]))
    entities.append(frame)

    # Draw bbox
    bbox_to_draw = o3d.geometry.LineSet.create_from_axis_aligned_bounding_box(p.bbox)
    entities.append(bbox_to_draw)

    #Draw objects
    for object in objects:
        entities.append(object['points'])

    # #Show only object idx = 2
    # for object_idx, object in enumerate(objects):
    #     if object_idx == 2:
    #         entities.append(object['points'])

    #Draws entities and show PointCloud in the defined view
    o3d.visualization.draw_geometries(entities,
                                    zoom=view['trajectory'][0]['zoom'],
                                    front=view['trajectory'][0]['front'],
                                    lookat=view['trajectory'][0]['lookat'],
                                    up=view['trajectory'][0]['up'])

    # ------------------------------------------
    # Termination
    # ------------------------------------------
    if cv2.waitKey(0) == ord('q'):
        exit()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import json
from selenium import webdriver
import re

def save_json_file(data, filename):
    # save data in json file
    with open(filename + '.json', 'w', encoding='utf8') as outfile:
        json.dump(data, outfile)

def read_json_file(filename):
    # read json file and return json object
    data = []
    with open(filename, 'r') as outfile:
        data = json.load(outfile)
    return data

def web_driver():
    # web driver for headless chrome
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('window-size=1200x600')

    driver = webdriver.Chrome(chrome_options=options)
    driver.maximize_window()
    return driver

def get_emails(source):
    # find email in source using regex match
    regex = re.compile('[\w\.-]+@[\w\.-]+\.\w+')
    return [email for email in re.findall(regex, source)]


#Fibonacci Series

def fibprint(n):
    a,b=0,1

    print(a,b,end=" ")
    term=3

    while term<=n:
        c=a+b
        print(c,end=" ")
        a=b
        b=c
        term+=1
    return c #nth number in Fibonacci series
print(fibprint(5)) #3
print(fibprint(60)) #956722026041


''' Programa para rastrear pacotes nos Correios
    Versão: 1.0
'''

from PyRastreamentoCorreios import rastrear
import pandas as pd
import re

while True:
    cod_rastreio = input('Digite o código de rastreamento: ')
    valid_pattern = re.compile("^[A-Za-z]{2}[0-9]{9}[A-Za-z]{2}$")
    '''Nesta validação, verificamos se o código de rastreamento começa com duas letras maiúsculas ([A-Z]{2}),
    seguido de nove dígitos ([0-9]{9}) e termina com mais duas letras maiúsculas ([A-Z]{2}).'''
    if valid_pattern.match(cod_rastreio):
        break
    else:
        print("Código de rastreamento inválido. Por favor, tente novamente.")

statusList = rastrear(cod_rastreio)
# print(statusList)

if len(statusList['status_list']) == 0:
    print('Objeto não encontrado na base de dados dos Correios.')
else:
    df = pd.DataFrame.from_dict(statusList['status_list'])

    df['status'] = df['status'].str.replace("Status: ", "")  #Substitui a palavra "Status: " da célula
    df['data'] = df['data'].str.replace("Data  : ", "")
    df['data'] = df['data'].str.replace("| Hora:", "", regex=True)
    df['local'] = df['local'].str.replace("Local: ", "")
    df.fillna("", inplace=True)  #preencher todas as células com NaN com uma string vazia

    print('\nSeguem os ultimos últimos status do pacote:')

    for i in range(len(df)):
        print(f"{df.iloc[i]['data']}: {df.iloc[i]['status']} | {df.iloc[i]['local']}")

    #print(df.head(2).to_string(index=False))  #Printa as duas primeiras linhas da tabela

    #print(df.to_string()) #Imprime toda a tabela
    #df.to_excel("status_table.xlsx", index=False)  #Gera um arquivo xlsx ta tabela
    #print(statusList['status_list'][0]['status'])

    # Código teste: 'NA869896819BR'

input('\nTecle ENTER para sair')


'''Containts definition of Table class.
'''

import cards

class Table(list):
    '''Represents a set of pairs [bottom<top].
    '''
    def _card_encl(self, card):
        '''Returns '[cA]' if card is cA.
        '''
        return '[' + str(card) + ']'
    def _cover_encl(self, bottom, top):
        '''Returns a cover pair like '[c6<c7]'.
        '''
        return self._card_encl(str(bottom) + '<' + str(top))
    def clear(self):
        '''Removes all cards from the table.
        '''
        del self[:]
    def take_all(self):
        '''Returns all cards from the table in the form of list.
        '''
        all = []
        for x in self:
            if isinstance(x, list):
                all.extend(x)
            else:
                all.append(x)
        self.clear()
        return all
    def put_on_cards(self, cards):
        '''Adds cards on the table as uncovered.
        '''
        for card in cards:
            self.put_on_card(card)
    def put_on_card(self, card):
        '''Adds card on the table as uncovered.
        '''
        self.append(card)
    def get_bottom_cards(self):
        '''Returns list with all bottom cards.
        '''
        bottom_cards = []
        for smth in self:
            if isinstance(smth, list):
                bottom_cards.append(smth[0])
            else:
                bottom_cards.append(smth)
        return bottom_cards
    def has_same_value(self, value):
        '''Returns True if some card on the table
        has the 'value' value. Returns False otherwise.
        '''
        for card in self.convert_to_cards():
            if value == card.get_value():
                return True
        return False
    def get_covering_cards(self):
        '''Returns a list of all cards covering smth.
        '''
        covering_cards = []
        for smth in self:
            if isinstance(smth, list):
                covering_cards.append(smth[1])
        return covering_cards
    def get_covered_cards(self):
        '''Returns a list of all cards covered with smth.
        '''
        covered_smth = []
        for smth in self:
            if isinstance(smth, list):
                covered_smth.append(smth[0])
        return covered_smth
    def get_uncovered_cards(self):
        '''Returns a list of all not covered cards.
        '''
        uncovered_smth = []
        for smth in self:
            if isinstance(smth, cards.Card):
                uncovered_smth.append(smth)
        return uncovered_smth
    def add_retransfered(self, retransfered_cards):
        '''Returns True and adds retransfered_cards to the
        tabe as uncovered if it is possible to add.
        Returns False if it is not.
        '''
        if not self.possible_to_put_cards(retransfered_cards):
            return False
        for card in retransfered_cards:
            self.put_on_card(card)
        return True
    def cover_card(self, bottom, top):
        '''Returns True and covers card bottom with card
        top if bottom is on the table.
        '''
        if bottom in self:
            self.append([self.pop(self.index(bottom)), top])
            return True
        return False
    def __str__(self):
        '''String representation of the table.
        '''
        string = ''
        for x in self:
            if isinstance(x, list):
                string += self._cover_encl(x[0], x[1])
            else:
                string += self._card_encl(x)
        return string
    def has_uncovered_cards(self):
        '''Returns True if the table has uncovered cards.
        False otherwise.
        '''
        for x in self:
            if isinstance(x, cards.Card):
                return True
        return False
    def has_covered_cards(self):
        '''Returns True if the table has covered cards.
        False otherwise.
        '''
        for x in self:
            if isinstance(x, list):
                return True
        return False
    def cover(self, cover_set):
        '''Perform sa cover operation on the table
        for all pairs in the cover_set.
        '''
        for pair in cover_set:
            self.cover_card(pair[0], pair[1])
    def convert_to_cards(self):
        '''Returns all cards on the table
        in one cards.Cards object.
        '''
        list_of_cards = cards.Cards()
        for x in self:
            if isinstance(x, cards.Card):
                list_of_cards.append(x)
            else:
                list_of_cards.extend(x)
        return list_of_cards
    def possible_to_throw_on(self, card):
        '''Returns True if it is possible to throw on card
        on the table.
        '''
        if not self.is_empty():
            value = card.get_value()
            for on_table in self.convert_to_cards():
                if on_table.get_value() == value:
                    return True
        return False
    def possible_to_put_cards(self, to_put):
        '''Returns True if to_put is possible to put on the table.
        '''
        for i in range(len(to_put) - 1):
            if to_put[i].get_value() != to_put[i + 1].get_value():
                return False
        return True
    def get_number_of_uncovered_cards(self):
        '''Returns number of uncovered cards on the table.
        '''
        num = 0
        for x in self:
            if isinstance(x, cards.Card):
                num = num + 1
        return num
    def get_number_of_items(self):
        '''Returns number of cover pairs and not covered cards.
        '''
        return len(self)
    def get_number_of_cards(self):
        '''Returns number of cards on the table.
        '''
        number = 0
        for elem in self:
            if isinstance(elem, cards.Card):
                number += 1
            else:
                number += 2
        return number
    def has_card(self, card):
        '''Returns True if the table has card.
        Returns False otherwise.
        '''
        for x in self:
            if isinstance(x, list):
                if x[0] == card or x[1] == card:
                    return True
            else:
                if x == card:
                    return True
        return False
    def has_as_covered(self, card):
        '''Return True if the table has card as covered.
        Returns False otherwise.
        '''
        for x in self:
            if isinstance(x, list):
                if x[0] == card:
                    return True
        return False
    def has_as_covering(self, card):
        '''Return True if the table has card as covering.
        Returns False otherwise.
        '''
        for x in self:
            if isinstance(x, list):
                if x[1] == card:
                    return True
        return False
    def has_as_not_covered(self, card):
        '''Return True if the table has card as not covered.
        Returns False otherwise.
        '''
        for x in self:
            if isinstance(x, cards.Card):
                if x == card:
                    return True
        return False
    def is_empty(self):
        '''Returns True if the table is empty.
        Returns False otherwise.
        '''
        return self.get_number_of_items() == 0
    def __repr__(self):
        '''Representation of the object.
        '''
        return self.__str__()


import pygame

class Cloud:

    def __init__( self, x, y, width, height ):
        self.mX = x
        self.mY = y
        self.mWidth = width
        self.mHeight = height
        self.mColor = ( 251, 200, 122 )
        return

    def darken( self ):
        r, g, b = self.mColor
        r *= 0.9
        g *= 0.9
        b *= 0.9
        self.mColor = (int(r),int(g),int(b))
        return

    def lighten( self ):
        r, g, b = self.mColor
        r *= 1.1
        g *= 1.1
        b *= 1.1
        self.mColor = (min(int(r),255), min(int(g),255), min(int(b),255) )
        return

    def evolve( self, dt ):
        return

    def draw( self, surface ):

        rect = pygame.Rect( int ( self.mX ), int ( self.mY ), int ( self.mWidth ), int ( self.mHeight ) )
        pygame.draw.ellipse( surface, self.mColor, rect, 0 )

        return