from common import *
import numpy as np
from collections import deque

class Player:
    def __init__(self, is_bot, x_start=20, y_start=20, start_direction=Direction.RIGHT, color=(255,255,255)):
        self._X_START = x_start
        self._Y_START = y_start
        self._START_DIRECTION = start_direction

        self.alive = True
        self.direction = start_direction
        self.x = x_start
        self.y = y_start
        self.xs = []
        self.ys = []
        self.color = color
        self.is_bot = is_bot

    def moveRight(self):
        self.direction = Direction.RIGHT

    def moveLeft(self):
        self.direction = Direction.LEFT

    def moveUp(self):
        self.direction = Direction.UP

    def moveDown(self):
        self.direction = Direction.DOWN

    def addBlock(self):
        self.xs.append(self.x)
        self.ys.append(self.y)
        if self.direction == Direction.RIGHT:
            self.x = self.x + step_size
        elif self.direction == Direction.LEFT:
            self.x = self.x - step_size
        elif self.direction == Direction.UP:
            self.y = self.y - step_size
        else: # self.direction == Direction.DOWN:
            self.y = self.y + step_size

    ## Start BOT methods #####################################################################################################
    def _get_next(self, player, windowWidth, windowHeight):
        # assume player (except self) continues a step in each direction, to prevent head on collisions and ties
        ns = []
        if player.x != self.x:
            #  if player.direction == Direction.RIGHT:
            ns.append([min(player.x + step_size, windowWidth - step_size), player.y])
            #  yNext.append(player.y)
            #  elif player.direction == Direction.LEFT:
            ns.append([max(player.x - step_size, 0), player.y])
            #  yNext.append(player.y)
            #  elif player.direction == Direction.UP:
            ns.append([player.x, max(player.y - step_size, 0)])
            #  yNext.append(max(player.y - step_size, 0))
            #  else: # player.direction == Direction.DOWN
            #  xNext.append(player.x)
            ns.append([player.x, min(player.y + step_size, windowHeight - step_size)])
        return ns

    # return each direction bot can go in without killing himself immediately
    def _get_valid_directions(self, board, windowWidth, windowHeight):
        valid_directions = []
        if self.x != 0 and not board[ind(self.x-step_size, self.y)]:
            valid_directions.append(Direction.LEFT)
        if self.x+step_size != windowWidth and not board[ind(self.x+step_size, self.y)]:
            valid_directions.append(Direction.RIGHT)
        if self.y != 0 and not board[ind(self.x, self.y-step_size)]:
            valid_directions.append(Direction.UP)
        if self.y+step_size != windowHeight and not board[ind(self.x, self.y+step_size)]:
            valid_directions.append(Direction.DOWN)
        return valid_directions

    def _bfs_score(self, start, board, direc, numSteps, nextFive=None):
        visited = np.full(board.shape, False)
        q = deque()

        score = 0
        # Append nodes of the form (distance, coordinate)
        dist = 0
        q.append((dist, start))
        while q and dist < numSteps:
            node = q.popleft()
            dist = node[0]
            block = node[1]
            #  f.write(",".join(map(str, block)) + "\n")
            #  f.write(str(board.shape) + "\n")

            left = (block[0]-1, block[1])
            right = (block[0]+1, block[1])
            up = (block[0], block[1]-1)
            down = (block[0], block[1]+1)

            #  f.write(",".join(map(str, left)) + " ")
            #  f.write(",".join(map(str, right)) + " ")
            #  f.write(",".join(map(str, up)) + " ")
            #  f.write(",".join(map(str, down)) + "\n")
            numChoices = 0
            if block[0] != 0 and not board[left]:
                numChoices += 1
                if not visited[left]:
                    visited[left] = True
                    score += 1
                    q.append((dist+1, left))

            if block[0] != board.shape[0] - 1 and not board[right]:
                numChoices += 1
                if not visited[right]:
                    visited[right] = True
                    score += 1
                    q.append((dist+1, right))

            if block[1] != 0 and not board[up]:
                numChoices += 1
                if not visited[up]:
                    visited[up] = True
                    score += 1
                    q.append((dist+1, up))

            if block[1] != board.shape[1] - 1 and not board[down]:
                numChoices += 1
                if not visited[down]:
                    visited[down] = True
                    score += 1
                    q.append((dist+1, down))
            # discourage going down one lane paths (no escape)
            if numChoices < 2:
                score -= 5

        # encourage cutting players off
        if nextFive:
            snf = []
            if direc == Direction.LEFT:
                for i in range(0, 5):
                    if start[0] - i < 0:
                        break
                    n = (start[0] - i, start[1])
                    if i == 0 or not board[n]: snf.append(n)
                    else: break
            elif direc == Direction.RIGHT:
                for i in range(0, 5):
                    if start[0] + i > board.shape[0] - 1:
                        break
                    n = (start[0] + i, start[1])
                    if i == 0 or not board[n]: snf.append(n)
                    else: break
            elif direc == Direction.UP:
                for i in range(0, 5):
                    if start[1] - i < 0:
                        break
                    n = (start[0], start[1] - i)
                    if i == 0 or not board[n]: snf.append(n)
                    else: break
            else:
                for i in range(0,5):
                    if start[1] + i > board.shape[1] - 1:
                        break
                    n = (start[0], start[1] + i)
                    if i == 0 or not board[n]: snf.append(n)
                    else: break
            #  print("dir " + str(direc) + " snf:")
            #  print(snf) # DEBUG
            #  print("nf")
            #  print(nextFive)
            for nf in nextFive:
                for i in range(len(nf)):
                    pos = nf[i]
                    if pos in snf and snf.index(pos) <= i:
                        score += 1000
                        #  print('cutoff')

        return score

    def _get_next_five(self, board, players, windowWidth, windowHeight):
        nfs = []
        for player in players:
            nf = []
            if player.x == self.x and player.y == self.y:
                continue
            if player.direction == Direction.LEFT:
                for i in range(2, 6):
                    if player.x - (step_size * i) < 0:
                        break
                    n = ind(max(player.x - (step_size * i), 0), player.y)
                    if not board[n]: nf.append(n)
                    else:
                        break
            elif player.direction == Direction.RIGHT:
                for i in range(2, 6):
                    if player.x + (step_size * i) > windowWidth - step_size:
                        break
                    n = ind(min(player.x + (step_size * i), windowWidth - step_size), player.y)
                    if not board[n]: nf.append(n)
                    else:
                        break
            elif player.direction == Direction.UP:
                for i in range(2, 6):
                    if player.y - (step_size * i) < 0:
                        break
                    n = ind(player.x, max(player.y - (step_size * i), 0))
                    if not board[n]: nf.append(n)
                    else:
                        break
            else:
                for i in range(2, 6):
                    if player.y + (step_size * i) > windowHeight - step_size:
                        break
                    n = ind(player.x, min(player.y + (step_size * i), windowHeight - step_size))
                    if not board[n]: nf.append(n)
                    else:
                        break
            nfs.append(nf)
        return nfs

    def _get_score(self, board, start, players, nextFive, direc):
        self_score = self._bfs_score(start, board, direc, 101, nextFive)
        return self_score

    def update(self, board, players, windowWidth, windowHeight):
        # do nothing if player is human
        if not self.is_bot:
            return

        # initialize preferences to -1000
        directions = {
            Direction.LEFT: float('-inf'),
            Direction.RIGHT: float('-inf'),
            Direction.UP: float('-inf'),
            Direction.DOWN: float('-inf')
        }

        # assume all players (except self) continue one step in each direction to avoid head-on collisions
        coords = []
        old = []
        for player in players:
            ns = self._get_next(player, windowWidth, windowHeight)
            for n in ns:
                i = ind(n[0], n[1])
                old.append(board[i]) # keep track of what board used to be so we can set it back
                coords.append(i)
        for coord in coords:
            board[coord] = True

        # get next five straight moves for all players (except self)
        nextFive = self._get_next_five(board, players, windowWidth, windowHeight)
        #  print(nextFive) # DEBUG

        validDirections = self._get_valid_directions(board, windowWidth, windowHeight)
        for direction in validDirections:
            start = None
            if direction == Direction.UP:
                start = ind(self.x, self.y-step_size)
            elif direction == Direction.LEFT:
                start = ind(self.x-step_size, self.y)
            elif direction == Direction.RIGHT:
                start = ind(self.x+step_size, self.y)
            elif direction == Direction.DOWN:
                start = ind(self.x, self.y+step_size)
            board[start] = True
            directions[direction] = self._get_score(board, start, players, nextFive, direction)
            board[start] = False

        # set board back
        for j in range(len(coords)):
            board[coords[j]] = old[j]

        # if the best direction is "splitting" ie it will divide the board into two halves, discourage it
        if directions[Direction.UP] > 0 and (self.y <= step_size or board[ind(self.x, self.y-step_size*2)]) \
                and Direction.LEFT in validDirections and Direction.RIGHT in validDirections:
            #  print('up split') # debug
            directions[Direction.UP] /= 2
        if directions[Direction.LEFT] > 0 and (self.x <= step_size or board[ind(self.x-step_size*2, self.y)]) \
                and Direction.UP in validDirections and Direction.DOWN in validDirections:
            #  print('left split') # debug
            directions[Direction.LEFT] /= 2
        if directions[Direction.RIGHT] > 0 and (self.x >= windowWidth - step_size*2 or \
                board[ind(self.x+step_size*2, self.y)]) and Direction.UP in validDirections \
                and Direction.DOWN in validDirections:
            #  print('right split') # debug
            directions[Direction.RIGHT] /= 2
        if directions[Direction.DOWN] > 0 and (self.y >= windowHeight - step_size*2 or \
                board[ind(self.x, self.y+step_size*2)]) and Direction.LEFT in validDirections and \
                Direction.RIGHT in validDirections:
            directions[Direction.DOWN] /= 2
            #  print('down split') # debug

        # encourage going in the same direction
        directions[self.direction] *= 1.05

        self.direction = max(directions, key=directions.get)
        #  print(str(directions)) # DEBUG


from corehq.apps.sms.forms import BackendForm
from corehq.apps.sms.mixin import apply_leniency
from corehq.apps.sms.util import validate_phone_number
from corehq.apps.hqwebapp import crispy as hqcrispy
from crispy_forms import layout as crispy
from crispy_forms.bootstrap import StrictButton, FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, HTML
from dimagi.utils.django.fields import TrimmedCharField
from django.core.exceptions import ValidationError
from django.forms.fields import ChoiceField
from django.forms.forms import Form
from django.utils.translation import gettext as _, gettext_lazy

class TelerivetBackendForm(BackendForm):
    api_key = TrimmedCharField(
        label=gettext_lazy("API Key"),
    )
    project_id = TrimmedCharField(
        label=gettext_lazy("Project ID"),
    )
    phone_id = TrimmedCharField(
        label=gettext_lazy("Phone ID"),
    )
    webhook_secret = TrimmedCharField(
        label=gettext_lazy("Webhook Secret"),
    )

    def __init__(self, *args, **kwargs):
        super(TelerivetBackendForm, self).__init__(*args, **kwargs)

        if self.backend_id:
            # Don't allow editing the webhook secret.
            # Django ensures that posted values don't change the value here.
            self.fields['webhook_secret'].disabled = True

    @property
    def gateway_specific_fields(self):
        return crispy.Fieldset(
            _("Telerivet (Android) Settings"),
            'api_key',
            'project_id',
            'phone_id',
            'webhook_secret',
        )

    def clean_webhook_secret(self):
        # Circular import
        from corehq.messaging.smsbackends.telerivet.models import SQLTelerivetBackend
        value = self.cleaned_data['webhook_secret']
        backend = SQLTelerivetBackend.by_webhook_secret(value)
        if backend and backend.pk != self.backend_id:
            raise ValidationError(_("Already in use."))
        return value

class TelerivetOutgoingSMSForm(Form):
    api_key = TrimmedCharField(
        label=gettext_lazy("API Key"),
        required=True
    )
    project_id = TrimmedCharField(
        label=gettext_lazy("Project ID"),
        required=True
    )
    phone_id = TrimmedCharField(
        label=gettext_lazy("Phone ID"),
        required=True
    )

    def __init__(self, *args, **kwargs):
        super(TelerivetOutgoingSMSForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-2 col-md-1'
        self.helper.field_class = 'col-sm-4 col-md-3'
        self.helper.layout = Layout(
            Div(
                hqcrispy.B3MultiField(
                    _("API Key"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'api_key',
                            data_bind='value: apiKey',
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: apiKeyError, text: apiKeyError",
                    ),
                    data_bind="css: {'has-error': apiKeyError}",
                ),
                hqcrispy.B3MultiField(
                    _("Project ID"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'project_id',
                            data_bind='value: projectId',
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: projectIdError, text: projectIdError",
                    ),
                    data_bind="css: {'has-error': projectIdError}",
                ),
                hqcrispy.B3MultiField(
                    _("Phone ID"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'phone_id',
                            data_bind='value: phoneId',
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: phoneIdError, text: phoneIdError",
                    ),
                    data_bind="css: {'has-error': phoneIdError}",
                )
            )
        )

class TelerivetPhoneNumberForm(Form):
    test_phone_number = TrimmedCharField(
        required=True,
        label=gettext_lazy("+ (Country Code) Phone Number")
    )

    def __init__(self, *args, **kwargs):
        super(TelerivetPhoneNumberForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-2 col-md-1'
        self.helper.field_class = 'col-sm-4 col-md-3'
        self.helper.layout = Layout(
            Div(
                hqcrispy.B3MultiField(
                    _("Test Phone Number"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'test_phone_number',
                            data_bind='value: testPhoneNumber',
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: testPhoneNumberError, text: testPhoneNumberError",
                    ),
                    Div(
                        StrictButton(
                            "",
                            id='id_send_sms_button',
                            css_class='btn',
                            data_bind="text: sendSmsButtonText, click: sendTestSMS, "
                                      "css: {'btn-primary': !sendSmsButtonError(), "
                                      "'btn-danger': sendSmsButtonError()}",
                        )
                    ),
                    data_bind="css: {'has-error': testPhoneNumberError}",
                )
            )
        )

    def clean_test_phone_number(self):
        value = self.cleaned_data.get('test_phone_number')
        value = apply_leniency(value)
        validate_phone_number(value,
            error_message=_("Please enter digits only, in international format (country code and phone number)."))
        return value

class FinalizeGatewaySetupForm(Form):
    YES = 'Y'
    NO = 'N'

    YES_NO_CHOICES = (
        (YES, gettext_lazy("Yes")),
        (NO, gettext_lazy("No")),
    )

    name = TrimmedCharField(
        label=gettext_lazy("Name"),
        required=True
    )
    set_as_default = ChoiceField(
        label=gettext_lazy("Set as default gateway"),
        choices=YES_NO_CHOICES,
        required=True
    )

    def __init__(self, *args, **kwargs):
        super(FinalizeGatewaySetupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form form-horizontal'
        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-3 col-md-2'
        self.helper.layout = Layout(
            Div(
                hqcrispy.B3MultiField(
                    _("Name"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'name',
                            data_bind='value: name',
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: nameError, text: nameError",
                    ),
                    data_bind="css: {'has-error': nameError}",
                ),
                hqcrispy.B3MultiField(
                    _("Set as default gateway"),
                    Div(
                        hqcrispy.MultiInlineField(
                            'set_as_default',
                            data_bind='value: setAsDefault',
                            style='margin-left: 0px;'
                        )
                    ),
                    crispy.Div(
                        css_class="help-block",
                        data_bind="visible: setAsDefaultError, text: setAsDefaultError",
                    ),
                    data_bind="css: {'has-error': setAsDefaultError}",
                ),
                FormActions(
                    StrictButton(
                        "",
                        id="id_create_backend",
                        css_class='btn-primary',
                        data_bind="text: backendButtonText, click: createBackend, disable: creatingBackend,"
                                  "css: {'btn-primary': !backendButtonError(), "
                                  "'btn-danger': backendButtonError()}",
                    )
                )
            )
        )


#socket_echo_server.py

import socket,errno
import sys

def getPort():

    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    port=8200

    while True:

        # Bind the socket to the port
        server_address = ('localhost', port)
        #print('starting up on {} port {}'.format(*server_address))

        try:
            sock.bind(server_address)
            print (port)
            sock.close()  # closing, I will reopen it afterwards
            return port
            exit()

        except socket.error as e:
            if e.errno == errno.EADDRINUSE:
                #print("Port",port," is already in use,trying ",port+1)
                port+=1

            else:
                # something else raised the socket.error exception
                print(e)

            exit()
    return None

if __name__ == '__main__':
    getPort()


import os
import shutil

from tqdm import tqdm

from ....distributed.group import is_distributed
from ....logger import get_logger
from ....serialization import load, save
from .folder import ImageFolder
from .utils import _default_dataset_root, calculate_md5, untar, untargz

logger = get_logger(__name__)

class ImageNet(ImageFolder):
    r"""Load ImageNet from raw files or folder. Expected folder looks like:

    .. code-block:: shell

        ${root}/
        |       [REQUIRED TAR FILES]
        |-  ILSVRC2012_img_train.tar
        |-  ILSVRC2012_img_val.tar
        |-  ILSVRC2012_devkit_t12.tar.gz
        |       [OPTIONAL IMAGE FOLDERS]
        |-  train/cls/xxx.${img_ext}
        |-  val/cls/xxx.${img_ext}
        |-  ILSVRC2012_devkit_t12/data/meta.mat
        |-  ILSVRC2012_devkit_t12/data/ILSVRC2012_validation_ground_truth.txt

    If the image folders don't exist, raw tar files are required to get extracted and processed.

        * if ``root`` contains ``self.target_folder`` depending on ``train``:

          * initialize ImageFolder with target_folder.

        * else:

          * if all raw files are in ``root``:

            * parse ``self.target_folder`` from raw files.
            * initialize ImageFolder with ``self.target_folder``.

          * else:

            * raise error.

    Args:
        root: root directory of imagenet data, if root is ``None``, use default_dataset_root.
        train: if ``True``, load the train split, otherwise load the validation split.

    """

    raw_file_meta = {
        "train": ("ILSVRC2012_img_train.tar", "1d675b47d978889d74fa0da5fadfb00e"),
        "val": ("ILSVRC2012_img_val.tar", "29b22e2961454d5413ddabcf34fc5622"),
        "devkit": ("ILSVRC2012_devkit_t12.tar.gz", "fa75699e90414af021442c21a62c3abf"),
    }  # ImageNet raw files
    default_train_dir = "train"
    default_val_dir = "val"
    default_devkit_dir = "ILSVRC2012_devkit_t12"

    def __init__(self, root: str = None, train: bool = True, **kwargs):
        # process the root path
        if root is None:
            self.root = self._default_root
        else:
            self.root = root

        if not os.path.exists(self.root):
            raise FileNotFoundError("dir %s does not exist" % self.root)

        self.devkit_dir = os.path.join(self.root, self.default_devkit_dir)

        if not os.path.exists(self.devkit_dir):
            logger.warning("devkit directory %s does not exists", self.devkit_dir)
            self._prepare_devkit()

        self.train = train

        if train:
            self.target_folder = os.path.join(self.root, self.default_train_dir)
        else:
            self.target_folder = os.path.join(self.root, self.default_val_dir)

        if not os.path.exists(self.target_folder):
            logger.warning(
                "expected image folder %s does not exist, try to load from raw file",
                self.target_folder,
            )
            if not self.check_raw_file():
                raise FileNotFoundError(
                    "expected image folder %s does not exist, and raw files do not exist in %s"
                    % (self.target_folder, self.root)
                )
            elif is_distributed():
                raise RuntimeError(
                    "extracting raw file shouldn't be done in distributed mode, use single process instead"
                )
            elif train:
                self._prepare_train()
            else:
                self._prepare_val()

        super().__init__(self.target_folder, **kwargs)

    @property
    def _default_root(self):
        return os.path.join(_default_dataset_root(), self.__class__.__name__)

    @property
    def valid_ground_truth(self):
        groud_truth_path = os.path.join(
            self.devkit_dir, "data", "ILSVRC2012_validation_ground_truth.txt"
        )
        if os.path.exists(groud_truth_path):
            with open(groud_truth_path, "r") as f:
                val_labels = f.readlines()
                return [int(val_label) for val_label in val_labels]
        else:
            raise FileNotFoundError(
                "valid ground truth file %s does not exist" % groud_truth_path
            )

    @property
    def meta(self):
        try:
            return load(os.path.join(self.devkit_dir, "meta.pkl"))
        except FileNotFoundError:
            import scipy.io

            meta_path = os.path.join(self.devkit_dir, "data", "meta.mat")
            if not os.path.exists(meta_path):
                raise FileNotFoundError("meta file %s does not exist" % meta_path)
            meta = scipy.io.loadmat(meta_path, squeeze_me=True)["synsets"]
            nums_children = list(zip(*meta))[4]
            meta = [
                meta[idx]
                for idx, num_children in enumerate(nums_children)
                if num_children == 0
            ]
            idcs, wnids, classes = list(zip(*meta))[:3]
            classes = [tuple(clss.split(", ")) for clss in classes]
            idx_to_wnid = dict(zip(idcs, wnids))
            wnid_to_classes = dict(zip(wnids, classes))
            logger.info(
                "saving cached meta file to %s",
                os.path.join(self.devkit_dir, "meta.pkl"),
            )
            save(
                (idx_to_wnid, wnid_to_classes),
                os.path.join(self.devkit_dir, "meta.pkl"),
            )
            return idx_to_wnid, wnid_to_classes

    def check_raw_file(self) -> bool:
        return all(
            [
                os.path.exists(os.path.join(self.root, value[0]))
                for _, value in self.raw_file_meta.items()
            ]
        )

    def _organize_val_data(self):
        id2wnid = self.meta[0]
        val_idcs = self.valid_ground_truth
        val_wnids = [id2wnid[idx] for idx in val_idcs]

        val_images = sorted(
            [
                os.path.join(self.target_folder, image)
                for image in os.listdir(self.target_folder)
            ]
        )

        logger.debug("mkdir for val set wnids")
        for wnid in set(val_wnids):
            os.makedirs(os.path.join(self.root, self.default_val_dir, wnid))

        logger.debug("mv val images into wnids dir")
        for wnid, img_file in tqdm(zip(val_wnids, val_images)):
            shutil.move(
                img_file,
                os.path.join(
                    self.root, self.default_val_dir, wnid, os.path.basename(img_file)
                ),
            )

    def _prepare_val(self):
        assert not self.train
        raw_filename, checksum = self.raw_file_meta["val"]
        raw_file = os.path.join(self.root, raw_filename)
        logger.info("checksum valid tar file %s ...", raw_file)
        assert (
            calculate_md5(raw_file) == checksum
        ), "checksum mismatch, {} may be damaged".format(raw_file)
        logger.info("extract valid tar file... this may take 10-20 minutes")
        untar(raw_file, self.target_folder)
        self._organize_val_data()

    def _prepare_train(self):
        assert self.train
        raw_filename, checksum = self.raw_file_meta["train"]
        raw_file = os.path.join(self.root, raw_filename)
        logger.info("checksum train tar file %s ...", raw_file)
        assert (
            calculate_md5(raw_file) == checksum
        ), "checksum mismatch, {} may be damaged".format(raw_file)
        logger.info("extract train tar file.. this may take several hours")
        untar(raw_file, self.target_folder)
        paths = [
            os.path.join(self.target_folder, child_dir)
            for child_dir in os.listdir(self.target_folder)
        ]
        for path in tqdm(paths):
            untar(path, os.path.splitext(path)[0], remove=True)

    def _prepare_devkit(self):
        raw_filename, checksum = self.raw_file_meta["devkit"]
        raw_file = os.path.join(self.root, raw_filename)
        logger.info("checksum devkit tar file %s ...", raw_file)
        assert (
            calculate_md5(raw_file) == checksum
        ), "checksum mismatch, {} may be damaged".format(raw_file)
        logger.info("extract devkit file..")
        untargz(os.path.join(self.root, self.raw_file_meta["devkit"][0]))


#Euler Project Problem 28: Number spiral diagonals

asum=1
num=1

for a in range(1,501):

    for b in range(0,4):

        num=num+2*a

        asum=asum+num

print(asum)


import tkinter
import customtkinter as ctk
import customtkinter
from utils.layout.front import *
import os
from banco_conections.conexao import *
from banco_conections.conexao_forncedores import query_fornecedor
from PIL import ImageTk, Image
from banco_conections.conexao_categorias import query_categoria

def cad_categoria():
    janela_categoria = customtkinter.CTkToplevel()
    janela_categoria.attributes("-topmost", True)
    janela_categoria.title("Cadastro de Categoria")
    janela_categoria.after(200, lambda: janela_categoria.iconbitmap("./imagens/logo_icone.ico")) # alterando o icone da janela
    janela_categoria.geometry("1000x550+250+70")
    janela_categoria.resizable(False, False)
    janela_categoria.grid_rowconfigure(0, weight=1)
    janela_categoria.grid_columnconfigure(1, weight=1)

    # Inserindo as imagens que serão utilizadas
    image_path = os.path.join(os.path.dirname(os.path.realpath(
        __file__)), "C:/sistema_estoque/imagens")

    background_image = customtkinter.CTkImage(dark_image=Image.open(
    os.path.join(image_path, "background_fornecedor.png")), size=(1000, 550))

    # Inserindo imagem de fundo
    label_background = customtkinter.CTkLabel(master=janela_categoria,
                                          text="",
                                          image=background_image)
    label_background.pack()

    label_combobox = customtkinter.CTkLabel(master=janela_categoria,
                                             text="SEGMENTO",
                                             font=('Poppins bold', 13),
                                             width=40,
                                             height=20,
                                             fg_color=co4,
                                             bg_color="transparent")
    label_combobox.place(x=330, y=150, anchor=tkinter.CENTER)

    #Caixa para selecionar segmento
    global var_combobox
    combobox = customtkinter.CTkOptionMenu(master=janela_categoria,
                                       values=["Alimentos", "Bebida", "Papelaria", "Informatica", "Cosmeticos", "Outros"])
    combobox.configure(fg_color=co0, width=180, height=30)
    combobox.set("Informatica")  # setando valor inicial
    combobox.place(x=294, y=168)
    var_combobox = combobox.get()

    label_categoria = customtkinter.CTkLabel(master=janela_categoria,
                                             text="CATEGORIA",
                                             font=('Poppins bold', 13),
                                             width=40,
                                             height=20,
                                             fg_color=co4,
                                             bg_color="transparent")
    label_categoria.place(x=600, y=150, anchor=tkinter.CENTER)

    # Criando e configurando a entry categoria
    entry_categoria = customtkinter.CTkEntry(master=janela_categoria,
                                        width=250,
                                        height=30,
                                        font=('Century gothic', 13),
                                        fg_color="transparent",
                                        bg_color="transparent",
                                        border_color=co0,
                                        placeholder_text='Insira o nome da categoria',
                                        justify='center')
    entry_categoria.place(x=687, y=183, anchor=tkinter.CENTER)

    def armazenar_categoria():

        global var_categoria
        var_categoria = entry_categoria.get()
    armazenar_categoria

    def clean_entryc():
        entry_categoria.delete(0, "end")
    clean_entryc

    # Criando e configurando o botão cadastrar
    button_cadastrar = customtkinter.CTkButton(master=janela_categoria, text="CADASTRAR",
                                            width=15,
                                            height=15,
                                            font=('Poppins Bold', 15),
                                            fg_color=co4,
                                            hover_color=co2,
                                            bg_color=co4,
                                            cursor='hand2')

    button_cadastrar.place(x=520, y=270, anchor=tkinter.CENTER)

    # Cadastrando as infomações do fornecedor no banco de dados
    button_cadastrar.configure(command=lambda:[armazenar_categoria(), query_categoria(), clean_entryc()])

    janela_categoria.mainloop()

cad_categoria


import datetime
import whisper
import json
filename = "example"
model = whisper.load_model("base")
result = model.transcribe(f"{filename}.mp3")
print(result)
with open("{}.txt".format(filename), "w") as f:
  f.write(result["text"])

with open("{}.json".format(filename), "w", encoding="utf-8") as f:
  json.dump(result, f, ensure_ascii=False)
withTime = {}

for segment in result["segments"]:
   withTime[str(datetime.timedelta(seconds=segment["start"])).split(".")[0]] = segment["text"]

with open("{}.json".format("withTime"), "w", encoding="utf-8") as f:
  json.dump(withTime, f, ensure_ascii=False)


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

from datetime import datetime
from flask import render_template

from TgwlDataCenter import db
from TgwlDataCenter.models import Fruit
from TgwlDataCenter.main import main

@main.route('/')
@main.route('/home')
def home():
    """Renders the home page."""
    fruit = Fruit(fruit=u"苹果")
    db.session.add(fruit)
    db.session.commit()
    return render_template(
        'index.html',
        title='Home Page',
        year=datetime.now().year,
    )

@main.route('/contact')
def contact():
    """Renders the contact page."""
    return render_template(
        'contact.html',
        title='Contact',
        year=datetime.now().year,
        message='Your contact page.'
    )

@main.route('/about')
def about():
    """Renders the about page."""
    return render_template(
        'about.html',
        title='About',
        year=datetime.now().year,
        message='Your application description page.'
    )


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

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
    QgsMapLayer,
    QgsProcessing,
    QgsFeatureSink,
    QgsProcessingAlgorithm,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterDefinition,
    QgsProcessingParameterMapLayer,
    QgsProcessingParameterMultipleLayers,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterFeatureSink,
    QgsProcessingParameterRasterLayer,
    QgsWkbTypes,
    QgsProcessingParameterNumber,
    QgsFields,
    QgsField,
    QgsCoordinateTransform,
    QgsProject,
    QgsFeature,
    QgsProcessingParameterVectorLayer,
    )
from qgis.PyQt.QtCore import QVariant
from VeloRouteScripts.distance_framework import DistanceCalculateFramework
from VeloRouteScripts import utils

class DistanceCalculateAlgorithm(QgsProcessingAlgorithm):
    """
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    PATHS_OUTPUT = 'PATHS_OUTPUT'
    SIGN_INPUT = 'SIGN_INPUT'
    MAIN_ROAD_INPUT = 'MAIN_ROAD_INPUT'
    SECONDARY_ROAD_INPUT = 'SECONDARY_ROAD_INPUT'
    POIS_INPUT = 'POIS_INPUT'
    HEIGHTS_INPUT = 'HEIGHTS_INPUT'
    TOLERANCE = 'TOLERANCE'

    def initAlgorithm(self, config):
        main_route_layer = utils.get_main_road_layer()
        main_route_layer_name = main_route_layer.name() if main_route_layer else None
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.SIGN_INPUT,
                self.tr('Слой с носителями'),
                types = [QgsProcessing.TypeVectorPoint],
                defaultValue = '123_DIR'
            )
        )
        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                self.POIS_INPUT,
                self.tr('Слои с объектами'),
                QgsProcessing.TypeVectorPoint,
                defaultValue = ['POI', 'locality', 'transport', 'services']
            )
        )
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.MAIN_ROAD_INPUT,
                self.tr('Слой с главными дорогами'),
                types = [QgsProcessing.TypeVectorLine],
                defaultValue = main_route_layer_name
            )
        )
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.SECONDARY_ROAD_INPUT,
                self.tr('Слой с доп. дорогами'),
                types = [QgsProcessing.TypeVectorLine],
                defaultValue = 'secondary_routes',
                optional=True,
            )
        )
        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.HEIGHTS_INPUT,
                self.tr('Слой с картой высот рельефа'),
                optional=True,
            )
        )
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.PATHS_OUTPUT,
                self.tr('Итоговый слой с кратчайшими путями'),
                type=QgsProcessing.TypeVectorLine
            )
        )

        advanced_params = []
        advanced_params.append(QgsProcessingParameterNumber(self.TOLERANCE,
                                                   self.tr('Topology tolerance'),
                                                   QgsProcessingParameterNumber.Double,
                                                   0.0, False, 0, 99999999.99))
        for p in advanced_params:
            p.setFlags(p.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
            self.addParameter(p)

    def processAlgorithm(self, parameters, context, feedback):
        sign_layer = self.parameterAsLayer(parameters, self.SIGN_INPUT, context)
        main_road_layer = self.parameterAsLayer(parameters, self.MAIN_ROAD_INPUT, context)
        secondary_road_layer = self.parameterAsLayer(parameters, self.SECONDARY_ROAD_INPUT, context)
        poi_layers = self.parameterAsLayerList(parameters, self.POIS_INPUT, context)
        height_layer = self.parameterAsRasterLayer(parameters, self.HEIGHTS_INPUT, context)
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE, context)

        framework = DistanceCalculateFramework(
            sign_layer,
            poi_layers,
            main_road_layer,
            secondary_road_layer,
            height_layer,
            tolerance,
            feedback
            )

        path_sink, path_dest_id = self.parameterAsSink(parameters, self.PATHS_OUTPUT,
                context, framework.output_fields, QgsWkbTypes.LineString, framework.TARGET_CRS)

        for i, path_feature in enumerate(framework.main()):
            path_feature['id'] = i
            path_sink.addFeature(path_feature, QgsFeatureSink.FastInsert)
        return {self.PATHS_OUTPUT: path_dest_id}

    def name(self):
        return 'distance_calculate'

    def displayName(self):
        return 'Расчет расстояний'

    def group(self):
        return 'Веломаршрут'

    def groupId(self):
        return 'Group1'

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return DistanceCalculateAlgorithm()

    def shortHelpString(self):
        return "Параметры
"\
                "
Слой с носителями - слой, от объектов которого будут "\
                "начинаться расчеты кратчайших путей
"\
                "
Слой с объектами - слои, в которых будут искаться объекты "\
                "по названию и до которых будет считаться маршрут (в том числе сервисы)
"\
                "
Слой с главными дорогами - основной маршрут сети передвижения, "\
                "в котором обозначены коды участков
"\
                "
Слой с доп.дорогами - слой, в котором обозначены второстепенные "\
                "участки дороги, также используется для построение сети передвижения
"\
                "
Слой с картой высот рельефа - растровый слой, в котором значение пикселя "\
                "соответствует высоте рельефа от уровня моря (с сайта USGS Earthexplorer, алгоритм mean)
"\
                "
Topology tolerance - степень “сшивания” дорожной сети. Если все "\
                "сопряжения всех участков лежат точно на полилиниях, то значения оставить как 0
"\
                "
"\
                "Результат
"\
                "
Будет создан слой с линиями кратчайших путей. Он поможет отслеживать "\
                "корректность работы алгоритма, а также посмотреть рассчитанные длины путей (2d - без учета рельефа, 3d - с учетом)
"\
                "
В аттрибутивке слоя носителей обновятся значения для параметров типа: "\
                "PIC, km, NameEn, а так же присвоен код ближайшего участка
"\
                "
"


import random, sys

print('ROCK, PAPER, SCISSORS')

wins = 0
losses = 0
ties = 0

while True:
    print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
    while True: # Player input loop
        playerMove = input('Enter your move: (r)ock (p)aper (s)cissors or (q)uit\n')
        if playerMove == 'q':
                sys.exit()
        if playerMove == 'r' or playerMove == 'p' or playerMove == 's':
            break
        print('Type one of r, p, s, or q')

    # Displays what the player chose
    if playerMove == 'r':
        print('Rock versus...')
    elif playerMove == 'p':
        print('Paper versus...')
    elif playerMove == 's':
        print('Scissors versus...')

    # Makes the computer randomly choose a number to be assigned to a value
    randomNumber = random.randint(1,3)
    if randomNumber == 1:
        computerMove = 'r'
        print('ROCK')
    elif randomNumber == 2:
        computerMove = 'p'
        print('PAPER')
    elif randomNumber == 3:
        computerMove = 's'
        print('SCISSORS')

    # Displays wins, losses, and ties and adds a value depending on the outcome
    if playerMove == computerMove:
        print('It is a tie!')
        ties = ties + 1
    elif playerMove == 'r' and computerMove == 'p':
        print('You lose!')
        losses = losses + 1
    elif playerMove == 'r' and computerMove == 's':
        print('You win!')
        wins = wins + 1
    elif playerMove == 'p' and computerMove == 'r':
        print('You win!')
        wins = wins + 1
    elif playerMove == 'p' and computerMove == 's':
        print('You lose!')
        losses = losses + 1
    elif playerMove == 's' and computerMove == 'p':
        print('You win!')
        wins = wins + 1
    elif playerMove == 's' and computerMove == 'r':
        print('You lose!')
        losses = losses + 1


from Population import Population

if __name__ == "__main__":
    def fit(lst):
        n = len(lst)
        return sum([((i + 1) / n) * lst[i] for i in range(n)])
    population = Population(genes_length=5, num_type="int", fitness_fun=fit, size=10)

    population.generate_initial()
    print(population)

    population.refresh_nofit()
    print(population)

    while True:
        population.prob_crossover()
        population.prob_mutation()
        population.refresh_nofit()
        best = population.best_fit.fitness
        worst = population.worst_fit.fitness
        print(best, worst)
        if best/worst < 0.005:
            break


import os
import pygame
from variable_sh import *
from botton import *

grade_list = []
os.chdir(firstpath)
file = open("grade_list.txt",'r')
for lineContent in file:
	grade_list.append(lineContent.strip().split(','))
file.close()

def makewordtext(textfilename):
	for i in range(6):
		if textfilename[0] == grade_list[i+2][2]:
			wordnow_Path = os.path.join(word_Path,grade_list[i+2][4],textfilename[2])
			break
	os.chdir(wordnow_Path)
	wordtext = []
	try:
		with open(textfilename[2]+'.txt','r') as wordfile:
			for lineContent in wordfile:
				wordtext.append(lineContent.strip().split(','))
	except FileNotFoundError:
		print('해당단어의 txt파일이 없습니다.')
		return 0

	for j in range(len(wordtext)):
		for k in range(len(wordtext[j])):
			while "<c>" in wordtext[j][k]:
				index = wordtext[j][k].find("<c>")
				wordtext[j][k] = wordtext[j][k][:index] + "," + wordtext[j][k][index+3:]

			index = 0
			indexwhere = [0]

			while True:
				index += wordtext[j][k][index:].find("<n>")+3
				indexwhere += [index]
				if "<n>" not in wordtext[j][k][index:]:
					break
			indexwhere += [len(wordtext[j][k])+3]
			a = 0
			retext = []
			if "<n>" in wordtext[j][k]:
				for i in indexwhere:
					if i == 0:
						continue
					retext += [wordtext[j][k][a:i-3]]
					a = i
				wordtext[j][k] = retext
			else:
				wordtext[j][k] = [wordtext[j][k]]

	return wordtext


from os import path
from qhue import Bridge, QhueException, create_new_username
import discoverhue,csv,json,os,random,time

#https://pypi.org/project/discoverhue/
#https://github.com/studioimaginaire/phue

# the path for the username credentials file
CRED_FILE_PATH = "qhue_username.txt"

def Get_Bridge_IP():
    # the IP address of your bridge
    found = discoverhue.find_bridges()
    for bridge in found:
        ip = found[bridge]
    ip = ip.replace("http://","")
    ip = ip.replace(":80/","")
    return ip

def Get_Username(ip):
    if not path.exists(CRED_FILE_PATH):
        with open(CRED_FILE_PATH, "w") as csv_file:
            fieldnames = ['ip','username']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writeheader()

    # check for a credential file
    found = False
    cred_file = open(CRED_FILE_PATH)
    csv_file = csv.reader(cred_file)
    for row in csv_file:
        if ip in row:
            username = row[1]
            found = True
            break

    if found == True:
        return username
    else:
        try:
            username = create_new_username(ip)
        except QhueException as err:
            print("Error occurred while creating a new username: {}".format(err))

        with open(CRED_FILE_PATH, "a") as csv_file:
            fieldnames = ['ip','username']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            writer.writerow({'ip': ip, 'username': username})

        return username

def Get_LightInfo():
    lights = {}
    lights = bridge.lights
    with open('lights.json', 'w') as outfile:
        json_lights = json.dumps(lights(), indent=4)
        json.dump(lights(), outfile)
    print(json_lights)

def Start_Rave(light):
    print("Press Ctrl-C to terminate the rave!")
    try:
        while True:
            bridge.lights[random.randint(1,light)].state(on=True, sat=random.randint(0,254), bri=254,hue=random.randint(0,65535))
            time.sleep(.1)
    except KeyboardInterrupt:
        os.system('clear')
        pass

def Turn_Off(lights):
    for x in range(lights):
        light = x + 1
        bridge.lights[light].state(on=False)

def Turn_On(lights):
    for x in range(lights):
        light = x + 1
        bridge.lights[light].state(on=True)

def menu():
    os.system('clear')
    ans=True
    while ans:
        print('Bridge IP {ip} and Username {UN}'.format(ip=BRIDGE_IP, UN=username))
        print ("""
1. View Light Info
2. Start Rave
3. Turn Off All Lights
4. Turn On All Lights
5. View Creds File
6. Exit Program
        """)
        ans=input("What would you like to do? ")
        if ans=="1":
            Get_LightInfo()
            input("Press Enter to continue...")
            menu()
        elif ans=="2":
            num_lights = int(input("Enter the number of hue lights:"))
            Start_Rave(num_lights)
            input("Press Enter to continue...")
            menu()
        elif ans=="3":
            num_lights = int(input("Enter the number of hue lights:"))
            Turn_Off(num_lights)
            input("Press Enter to continue...")
            menu()
        elif ans=="4":
            num_lights = int(input("Enter the number of hue lights:"))
            Turn_On(num_lights)
            input("Press Enter to continue...")
            menu()
        elif ans=="5":
            Creds = open(CRED_FILE_PATH, "r")
            for line in Creds:
                print(line)
            input("Press Enter to continue...")
            menu()
        elif ans=="6":
            exit()
        elif ans !="":
            print("\n Not Valid Choice Try again")
            input("Press Enter to continue...")
            menu()

#Gets Bridge IP
BRIDGE_IP = Get_Bridge_IP()
#Get Bridge Username
username = Get_Username(BRIDGE_IP)
#Creates Bridge Connection
bridge = Bridge(BRIDGE_IP, username)

menu()


from django.urls import path, re_path, include
from django.views.generic.base import TemplateView

from . import views

urlpatterns = [
    path('mine/', views.UserQuestionsList.as_view(), name='my_questions'),
    re_path('^create/$', views.QuestionCreate.as_view(), name='create_question'),
    re_path('^details/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='question-detail'),
    re_path('^delete/(?P<pk>\d+)/$', views.QuestionDelete.as_view(), name='question-delete'),
    re_path('^edit/(?P<pk>\d+)/$', views.QuestionEdit.as_view(), name='question-edit'),
    path('unchecked/', views.UncheckedQuestionsList.as_view(), name='unchecked_questions'),
]


import os
import http.server
import json
import threading
import multiprocessing.pool
import subprocess

events = ["Push Hook",
          "Tag Push Hook",
          "Issue Hook",
          "Note Hook",
          "Merge Request Hook",
          "Wiki Page Hook",
          "Pipeline Hook",
          "Job Hook"]

def handle_hook(event, token, obj, config):
    try:
        handle_hook_c(event, token, obj, config)
    except Exception as e:
        print(e)

def handle_hook_c(event, token, obj, config):
    if 'project' not in obj or type(obj['project']) != dict:
        return
    if 'web_url' not in obj['project'] or type(obj['project']['web_url']) != str:
        return
    weburl = obj['project']['web_url']
    if 'ref' not in obj or type(obj['ref']) != str:
        return
    ref = obj['ref']
    print("Hook: ", event, weburl, ref)
    # find repositories
    found_repos = []
    for repo in config.repositories:
        if repo.gitlaburl == weburl and repo.gitlabtoken == token and (repo.ref == None or repo.ref == ref) and (repo.hooks == None or len(repo.hooks) == 0 or event in repo.hooks):
            print(" *  ", repo.name, repo.gitlaburl, repo.ref, repo.hooks)
            found_repos.append(repo)
    if len(found_repos) == 0:
        return
    # find programs
    found_cmds = []
    for cmd in config.commands:
        for repo in found_repos:
            if cmd.repo == repo.name:
                print(" -> ", cmd.name)
                found_cmds.append(cmd)
                break
    if len(found_cmds) == 0:
        return
    # execute programs
    env = {}
    env['GITLAB_URL'] = weburl
    env['GITLAB_TOKEN'] = token
    env['GITLAB_REF'] = ref
    env['GITLAB_EVENT'] = event
    for cmd in found_cmds:
        res = cmd.exec(env)
        if cmd.ignore_error == False and res != 0:
            break

class GitlabHookHandler(http.server.BaseHTTPRequestHandler):

    def send_error(self, code, message=None, explain=None):
        self.log_request(code)
        self.send_response_only(code, message)
        self.send_header('Connection', 'close')
        self.end_headers()

    def do_POST(self):
        event = None
        token = None
        if "X-Gitlab-Event" in self.headers:
            event = self.headers["X-Gitlab-Event"]
        if "X-Gitlab-Token" in self.headers:
            token = self.headers["X-Gitlab-Token"]
        if event == None or token == None:
            self.send_error(http.HTTPStatus.FORBIDDEN, "Forbidden")
            return

        if 'Content-Length' not in self.headers:
            self.send_error(http.HTTPStatus.BAD_REQUEST, "Bad request")
            return

        # get body
        length = None
        try:
            length = int(self.headers['Content-Length'])
        except:
            pass
        if length == None:
            self.send_error(http.HTTPStatus.BAD_REQUEST, "Bad request")
            return
        text = None
        try:
            text = self.rfile.read(length)
        except:
            self.send_error(http.HTTPStatus.BAD_REQUEST, "Bad request")
            return
        json_obj = None
        try:
            json_obj = json.loads(text)
        except Exception as e:
            pass
        if json_obj == None:
            self.send_error(http.HTTPStatus.BAD_REQUEST, "Bad request")
            return

        self.handle_request(event, token, json_obj)

        self.log_request(http.HTTPStatus.OK)
        self.send_response_only(http.HTTPStatus.OK)
        self.send_header('Connection', 'close')
        self.end_headers()

    def handle_request(self, event, token, json_obj):
        pass

class GitlabHookServer(threading.Thread):
    def __init__(self, interface, port, configjson, workers=2):
        config = GitlabHookConfig.fromConfig(configjson)
        self.config = config
        self.configjson = configjson
        pool = multiprocessing.pool.ThreadPool()
        self.pool = pool
        class PrivateGitlabHookHandler(GitlabHookHandler):
            def handle_request(self, event, token, json_obj):
                pool.apply_async(handle_hook, (event, token, json_obj, config))
        print("Start server on ", interface, port)
        self.httpd = http.server.HTTPServer((interface, port), PrivateGitlabHookHandler)
        threading.Thread.__init__(self)
    def run(self):
        self.httpd.serve_forever()
    def stopServer(self):
        self.httpd.shutdown()
        self.httpd.server_close()
        self.pool.close()
        self.pool.join()
        self.pool.terminate()

class Command:
    def __init__(self, name, prog, reponame):
        # config
        self.name = name
        self.prog = prog
        self.repo = reponame
        self.workingdir = None
        self.ignore_error = False
        self.hooks = None
    def fromConfig(config):
        j = Command(config["name"], config["exec"], config["repo"])
        if "workingdir" in config:
            j.workingdir = config["workingdir"]
        if "ignore_error" in config:
            j.ignore_error = config["ignore_error"]
        if 'hook' in config and type(config['hook']) == list:
            hooks = config['hook']
            for h in hooks:
                if type(h) != str:
                    print("Wrong config value: ", config["name"], "hooks")
                if h not in events:
                    print("Unknown hook event: ", h)
            j.hooks = hooks
        return j
    def exec(self, env):
        cmd = self.prog
        print("Prog", self.name, "execute", " ".join(cmd))
        # create new environment
        new_env = os.environ.copy()
        new_env.update(env)
        # run process
        process = subprocess.Popen(cmd, env=new_env, cwd=self.workingdir)
        process.wait()
        print("Prog", self.name, "Return:", process.returncode)
        return process.returncode

class Repository:
    def __init__(self, name, url, token):
        self.name = name
        self.gitlaburl = url
        self.gitlabtoken = token
        self.ref = None
        self.hooks = None
    def fromConfig(config):
        r = Repository(config["name"], config["gitlaburl"], config["gitlabtoken"])
        if 'ref' in config:
            r.ref = config['ref']
        if 'hook' in config and type(config['hook']) == list:
            hooks = config['hook']
            for h in hooks:
                if type(h) != str:
                    print("Wrong config value: ", config["name"], "hooks")
                if h not in events:
                    print("Unknown hook event: ", h)
            r.hooks = hooks
        return r

class GitlabHookConfig:
    def __init__(self):
        self.interface = ""
        self.port = None
        self.repositories = []
        self.commands = []
    def fromConfig(config):
        c = GitlabHookConfig()
        if 'interface' in config:
            c.interface = config['interface']
        if 'port' in config:
            c.port = config['port']
        for r in config['repositories']:
            r = Repository.fromConfig(r)
            c.repositories.append(r)
        for e in config['commands']:
            cmd = Command.fromConfig(e)
            c.commands.append(cmd)
        return c


from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal

_DATE_FORMAT = "%Y%m%d"

@dataclass
class CashDividendsEntity:
    asset_issued: str
    payment_date: datetime.date
    rate: Decimal
    related_to: str
    approved_on: datetime.date
    isin_code: str
    label: str
    last_date_prior: datetime.date
    remarks: str = ""
    id: str = None

    def __post_init__(self):
        if isinstance(self.payment_date, str):
            self.payment_date = datetime.strptime(self.payment_date, _DATE_FORMAT).date()
        if isinstance(self.approved_on, str):
            self.approved_on = datetime.strptime(self.approved_on, _DATE_FORMAT).date()
        if isinstance(self.last_date_prior, str):
            self.last_date_prior = datetime.strptime(self.last_date_prior, _DATE_FORMAT).date()
        if not isinstance(self.rate, Decimal):
            self.rate = Decimal(self.rate).quantize(Decimal("0.00000000001"))
        if not self.id:
            self.id = f"{self.payment_date.strftime(_DATE_FORMAT)}" \
                      f"#{self.label}#{self.approved_on.strftime(_DATE_FORMAT)}" \
                      f"#{self.last_date_prior.strftime(_DATE_FORMAT)}"

    def to_dict(self):
        return {
            **self.__dict__,
            "payment_date": self.payment_date.strftime(_DATE_FORMAT),
            "approved_on": self.approved_on.strftime(_DATE_FORMAT),
            "last_date_prior": self.last_date_prior.strftime(_DATE_FORMAT),
        }


'''
二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为：
“对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”
'''

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

'''当节点 p, qp,q 在节点 rootroot 的异侧时，节点 rootroot 即为最近公共祖先'''

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        '''方法一：超出时间范围 nlogn'''
        # def findNode(node:TreeNode,p:TreeNode)->bool:
        #     if not node:
        #         return False
        #     elif node==p:
        #         return True
        #     else:
        #         return findNode(node.left,p) or findNode(node.right,p)
        # if not root:
        #     return None
        # # 公共节点在左子树
        # if findNode(root.left,p) and findNode(root.left,q):
        #     return self.lowestCommonAncestor(root.left,p,q)
        # # 公共节点在右子树
        # if findNode(root.right,p) and findNode(root.right,q):
        #     return self.lowestCommonAncestor(root.right,p,q)
        # # 公共节点分别在两侧
        # return root
        '''方法二'''
        # 定义规则：比如在某一棵子树上先找到了p，则无需继续遍历这棵子树，
        # 因为即使这棵子树有q，p也一定是q的祖先，也就是它们两个的最近公共祖先。
        if root==None or root==p or root==q:
            return root
        # 按照上述规则，找到root的左子树的最近公共祖先。
        left=self.lowestCommonAncestor(root.left,p,q)
        # 按照上述规则，找到root的右子树的最近公共祖先。
        right=self.lowestCommonAncestor(root.right,p,q)
        # 一边找到了，一边没找到，根据上述规则，找到的就是最近公共祖先。
        if left==None:
            return right
        elif right==None:
            return left
        else:
            # 如果在左右子树分别找到了p和q，则说明root是它们两个的最近公共祖先。
            return root

code/数据结构/二叉树/dfs的应用/获得树的一些属性/2022-04-11_3-二叉树的最近公共祖先.py


def create_sentences_out_of_dataframe(data):
    """
    Create sentences out of a dataframe of tagged data containing the columns "Words" and "Tags"
    :param data: (pandas DataFrame) where the first element of each line corresponds to a word,
    where ### is the end of a sentence word, and where the second element of each line is the tag of this word
    :return: (list of lists of tuples) tag sentences as list of lists of tuples (word, tag)
    """
    sentence_data = list(zip(data['Sentence #'], data['Word'], data['Tag']))

    tagged_sentences = []
    tag_sent = []

    for line in sentence_data:
        if line[0] == line[0]: # When we meet a "Sentence: " for a sentence start
            if tag_sent: # Other cases
                tagged_sentences.append(tag_sent)
                tag_sent = []
                tag_sent.append((line[1], line[2]))
            if not tag_sent: # First case
                tag_sent.append((line[1], line[2]))
        elif line[0] != line[0]: # Check if NaN
            tag_sent.append((line[1],line[2]))
    # Last case
    tagged_sentences.append(tag_sent)

    return tagged_sentences

# Some usefull functions
def tag_sequence(sentences):
    return [[t for w, t in sentence] for sentence in sentences]

def text_sequence(sentences):
    return [[w for w, t in sentence] for sentence in sentences]

def from_iob_to_io(sentences):
    """
    Transforms the IOB tags in sentences (output of create_sentences_out_of_dataframe) to IO tags
    :param sentences: (list of list of tuples)
    :return: (list of list of tuples)
    """
    clean_sentences=[]
    for desc in sentences:
        sublist=[]
        for x in desc:
            l = list(x)
            tag = l[1]
            if 'B-' in tag:
                tag = tag.replace('B-', '')
            elif 'I-' in tag:
                tag = tag.replace('I-', '')
            elif 'b-' in tag:
                tag = tag.replace('b-', '')
            elif 'i-' in tag:
                tag = tag.replace('i-', '')
            t = tuple([l[0], tag])
            sublist.append(t)
        clean_sentences.append(sublist)
    return clean_sentences

def split(sentences, max):
    """ Splits sentences (as list of lists of tuples), to list of lists of len(max) or less """

    new = []
    for data in sentences:
        new.append(([data[x:x+max] for x in range(0, len(data), max)]))
    new = [val for sublist in new for val in sublist]
    return new

def split_and_duplicate_index(sentences, max):
    """
    Splits sentences (as list of lists of tuples), to list of lists of len(max) or less
    And keeps track of the sentence "index" (usefull for inference)
    """

    new = []
    index = []
    for i, data in enumerate(sentences):
        new.append(([data[x:x+max] for x in range(0, len(data), max)]))
        index.append([i for x in range(0, len(data), max)])
    new = [val for sublist in new for val in sublist]
    index = [val for sublist in index for val in sublist]
    return new, index


from app import db
from app.models import Role, Category, DocumentType

roles_text = ['Cliente', 'Empleado', 'Administrador']
categories_text = ['PQRs', 'Soporte', 'Otros']
document_types_text = ['Cedula', 'Pasaporte', 'NIT']

for role in roles_text:
    db.session.add(Role(name=role))

for category in categories_text:
    db.session.add(Category(name=category))

for document_type in document_types_text:
    db.session.add(DocumentType(name=document_type))

db.session.commit()


from django.contrib import admin
from django.urls import path, re_path as url
from benie_app import views

# url patterns/configurations
urlpatterns = [
    url(r'^contacts/all$',views.Contacts.as_view(),name='contacts'),
    url(r'^contact/details/(\d+)$',views.ContactDetails.as_view(),name='contact-details'),
    url(r'^subscriber/details/(\d+)$',views.SubscriberDetails.as_view(),name='subscriber-details'),
    url(r'^stories/add$',views.AddStory.as_view(),name='add-story'),
    url(r'^story/update/(\d+)$',views.UpdateStory.as_view(),name='update-story'),
    url(r'^chapters/add$',views.AddChapter.as_view(),name='add-chapter'),
    url(r'^chapter/update/(\d+)$',views.UpdateChapter.as_view(),name='update-chapter'),
    url(r'^pages/all$',views.AllPages.as_view(),name='all-pages'),
    url(r'^pages/add$',views.AddPage.as_view(),name='add-page'),
    url(r'^page/update/(\d+)$',views.UpdatePage.as_view(),name='update-page'),
    url(r'^tags/add$',views.AddTag.as_view(),name='add-tag'),
    url(r'^tag/details/(\d+)$',views.TagDetails.as_view(),name='tag-details'),
    url(r'^poems/add$',views.AddPoem.as_view(),name='add-poem'),
    url(r'^poem/update/(\d+)$',views.UpdatePoem.as_view(),name='update-poem'),
    url(r'^notification/details/(\d+)$',views.NotificationDetails.as_view(),name='notification-details'),
    url(r'^reaction/details/(\d+)$',views.ReactionDetails.as_view(),name='reaction-details'),
]


from django.contrib import admin
from .models import UserProfile
from django.contrib.auth.admin import UserAdmin
from typing import Set

# Unregister the provided model admin
#admin.site.unregister(UserProfile)

# Register out own model admin, based on the default UserAdmin
@admin.register(UserProfile)
class CustomUserAdmin(UserAdmin):

    readonly_fields = [
        'password',
        'date_joined'
    ]

    def has_delete_permission(self, request, obj=None):
        return False

    def get_form(self, request, obj=None, **kwargs): #Conditionally Prevent Update of Fields
        form = super().get_form(request, obj, **kwargs)
        is_superuser = request.user.is_superuser
        disabled_fields = set()  # type: Set[str]

        if not is_superuser:
            disabled_fields |= {
                'username',
                'email'
                'is_superuser',
            }

        # Prevent non-superusers from editing their own permissions
        if (
            not is_superuser
            and obj is not None
            and obj == request.user
        ):
            disabled_fields |= {
                'is_staff',
                'is_superuser',
                'groups',
                'user_permissions',
            }

        for f in disabled_fields:
            if f in form.base_fields:
                form.base_fields[f].disabled = True

        return form


from domain.JucatorCls import Jucator
from errors.Erori import TeamError, RepoError
import random
from infrastructure.Repository import RepoJucator
from validare.Validatori import ValidatorJucator

class ServJucator(object):
    def __init__(self, repoJucator, validJucator):
        '''
        descriere:
            - creeaza o entitate de tip ServJucator
        args:
            - repoJucator - o entitate de tip RepoJucator
            - validJucator - o entitate de tip ValidatorJucator
        return:
            -
        raises:
            -
        '''
        self.__repoJucator = repoJucator
        self.__validJucator = validJucator

    def addJucator(self, nume, prenume, inaltime, post):
        '''
        descriere:
            - creeaza o entitate de tip Jucator pe care incearca apoi
            sa o adauge in RepoJucator
        args:
            - nume - string nevid
            - prenume - string nevid
            - inaltime - nr natural
            - post - Fundas, Extrema sau Pivot
        return:
            -
        raises:
            -
        '''
        jucator = Jucator(nume, prenume, inaltime, post)
        self.__validJucator.valideazaJucator(jucator)
        self.__repoJucator.storeJucator(jucator)

    def modificaInaltimea(self, nume, prenume, inaltime):
        '''
        descriere:
            - modifica inaltimea unui jucator
        args:
            - nume - string nevid
            - prenume - string nevid
            -inaltime - nr natural
        return:
            -
        raises:
            -
        '''
        jucator = Jucator(nume, prenume, inaltime, "Fundas")
        self.__validJucator.valideazaJucator(jucator)
        self.__repoJucator.updateJucator(jucator)

    def greatTeam(self):
        '''
        descriere:
            - determina o echipa formata din 2 extreme, 2 fundasi si un pivot
            cei mai inalti din fisier
        args:
            -
        return:
            - o lista cu echipa formata din elemente de tip Jucator
        raises:
            - TeamError - daca nu se poate forma o echipa
        '''
        list_of_jucatori = self.__repoJucator.getAll()

        list_of_jucatori = sorted(list_of_jucatori, key = lambda x: x.get_inaltime(), reverse = True)

        extreme = []
        pivoti = []
        fundasi = []

        for juc in list_of_jucatori:
            if juc.get_post() == "Extrema":
                extreme.append(juc)
            elif juc.get_post() == "Pivot":
                pivoti.append(juc)
            elif juc.get_post() == "Fundas":
                fundasi.append(juc)

        if len(pivoti) < 1 or len(extreme) < 2 or len(fundasi) < 2:
            raise TeamError("NU se poate forma o echipa")

        else:
            list = []
            list.append(fundasi[0])
            list.append(fundasi[1])
            list.append(pivoti[0])
            list.append(extreme[0])
            list.append(extreme[1])
            return list

    def importaJucs(self, nume_fisier):
        '''
        descriere:
            - importa jucatori dintr-un fisier
        args:
            - nume_fisier - un string nevid
        return:
            - numarul de jucator importati
        raises:
            - IOError daca nu se poate deschide fisierul
        '''
        number = 0
        list_of_jucatori = self.__repoJucator.getAll()
        try:
            fisi = open(nume_fisier, "r")
            fileline = fisi.readline().strip()
            while fileline != "":
                attrs = fileline.split(" ")
                jucator = Jucator(attrs[0], attrs[1], random.randint(180,200), random.choice(["Fundas", "Extrema", "Pivot"]))
                if jucator not in list_of_jucatori:
                    number = number + 1
                    self.__repoJucator.storeJucator(jucator)
                fileline = fisi.readline().strip()

        except IOError:
            print("Nu s-a putut deschide fisierul")
        finally:
            fisi.close()

        return number

    def getAllJucatori(self):
        '''
        descriere:
            - returneaza lista cu jucatorii din fisier
        args:
            -
        return:
            - list_of_jucatori - lista cu jucatorii, entitati de tip Jucator
        raises:
            -
        '''

        list_of_jucatori = self.__repoJucator.getAll()
        return list_of_jucatori

def TestServ():
    try:
        f = open("testServ.txt", "w")
    finally:
        f.close()
    repo = RepoJucator("testServ.txt")
    valid = ValidatorJucator()
    serv = ServJucator(repo,valid)

    #test add + getall
    serv.addJucator("a", "b", 180, "Fundas")
    serv.addJucator("c", "d", 181, "Fundas")
    serv.addJucator("e", "f", 182, "Pivot")
    serv.addJucator("g", "h", 183, "Extrema")
    serv.addJucator("i", "j", 184, "Extrema")
    serv.addJucator("k", "l", 185, "Extrema")

    list = serv.getAllJucatori()

    assert len(list) == 6

    #test team
    team = serv.greatTeam()
    assert team[4].get_inaltime() == 184

    #test modifica
    serv.modificaInaltimea("a", "b", 181)
    list = serv.getAllJucatori()

    assert list[0].get_inaltime() == 181

    #test importa
    nr = serv.importaJucs("testimp.txt")
    assert nr == 1

TestServ()


"""
Q-Learning
MiniMax
(2 in 1)
"""

from typing import List, Tuple
from enum import Enum
from math import inf
from copy import deepcopy
from collections import UserDict
from random import random, choice

class Player(Enum):
    X = 'X'   # MAX-player
    O = 'O'   # MIN-player
    EMPTY = chr(0x25a1)
    DRAW = "DRAW"

class State():
    gamma = 0.9
    def __init__(self, *args, **kwargs):
        self._mx = list(args[0]) if args else [[Player.EMPTY,]*3 for _ in range(3)]
        self.utility_value = kwargs.get("utility")   # None by default
        self._terminal = None

        # Check state validity
        l = sum(self._mx, [])
        xx,oo = (l.count(v) for v in (Player.X, Player.O))
        if not(0 <= (xx - oo) <=1):
            raise ValueError("Invalid board state")

    def player(self) -> Player:
        """Returns the player who's turn it is"""
        l = sum(self._mx, [])
        xx,oo = (l.count(v) for v in (Player.X, Player.O))
        return Player.X if xx - oo == 0 else Player.O

    def actions(self) -> List[Tuple[int,int]]:
        """Returns valid moves from this state"""
        return [(i,j) for i in range(3) for j in range(3) if self._mx[i][j] == Player.EMPTY]

    def transition(self, action) -> 'State':
        """returns the next state"""
        assert min(action) >= 0 and max(action) <= 2
        copy = deepcopy(self._mx)
        r,c = action
        if copy[r][c] != Player.EMPTY:
            raise ValueError("bad action (tuple-index)")
        player = self.player()
        copy[r][c] = player

        new = State(copy)

        # for printing purposes
        r,c = [(i,j) for i in range(3) for j in range(3) if self._mx[i][j] != new._mx[i][j]][0]
        new.move = "ABC"[r] + str(c+1)

        return new

    def children(self) -> List:
        """returns next states from this state.
        This is a wrapper-function around actions() and transition() methods"""
        return [self.transition(action) for action in self.actions()]

    @property
    def terminal(self) -> bool:
        """is this state terminal?"""
        if self.utility():
            return True

        l = sum(self._mx, [])

        # This line is for RL (play to the last square, even when draw)
        return False if Player.EMPTY in l else True

        # This block is for Adversarial Search (returns True when it is clear that it is a draw)
        slices = [slice(i,None,3) for i in range(3)] + [slice(None,None,4), slice(2,-1,2)]

        for e in self._mx + slices:
            S = set(l[e] if isinstance(e, slice) else e)
            if not {Player.X, Player.O}.issubset(S) and Player.EMPTY in S:
                return False
        return True

    def winner(self):
        if not self.terminal:
            return None
        cost = self.utility()
        winner = {0:Player.DRAW, 1:Player.X, -1:Player.O}[cost]
        return winner

    def utility(self, depth=None) -> int or float:
        """returns the utility (used in Adverserial Search)"""
        l = sum(self._mx, [])
        slices = [slice(i,None,3) for i in range(3)] + [slice(None,None,4), slice(2,-1,2)]
        depth = abs(depth or 1)

        for e in self._mx + slices:
            t = l[e] if isinstance(e, slice) else e
            if t.count(Player.X) == 3:
                return 1 / depth
            elif t.count(Player.O) == 3:
                return -1 / depth
        return 0

    def __str__(self):
        return str.join('\n', ((str.join('', (v.value for v in row))) for row in self._mx))

    def __repr__(self):
        d = {Player.X: [], Player.O: []}
        for i,p in enumerate(sum(self._mx, [])):
            if p == Player.EMPTY:
                continue
            d[p].append(i+1)

        s = 'X:' + str(d[Player.X])[1:-1].replace(' ', '') + " / O:" + str(d[Player.O])[1:-1].replace(' ', '')
        return self.__class__.__name__ + f"({s})"

    def __lt__(self, other):
        return self.utility_value < (other.utility_value if isinstance(other, State) else other)
    def __gt__(self, other):
        return self.utility_value > (other.utility_value if isinstance(other, State) else other)

    def __hash__(self):
        return hash(tuple(sum(self._mx, [])))
    def __eq__(self, other):
        if type(self) is not type(other):
            raise TypeError(f"equality operation is not supported between '{self.__class__.__name__}' and '{other.__class__.__name__}'")
        return hash(self) == hash(other)

    @property
    def user_friendly_board(self):
        l = ["  123"] + [c+' '+line for c,line in zip("ABC", str(self).strip().split('\n'))]
        return str.join('\n', l)

    def reward(self, action=None):
        """returns immediate reward from the standpoint of player O"""
        d = {Player.X: -100, Player.O: 100, Player.DRAW: 0, None: 0}
        state = self if not action else self.transition(action)
        winner = state.winner()
        return d[winner]

    def value(self):
        """returns the value of the state (recursive function with a base case)"""
        if self.terminal:
            return self.reward()
        values = (s.value() for s in self.children())
        return self.reward() + self.gamma * max(values)

class QTable(UserDict):
    def __getitem__(self, index):
        if type(index) not in (State, tuple):
            raise TypeError("bad argument type")

        s,a = index if type(index) is tuple else (index, None)

        if s not in self:
            self.data[s] = {a:0 for a in s.actions()}
        return self.data[s] if a is None else self.data[s][a]

    def __setitem__(self, index, item):
        if not (type(index) is tuple and type(item) in (int,float)):
            raise TypeError("bad arguments")
        s,a = index
        self[s][a] = item

def policy(state, Q_table, epsilon=0):
    # deterministic
    if not epsilon or random() < (1 - epsilon):
        return max(Q_table[state], key=lambda k: Q_table[state][k])
    # stochastic
    return choice(tuple(Q_table[state]))

def min_play(state, depth=0):
    # Base case
    if state.terminal:
        if depth==0: return state
        return state.utility(depth=depth)
    # Recursive
    best = inf
    for child in state.children():
        v = max_play(child, depth-1)
        if depth==0:
            child.utility_value = v
            v = child
        best = min(v, best)

    # Figure out what move the ai has made for printing purposes
    if depth == 0 and isinstance(best, State):
        r,c = [(i,j) for i in range(3) for j in range(3) if state._mx[i][j] != best._mx[i][j]][0]
        best.move = "ABC"[r] + str(c+1)
    return best

def max_play(state, depth=0):
    # Base case
    if state.terminal:
        if depth==0: return state
        return state.utility(depth=depth)
    # Recursive
    best = -inf
    for child in state.children():
        v = min_play(child, depth-1)
        if depth==0:
            child.utility_value = v
            v = child
        best = max(v, best)

    # Figure out what move the ai has made for printing purposes
    if depth == 0 and isinstance(best, State):
        r,c = [(i,j) for i in range(3) for j in range(3) if state._mx[i][j] != best._mx[i][j]][0]
        best.move = "ABC"[r] + str(c+1)
    return best

def decorator(func):
    """Checks whether the square chosen by the user is occupied"""
    def closure(*args, **kwargs):
        state = kwargs.get("state")
        actions = kwargs.get("actions")

        while True:
            user_input = func()
            if not(state or actions):
                return user_input

            # Get allowed actions (i.e. moves) - if not provided by the user
            actions = actions or state.actions()

            # Check validity of the move
            if user_input not in actions:
                print("The selected square is taken.")
            else:
                return user_input
    return closure

@decorator
def get_input():
    rows = {'a':0, 'b':1, 'c':2}
    cols = {str(i+1):i for i in range(3)}
    while True:
        s = input("Your move: ")
        s = s.lower().strip()
        if len(s)!=2 or s[0] not in rows.keys() or s[1] not in cols.keys():
            print("bad input - accpted format: A1")
            continue
        else:
            return (rows[s[0]], cols[s[1]])

def check_winner(state):
    print(">>>WINNER:", state.winner())

    if state.terminal:
        print(state.user_friendly_board)
        cost = state.utility()
        winner = {0:None, 1:Player.X, -1:Player.O}[cost]
        if not winner:
            print("\nDRAW")
        else:
            print("\nWINNER:", winner.value)
        return winner or "DRAW"
    return False

def controller(player=None, Q_table=None):
    """
    Controlls the game.
    The AI is able to play in two modes: MiniMax or Q-Learning.

    If player=None  then the user is asked.
    """

    print("\nYour AI opponent: " + ("RL" if Q_table else "MiniMax"))

    human_as_X = None if player is None else True if 'X' in str(player).upper() else False

    if human_as_X is None:
        print("Do you want to play as 'X' or 'O'?\t\t(the 'X' starts the game)")
        answer = input("X or O? ")[-1].upper(); print()
        human_as_X = 'X' == answer

    # Initial state
    s = State()

    # If the human goes first
    if human_as_X:
        print(s.user_friendly_board)
        a = get_input(state=s)
        s = s.transition(a)
        print(s.user_friendly_board)

    # The main loop
    while True:
        # AI's move
        if Q_table:
            a = policy(s, Q)
            s = s.transition(a)
        else:
            s = (min_play if human_as_X else max_play)(s)

        print(f"\nMy move: {s.move}")
        print(s.user_friendly_board)

        winner = s.winner()
        if winner: break

        # Human's move
        a = get_input(state=s)
        s = s.transition(a)

        print(s.user_friendly_board)

        winner = s.winner()
        if winner: break

    print("\nThe winner is: " + winner.value)
    return winner

#_____________________________________________________________________________

## Q-learning
η = 0.9
γ = 0.9

r = 1
r_draw = 0.2
γ = 0.9
ε = 0.3
η = 0.25

Q = QTable()

for episode in range(100000):
    s = State()
    path = []

    while not s.terminal:
        a = policy(s, Q, ε)
        path.append((s,a))
        s = s.transition(a)

    # Who's the winner?
    winner = s.winner()

    #
    for (s,a) in path[::-1]:
        if winner == Player.DRAW:
            TD = r_draw - Q[s,a]
        elif s.player() == winner:
            TD = r - Q[s,a]
            #Q[s,a] += r
        else:
            TD = -r - Q[s,a]
            #Q[s,a] -= r
        Q[s,a] = Q[s,a] + η * TD

        # doscount the reward
        r *= γ
        r_draw *= γ

#______________________________________________________

winner = controller(Q_table=Q)


import os
import re
import sys
from os.path import join as pjoin
from glob import glob
import shutil

from setuptools import setup, Command, Extension, find_packages
from setuptools.command.sdist import sdist
from setuptools.command.build_ext import build_ext

from utils.bundle import fetch_libev, configure, bundled_version
from utils.detect import detect_ev
from utils.other import temporary_directory

#-----------------------------------------------------------------------------
# Utils
#-----------------------------------------------------------------------------

def dotc(name):
    return os.path.abspath(pjoin('pyev', name + '.c'))

def doth(name):
    return os.path.abspath(pjoin('pyev', name + '.c'))

#-----------------------------------------------------------------------------
# Flags
#-----------------------------------------------------------------------------

bundledir = "bundled"

#-----------------------------------------------------------------------------
# Compiler settings
#-----------------------------------------------------------------------------

def bundled_settings():
    settings = {
       'libraries': [],
       'include_dirs': [pjoin(bundledir, 'libev')],
       'library_dirs': [],
    }
    return settings

def system_settings():
    settings = {
       'libraries': ['ev'],
       'include_dirs': [],
       'library_dirs': [],
    }
    return settings

COMPILER_SETTINGS = {}

#-----------------------------------------------------------------------------
# Default Values
#-----------------------------------------------------------------------------

define_fmt = "\"{0}\""

cmdclass = {}

extensions = []

package_data = {}

#-----------------------------------------------------------------------------
# Commands
#-----------------------------------------------------------------------------

class FetchCommand(Command):
    """Fetch libev sources, that's it."""

    description = "Fetch libev sources into bundled"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        # fetch sources for libev extension:
        if not os.path.exists(bundledir):
            os.makedirs(bundledir)
        fetch_libev(bundledir)
        for tarball in glob(pjoin(bundledir, '*.tar.gz')):
            os.remove(tarball)

cmdclass['fetch'] = FetchCommand

class CheckSDist(sdist):
    """Custom sdist that ensures that libev is ready."""

    def run(self):
        # Clean before fetch.
        if os.path.exists(bundledir):
            shutil.rmtree(bundledir)
        self.run_command('fetch')
        sdist.run(self)

cmdclass['sdist'] = CheckSDist

class Configure(Command):
    """Configure command adapted from h5py."""

    description = "Discover libev"

    user_options = []

    def initialize_options(self):
        self.libev = 'system'

    def finalize_options(self):
        pass

    def detect_system_libev(self):
        with temporary_directory() as basedir:
            try:
                config = detect_ev(basedir, **system_settings())
            except Exception:
                etype, evalue, tb = sys.exc_info()
                # print the error as distutils would if we let it raise:
                print ("\nerror: %s\n" % evalue)
            else:
                print ("libev version detected: %s.%s" % config['vers'])
                return config

    def bundle_libev_extension(self):
        if self.distribution.ext_modules and \
           self.distribution.ext_modules[0].name == 'pyev.libev':
            # I've already been run
            return

        self.libev = 'bundled'
        settings = bundled_settings()

        print ("Using bundled libev")

        # fetch sources for libev extension
        fetch = self.distribution.get_command_obj('fetch')
        fetch.run()

        # configure libev
        configure(pjoin(bundledir, 'libev'))

        # find depended libraries
        libev_config = open(pjoin(bundledir, 'libev', 'config.h'), "r").read()
        libraries = [l.lower() for l in set(re.findall("#define HAVE_LIB(\S+) 1",
                                            libev_config))]
        settings['libraries'] = list(set(libraries + settings.get('libraries', [])))

        # register libev as extension
        ext = Extension(
            'pyev.libev',
            sources=[pjoin('utils', 'initlibev.c')],
            define_macros=[('LIBEV_EMBED', '1'),
                           ('EV_MULTIPLICITY', '1')],
            **settings
        )

        # Fix for distribute
        ext._needs_stub = False

        # insert the extension
        self.distribution.ext_modules.insert(0, ext)

        return dict(settings=settings,
                    vers=bundled_version)

    def run(self):
        # Try to build with system wide libev.
        config = self.detect_system_libev()

        if config is None:
            # No system wide found, try to build with bundled version.
            config = self.bundle_libev_extension()

        settings = config['settings']
        modules = self.distribution.ext_modules \
                  if self.libev == 'system' \
                  else self.distribution.ext_modules[1:]
        for ext in modules:
            for attr, value in settings.items():
                setattr(ext, attr, value)

cmdclass['configure'] = Configure

class CheckingBuildExt(build_ext):

    def run(self):
        configure = self.distribution.get_command_obj('configure')
        configure.run()
        return build_ext.run(self)

cmdclass['build_ext'] = CheckingBuildExt

#-----------------------------------------------------------------------------
# Description, version and other meta information.
#-----------------------------------------------------------------------------

re_meta = re.compile(r'__(\w+?)__\s*=\s*(.*)')
re_vers = re.compile(r'VERSION\s*=\s*\((.*?)\)')
re_doc = re.compile(r'^"""(.+?)"""')
rq = lambda s: s.strip("\"'")

def add_default(m):
    attr_name, attr_value = m.groups()
    return ((attr_name, rq(attr_value)),)

def add_version(m):
    v = list(map(rq, m.groups()[0].split(', ')))
    return (('VERSION', '.'.join(v[0:3]) + ''.join(v[3:])),)

def add_doc(m):
    return (('doc', m.groups()[0]),)

pats = {re_meta: add_default,
        re_vers: add_version,
        re_doc: add_doc}
here = os.path.abspath(os.path.dirname(__file__))
meta_fh = open(os.path.join(here, 'pyev/__init__.py'))
try:
    meta = {}
    for line in meta_fh:
        if line.strip() == '# -eof meta-':
            break
        for pattern, handler in pats.items():
            m = pattern.match(line.strip())
            if m:
                meta.update(handler(m))
finally:
    meta_fh.close()

with open('README.rst') as fh:
    long_description = fh.read()

#-----------------------------------------------------------------------------
# Extensions
#-----------------------------------------------------------------------------

extensions.append(
    Extension("pyev._pyev",
              ["src/pyev.c"],
              define_macros=[('PYEV_VERSION',
                              define_fmt.format(meta['VERSION']))],
              **COMPILER_SETTINGS
    )
)

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

setup(
    name="pyev-static",
    packages=find_packages(),
    version=meta['VERSION'],
    description=meta['doc'],
    long_description=long_description,
    author=meta['author'],
    author_email=meta['contact'],
    url=meta['homepage'],
    ext_modules=extensions,
    package_data=package_data,
    platforms=["Microsoft Windows", "POSIX"],
    license="BSD License / GNU General Public License (GPL)",
    cmdclass=cmdclass,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Intended Audience :: System Administrators",
        "License :: OSI Approved :: BSD License",
        "License :: OSI Approved :: GNU General Public License (GPL)",
        "Operating System :: Microsoft :: Windows :: Windows NT/2000",
        "Operating System :: POSIX",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.1",
        "Programming Language :: Python :: 3.2",
    ]
)


import sys
import math

r_1 = int(input())
r_2 = int(input())

while r_1 != r_2:
    str_r_1 = str(r_1)
    str_r_2 = str(r_2)
    if r_1 < r_2:
        for i in str_r_1:
            r_1 += int(i)
    else:
        for i in str_r_2:
            r_2 += int(i)

print(r_1)


import pytest
from selenium.webdriver import Chrome
from lesson_20.page.dashboard_page import Dashboard

@pytest.fixture(scope='session')
def driver():
    driver = Chrome()
    driver.get('https://lordofboards.com.ua/')
    driver.maximize_window()

    yield driver
    driver.close()

@pytest.fixture(scope='function')
def dashboard(driver):
    yield Dashboard(driver)


# DFS, BFS 탐색 결과 출력하기
from collections import deque
import sys

n, m, v = map(int, sys.stdin.readline().rstrip().split())

# gragh = [[]]
# for _ in range(m):
#     gragh.append(list(map(int, sys.stdin.readline().rstrip().split())))

gragh = [[0] * (n + 1) for i in range(n + 1)]

for i in range(m):
    x, y = map(int, input().split())
    gragh[x][y] = 1
    gragh[y][x] = 1

dfs_visited = [0] * (n + 1)
bfs_visited = [0] * (n + 1)

def dfs(gragh, v):
    # 현재 노드 방문 처리
    dfs_visited[v] = 1
    print(v, end=" ")

    # 현재 노드와 연결된 다른 노드를 재귀적으로 방문
    for node, yn in enumerate(gragh[v]):
        if yn == 1:
            if dfs_visited[node] == 0:
                dfs(gragh, node)

def bfs(gragh, v):
    # 큐 구현
    queue = deque()
    queue.append(v)

    # 현재 노드 방문 처리
    bfs_visited[v] = 1

    # 큐가 빌 때 까지 반복
    while queue:

        # 큐에서 원소 하나를 뺀다
        v = queue.popleft()
        print(v, end=" ")

        # 인접한 노드들 중 방문하지 않은 노드들은 큐에 넣는다
        for node, yn in enumerate(gragh[v]):
            if yn == 1:
                if bfs_visited[node] == 0:
                    queue.append(node)
                    bfs_visited[node] = 1

dfs(gragh, v)
print()
bfs(gragh, v)


import os
import shutil
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

class Command(BaseCommand):
    help = 'Moves ADS default images to the correct image directory'

    def handle(self, *args, **options):
        current_dir = os.path.dirname(os.path.realpath(__file__))
        ads_img_dir = os.path.join(current_dir, '../../static/img')
        src_files = os.listdir(ads_img_dir)
        dest = os.path.join(settings.MEDIA_ROOT, 'img')
        if not os.path.exists(dest):
            os.makedirs(dest)
        for file_name in src_files:
            full_file_name = os.path.join(ads_img_dir, file_name)
            if (os.path.isfile(full_file_name)):
                self.stdout.write("Copying " + file_name, ending='\n')
                shutil.copy(full_file_name, dest)
        self.stdout.write("Complete.", ending='\n')


# Importe a classe do idioma inglês
from spacy.lang.en import English

# Crie um objeto nlp
nlp = English()

# Processe o texto
doc = nlp("This is a sentence.")

# Imprima o texto do documento
print(doc.text)