"""Sample a set of points in a low-dimensional embedding, according to some
distribution. Points must fit in memory.

"""

import numpy as np
import scipy
import logging
from sklearn.cluster import (SpectralClustering,
                             KMeans,
                             AgglomerativeClustering,
                             DBSCAN)
from sklearn.mixture import GaussianMixture

logger = logging.getLogger('latens')

class Sampler:
  def __init__(self, sample_size=None):
    """A callable that returns an integer array indexing the points given to it.

    :param sample_size: number of examples that this sampler takes. Not used by
    every Sampler, but included for consistency. Can be a fraction, in which
    case len(points) * sample_size are taken from points. Can be None, in
    which case all points are taken.
    :returns:
    :rtype:

    """
    self.sample_size = sample_size

  def get_sample_size(self, N):
    """Get the number of examples to take from a set of points.

    :param N: number of original points
    :returns: sample_size
    :rtype:

    """
    if self.sample_size is None:
      return int(N)
    elif self.sample_size >= 1:
      return int(self.sample_size)
    elif 0 <= self.sample_size < 1:
      return int(np.floor(self.sample_size * N))
    else:
      raise ValueError(f'unrecognized sample_size: {self.sample_size}')

  def __call__(self, *args, **kwargs):
    """Wrapper around self.sample()"""
    return self.sample(*args, **kwargs)

  def sample(self, points):
    """Select some subset of points.

    Returns an array indexing into points. Specifies number of times to repeat
    each example (could be interpreted as a boolean array).

    :param points: points to sample
    :returns: integer or boolean array for indexing points, i.e. a "sampling"
    :rtype: 1-D array

    """
    return np.ones(points.shape[0], dtype=np.int64)

class IdentitySampler(Sampler):
  def sample(self, points):
    return points

class RandomSampler(Sampler):
  def sample(self, points):
    N = points.shape[0]
    n = self.get_sample_size(N)
    perm = np.random.permutation(N)
    sampling = np.zeros(N, dtype=np.int64)
    sampling[perm[:n]] = 1
    return sampling

class MaximizingSampler(Sampler):
  """Provided metrics or encodings, selects the indices which minimize some
  function on those encodings. In the simplest case, provided MAE, return
  examples which maximize the MAE (that is, those on which the autoencoder did
  the worst).

  Subclasses can override process.

  """

  def process(self, points):
    """Given points, compute the row-wise value wished to maximized on."""
    return np.max(points, axis=1)

  def sample(self, points):
    N = points.shape[0]
    n = self.get_sample_size(points.shape[0])
    logger.debug(f"points: {points.shape}, {points}")
    points = points.reshape(N, -1)
    values = self.process(points)
    logger.debug(f"values: {values.shape}")
    indices = np.argsort(values)
    sampling = np.zeros(N, dtype=np.int64)
    sampling[indices[-n:]] = 1
    logger.debug(f"sampling: {sampling}")
    return sampling

class SpatialSampler(Sampler):
  def __init__(self, threshold=0.25, metric='euclidean', **kwargs):
    """Samples over a space according to some distribution.

    Subclasses should override self.draw() using some distribution.

    """
    self.threshold = threshold
    self.metric = metric
    super().__init__(**kwargs)

  def draw(self, points, n):
    """Draw points from a given distribution.

    :param points: all the source points to be considered drawing from
    :param n: number of new points to draw
    :returns: numpy array of points

    """
    raise NotImplementedError

  def sample(self, points, n=None):
    """Sample according to the distribution.

    For each randomly sampled point, finds the closest point from points,
    according the given distance metric. For each of these steps, calculates nxN
    pairwise distances, pretty inefficiently.

    TODO: use an Approximate Nearest Neighbor algorithm instead

    :param points: points to sample
    :param n: number of points to take in sampling, overriding sample_size
    :returns: integer array for indexing points, i.e. a "sampling"
    :rtype: 1-D integer array

    """

    N = points.shape[0]
    if n is None:
      n = self.get_sample_size(N) # number of examples to add to sampling
    sampling = np.zeros(N, dtype=np.int64) # starts with zero examples

    while n > 0:
      logger.debug(f"sampler: drawing {n} points")
      draws = self.draw(points, n)
      distances = scipy.spatial.distance.cdist(
        draws, points, metric=self.metric) # (n,N) array of distances

      closest_indices = np.argmin(distances, axis=1)
      closest_distances = np.min(distances, axis=1) # len == n

      # indices to include in the sampling (with possible repetitions)
      indices = closest_indices[closest_distances <= self.threshold]
      for idx in indices:
        sampling[idx] += 1

      n -= indices.shape[0]

    return sampling

class NormalSampler(SpatialSampler):
  def __init__(self, mean=0.0, std=1.0,
               **kwargs):
    """Sample according to a normal distribution, like points"""
    self.mean = mean
    self.std = std
    super().__init__(**kwargs)

  def draw(self, points, n):
    mean = np.mean(points)
    std = np.std(points)
    return np.random.normal(loc=mean, scale=std, size=(n, points.shape[1]))

class MultivariateNormalSampler(SpatialSampler):
  def __init__(self, **kwargs):
    """Sample according to a multivariate normal distribution.

    """
    super().__init__(**kwargs)

  def draw(self, points, n):
    mean = np.mean(points, axis=0)
    cov = np.cov(points, rowvar=False)
    return np.random.multivariate_normal(mean, cov, size=n)

class UniformSampler(SpatialSampler):
  def __init__(self, **kwargs):
    """Samples uniformly over the space covered by points within [low,hi].

    :param threshold: distance threshold at which to resample.
    :param metric: passed to scipy.spatial.distance.cdist

    """
    super().__init__(**kwargs)

  def draw(self, points, n):
    low = np.min(points, axis=0)
    high = np.max(points, axis=0)
    return np.random.uniform(low, high, size=(n, points.shape[1]))

class ClusterSampler(SpatialSampler):
  def __init__(self, clustering=AgglomerativeClustering, n_clusters=5, **kwargs):
    """Draw the same number of points from each cluster.

    Default behavior is to sample uniformly across a cluster, but subclasses can
    modify the draw method to change this.

    :param clustering: clustering class to use
    :param n_clusters: number of clusters, default is 10

    """
    self.n_clusters = n_clusters
    self.clustering = clustering
    super().__init__(**kwargs)

  def cluster(self, points):
    """Return cluster labels for each point in points."""
    logger.info(f"clustering...")
    clustering = self.clustering(self.n_clusters)
    self._cluster_labels = clustering.fit_predict(points)
    return self._cluster_labels

  @property
  def cluster_labels(self):
    return self._cluster_labels

  def sample(self, points):
    """Sample uniformly from clusters in points.

    :param points:
    :returns:
    :rtype:

    """
    N = points.shape[0]
    n = self.get_sample_size(N)
    sampling = np.zeros(N, dtype=np.int64)
    cluster_labels = self.cluster(points)
    for i in range(self.n_clusters):
      cluster_which = cluster_labels == i
      cluster_n = int(round(n * np.sum(cluster_which) / N))
      cluster_points = points[cluster_which]
      cluster_sampling = super().sample(cluster_points, n=cluster_n)
      sampling[cluster_which] += cluster_sampling
    return sampling

class UniformClusterSampler(ClusterSampler, UniformSampler):
  pass

class NormalClusterSampler(ClusterSampler, NormalSampler):
  pass

class MultivariateNormalClusterSampler(ClusterSampler, MultivariateNormalSampler):
  pass


# Multiplying two matrices.

from matrix import *

# Taking order and elements of first matrix.
print("For Matrix A:-")
ma = int(input("Enter no. of rows(m):"))
na = int(input("Enter no.of columns(n):"))
A = matrix(ma,na)

# Taking order and elements of second matrix.
print("For Matrix B:-")
mb = int(input("Enter no. of rows(m):"))
nb = int(input("Enter no.of columns(n):"))
B = matrix(mb,nb)

# Taking Product of two marices.
if na != mb:  # Checking condition of mul.of matrices.
    print("No. of columns of A should be equal to no. of rows of B.")

else:
    P = []
    for r in range(ma):
        p = []
        for c in range(nb):
            E = 0
            for s in range(na):
               e = A[r][s] * B[s][c]
               E += e
            p.append(E)
        P.append(p)

# Displaying the matrix obtained by adding A and B.
print("Multiplied Matrix :-")
display_matrix(P)

Matrix Calculator/Multiplication of  two matrices..py


import uuid
from datetime import date, datetime
from secrets import token_urlsafe

from invenio_db import db
from sqlalchemy_utils import UUIDType

from .permissions import AccessRequestTokenNeed

class AccessRequestToken(db.Model):
    """Token for accessing guest-based access requests.

    These tokens are used in the guest-based access request workflow to
    signify that somebody has requested access to a record via e-mail,
    but hasn't verified their e-mail yet.
    Once the e-mail address is verified to create the access request, this
    the corresponding ``AccessRequestToken`` will be deleted, and a new
    guest access request will be created with some of the token's information.
    """

    __tablename__ = "rdm_records_access_request_tokens"

    id = db.Column(UUIDType, primary_key=True, default=uuid.uuid4)
    """Access request token ID."""

    token = db.Column(db.String(512), nullable=False)
    """Randomly generated token which will grant access to the request."""

    created = db.Column(
        db.DateTime, nullable=False, default=datetime.utcnow, index=True
    )
    """Creation timestamp."""

    expires_at = db.Column(db.DateTime, nullable=False)
    """Expiration date."""

    email = db.Column(db.String(255), nullable=False)
    """E-mail address for which the access request was made."""

    full_name = db.Column(db.String(255), nullable=False, default="")
    """Full name of the requester."""

    message = db.Column(db.Text, nullable=False, default="")
    """Message associated with the request, explaining why access is needed."""

    record_pid = db.Column(db.String(255), nullable=False)
    """PID value of the record for which the request will be created."""

    consent_to_share_personal_data = db.Column(db.String(255), nullable=False)

    def delete(self):
        """Delete this secret link."""
        db.session.delete(self)

    def to_dict(self):
        """Dump the access request token to a dictionary."""
        return {
            "id": str(self.id),
            "token": str(self.token),
            "created_at": self.created,
            "expires_at": self.expires_at,
            "email": self.email,
            "full_name": self.full_name,
            "message": self.message,
            "consent_to_share_personal_data": self.consent_to_share_personal_data,
            "record_pid": self.record_pid,
        }

    @property
    def need(self):
        """Get the needs provided by the link."""
        return AccessRequestTokenNeed(str(self.id))

    @property
    def is_expired(self):
        """Determine if link is expired."""
        return datetime.utcnow() > self.expires_at

    @classmethod
    def get_by_token(cls, token):
        """Get the AccessRequestToken referenced by the specified token."""
        return cls.query.filter_by(token=token).one_or_none()

    @classmethod
    def create(
        cls,
        email,
        full_name,
        message,
        record_pid,
        shelf_life=None,
        expires_at=None,
        consent=False,
    ):
        """Create a new request access token.

        The ``expires_at`` value will take precedence over the ``shelf_life``.

        :param email: The email address for which the request is made.
        :param full_name: The full name of the requester.
        :param message: The message attached to the request.
        :param record_pid: The PID value for the record that is subject to the request.
        :param shelf_life: The ``timedelta`` for how long the token will live for.
        :param expires_at: The expiration date of the access request token.
        """
        if shelf_life and not expires_at:
            expires_at = datetime.utcnow() + shelf_life

        is_date = isinstance(expires_at, date)
        is_datetime = isinstance(expires_at, datetime)
        if is_date and not is_datetime:
            expires_at = datetime.combine(expires_at, datetime.min.time())

        access_request_token = cls(
            email=email,
            full_name=full_name,
            message=message,
            record_pid=record_pid,
            expires_at=expires_at,
            token=token_urlsafe(),
            consent_to_share_personal_data=consent,
        )
        db.session.add(access_request_token)

        return access_request_token


def factorial(n):
    if n < 0:
        raise ValueError('Cannot take the factorial of a negative number.')
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

def committee(people, members, chairperson = True):
    if people <= 0:
        raise ValueError('Invalid weight')
    if members > people:
        raise ValueError('Member count must not be greater than people count.')
    if chairperson == True:
        ways = int(factorial(people) / (factorial(members-1) * factorial(people-members)))
    elif chairperson == False:
        ways = int(factorial(people) / (factorial(members)*factorial(people-members)))
    return ways


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

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='ipynb2fs',
    version='0.1.0',
    description='a Fuse filesyteme that expose ipython notebook as folders',
    long_description=readme + '\n\n' + history,
    author='Matthias Bussonnier',
    author_email='bussonniermatthias@gmail.com',
    url='https://github.com/Carreau/ipynb2fs',
    packages=[
        'ipynb2fs',
    ],
    package_dir={'ipynb2fs': 'ipynb2fs'},
    include_package_data=True,
    install_requires=[
    ],
    license="BSD",
    zip_safe=False,
    keywords='ipynb2fs',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
    ],
    test_suite='tests',
)


import os
import numpy as np
import json
import matplotlib.pyplot as plt
import cv2

import vstarstack.library.data
import vstarstack.tool.cfg
import vstarstack.tool.cfg

def show(project: vstarstack.tool.cfg.Project, argv: list):
    """Display detected stars"""
    image = vstarstack.library.data.DataFrame.load(argv[0])
    channel = argv[1]
    with open(argv[2], encoding='utf8') as f:
        descs = json.load(f)
    show_all = vstarstack.tool.cfg.get_param("all", bool, False)
    slope = vstarstack.tool.cfg.get_param("multiply", float, 1)
    layer, _ = image.get_channel(channel)
    layer = np.clip(layer/np.amax(layer)*slope, 0, 1)
    layer = (layer * 255).astype(np.uint8)

    showed = np.zeros((layer.shape[0], layer.shape[1], 3), dtype="uint8")
    showed[:,:,0] = layer
    showed[:,:,1] = layer
    showed[:,:,2] = layer
    if show_all:
        items = descs["stars"]
    else:
        items = [item["star"] for item in descs["main"]]
    for star in items:
        cv2.circle(showed, (star["x"], star["y"]), int(star["size"]+11), (255,0,0), 1)

    plt.imshow(showed)
    plt.show()

def get_brightness(df):
    light = None
    for channel in df.get_channels():
        layer, opts = df.get_channel(channel)
        if not opts["brightness"]:
            continue
        if light is None:
            light = layer
        else:
            light = light + layer
    return light

def show_match(project: vstarstack.tool.cfg.Project, argv: list):
    """Display detected stars"""
    fname1 = argv[0]
    fname2 = argv[1]
    name1 = os.path.splitext(os.path.basename(fname1))[0]
    name2 = os.path.splitext(os.path.basename(fname2))[0]
    image1 = vstarstack.library.data.DataFrame.load(fname1)
    image2 = vstarstack.library.data.DataFrame.load(fname2)
    with open(argv[2], encoding='utf8') as f:
        descs1 = json.load(f)
    with open(argv[3], encoding='utf8') as f:
        descs2 = json.load(f)
    with open(argv[4], encoding='utf8') as f:
        match_table = json.load(f)

    slope = vstarstack.tool.cfg.get_param("multiply", float, 1)
    layer1 = get_brightness(image1)
    layer2 = get_brightness(image2)
    layer1 = np.clip(layer1/np.amax(layer1)*slope, 0, 1)
    layer1 = (layer1 * 255).astype(np.uint8)
    layer2 = np.clip(layer2/np.amax(layer2)*slope, 0, 1)
    layer2 = (layer2 * 255).astype(np.uint8)

    kps1 = []
    kps2 = []
    matches = []
    index = 0
    for star1_id, star2_id in match_table[name1][name2].items():
        star1_id = int(star1_id)
        star1 = descs1["main"][star1_id]["star"]
        star2 = descs2["main"][star2_id]["star"]
        kps1.append(cv2.KeyPoint(star1["x"], star1["y"], int(star1["radius"])+2))
        kps2.append(cv2.KeyPoint(star2["x"], star2["y"], int(star2["radius"])+2))
        matches.append(cv2.DMatch(index, index, 0))
        index += 1

    img3 = cv2.drawMatches(layer1, kps1, layer2, kps2,
                           matches, None,
                           flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
    plt.imshow(img3)
    plt.show()


"""Sphinx configuration."""

from __future__ import annotations

from datetime import datetime
from datetime import timezone as tz
from importlib.metadata import metadata
from pathlib import PurePosixPath
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from sphinx.application import Sphinx

extensions = [
    "sphinx.ext.intersphinx",
    "sphinx.ext.napoleon",
    "sphinx_autodoc_typehints",  # needs to be after napoleon
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "scanpydoc",
    "sphinx.ext.linkcode",  # needs to be after scanpydoc
]

intersphinx_mapping = dict(
    python=("https://docs.python.org/3", None),
    jinja=("https://jinja.palletsprojects.com/en/2.10.x/", None),
    sphinx=("https://www.sphinx-doc.org/en/master/", None),
    sphinx_book_theme=("https://sphinx-book-theme.readthedocs.io/en/stable/", None),
    # examples
    numpy=("https://numpy.org/doc/stable/", None),
    anndata=("https://anndata.readthedocs.io/en/latest/", None),
    pandas=("https://pandas.pydata.org/pandas-docs/stable/", None),
    scipy=("https://docs.scipy.org/doc/scipy/", None),
)

# general information
meta = metadata("scanpydoc")
project = meta["name"]
author = meta["author-email"].split(" <")[0]
copyright = f"{datetime.now(tz=tz.utc):%Y}, {author}."  # noqa: A001
version = release = meta["version"]

master_doc = "index"
templates_path = ["_templates"]

# Generate .rst stubs for modules using autosummary
autosummary_generate = True
autosummary_ignore_module_all = False
# Don’t add module paths to documented functions’ names
add_module_names = False

html_theme = "scanpydoc"
html_theme_options = dict(
    repository_url="https://github.com/theislab/scanpydoc",
    repository_branch="main",
    use_repository_button=True,
)

rtd_links_prefix = PurePosixPath("src")

def setup(app: Sphinx) -> None:
    """Set up custom Sphinx extension."""
    app.add_object_type(
        "confval",
        "confval",
        objname="configuration value",
        indextemplate="pair: %s; configuration value",
    )


import pygame as pg
import math
from Tower import Tower
import numpy as np

class Board:
    def __init__(self,screenSizeX,screenSizeY):
        self.screenSizeX = screenSizeX
        self.screenSizeY = screenSizeY
        self.screen = pg.display.set_mode((screenSizeX, screenSizeY))
        self.nbSquare = 8
        self.colors = {'orange':'#CD6C37','pink':'#D85EC1','red':'#CD325A','green':'#029561','blue':'#137CCF','yellow':'#C9B91C','brown':'#472C17','purple':'#7949B5'}
        self.squareSizeX = int(self.screenSizeX/self.nbSquare)
        self.squareSizeY = int(self.screenSizeY / self.nbSquare)
        self.p0Towers = []
        self.p1Towers = []
        self.board = self.initBoardColor()
        self.currentTurn=0
        self.playerTurn=0
        self.selectedTower=None
        self.lastTurnColor=None
        self.initPlayers()

    def initBoardColor(self):
        return [['orange','blue','purple','pink','yellow','red','green','brown'],
                ['red','orange','pink','green','blue','yellow','brown','purple'],
                ['green', 'pink', 'orange', 'red','purple', 'brown', 'yellow', 'blue'],
                ['pink', 'purple', 'blue', 'orange','brown', 'green', 'red', 'yellow'],
                ['yellow', 'red', 'green', 'brown','orange', 'blue', 'purple', 'pink'],
                ['blue', 'yellow', 'brown', 'purple','red', 'orange', 'pink', 'green'],
                ['purple', 'brown', 'yellow', 'blue','green', 'pink', 'orange', 'red'],
                ['brown', 'green', 'red', 'yellow','pink', 'purple', 'blue', 'orange']]

    def initPlayers(self):

        p0Towers = []
        p1Towers = []
        p0Color = '#ffffff'
        p1Color = '#000000'
        i = 0
        colors = ['orange','blue','purple','pink','yellow','red','green','brown']
        for color in colors:
            p0Towers.append(Tower(0,self.colors[color],color,p0Color,i,0))
            i+=1
        self.p0Towers = p0Towers
        i=0
        for color in colors.__reversed__():
            p1Towers.append(Tower(1, self.colors[color],color, p1Color, i,7))
            i += 1
        self.p1Towers = p1Towers

    def displayPlayers(self):
        for tower in self.p0Towers+self.p1Towers:
            if self.selectedTower != None:
                if self.selectedTower.x == tower.x and self.selectedTower.y == tower.y:
                    pg.draw.circle(self.screen, pg.Color('#FF0000'),
                                   (tower.x * self.squareSizeX + self.squareSizeX / 2,
                                    tower.y * self.squareSizeY + self.squareSizeY / 2),
                                   self.squareSizeX /3)
            pg.draw.circle(self.screen, tower.playerColor, (tower.x*self.squareSizeX+self.squareSizeX/2,
                                                       tower.y*self.squareSizeY+self.squareSizeY/2),
                           self.squareSizeX/4)
            pg.draw.circle(self.screen, tower.color, (tower.x * self.squareSizeX + self.squareSizeX / 2,
                                                       tower.y * self.squareSizeY + self.squareSizeY / 2),
                           self.squareSizeX/6)

    def displayBoard(self):
        for i in range(self.nbSquare):
            for j in range(self.nbSquare):
                color = pg.Color(self.colors[self.board[j][i]])
                pg.draw.rect(self.screen,color,pg.Rect(i*self.squareSizeX,j*self.squareSizeY,(i+1)*self.squareSizeX,(j+1)*self.squareSizeY))

    def displayAll(self):
        self.screen.fill((255, 255, 255))
        self.displayBoard()
        self.displayPlayers()
        pg.display.flip()

    def victoryCheck(self):
        for tower in self.p0Towers:
            if tower.y == 7:
                print('player 1 WIN !!! Congrats !')
                return 1
        for tower in self.p1Towers:
            if tower.y == 0:
                print('player 0 WIN !!! Congrats !')
                return 0
        return -1

    def handlePlayerClick(self,pos):
        if self.selectedTower == None and self.currentTurn==0:
            self.playerSelectTower(pos)
        else:
            self.playerSelectDestination(pos)

    def findTowerPerCoordinates(self,playerIndex,x,y):
        if playerIndex == 0:
            for tower in self.p0Towers:
                if tower.x == x and tower.y == y:
                    return tower
        else:
            for tower in self.p1Towers:
                if tower.x == x and tower.y == y:
                    return tower
        return None
    def playerSelectTower(self,pos):
        x = math.trunc(pos[0]/self.squareSizeX)
        y = math.trunc(pos[1]/self.squareSizeY)
        selectedSquare = self.findTowerPerCoordinates(self.playerTurn,x,y)
        if selectedSquare != None:
            if selectedSquare.indexPlayer == self.playerTurn:
                self.selectedTower = selectedSquare

    def changeTurn(self):
        if self.playerTurn == 0:
            self.playerTurn = 1
        else:
            self.playerTurn = 0
        self.currentTurn+=1

    def isAbleToMove(self,tower):
        if tower.indexPlayer == 0:
            coordToCheck = [(tower.y+1,tower.x),]
            if tower.x-1 > 0:
                coordToCheck.append(((tower.x-1,tower.y+1)))
            if tower.x+1<self.nbSquare:
                coordToCheck.append(((tower.x + 1, tower.y + 1)))
        else:
            coordToCheck = [(tower.x, tower.y - 1)]
            if tower.x-1 > 0:
                coordToCheck.append(((tower.x-1,tower.y-1)))
            if tower.x+1<self.nbSquare:
                coordToCheck.append(((tower.x + 1, tower.y -1)))

        nbBlock = 0
        for coord in coordToCheck:
            alreadyCheckedThisOne = False
            for testedTower in self.p0Towers+self.p1Towers:
                if testedTower.x == coord[0] and testedTower.y == coord[1] and not alreadyCheckedThisOne:
                    nbBlock+=1
                    alreadyCheckedThisOne = True

        if nbBlock == len(coordToCheck):
            return False
        else:
            return True

    def isTHereATowerInDiagonale(self,tower,destY,destX):
        difXGlobal = abs(destX-tower.x)
        difYGlobal = abs(destY-tower.y)
        if difYGlobal != difXGlobal :
            return True

        for checkTower in self.p0Towers+self.p1Towers:
            if checkTower.x != tower.x or checkTower.y != tower.y :
                difX = abs(checkTower.x-tower.x)
                difY = abs(checkTower.y-tower.y)
                if difY == difX:
                    if tower.indexPlayer == 0:
                        inFront = checkTower.y > tower.y
                    else:
                        inFront = checkTower.y< tower.y
                    if inFront:
                        checkLeftRight = np.sign(checkTower.x-tower.x) == np.sign(destX-tower.x)
                        if difY<=difYGlobal and checkLeftRight:
                            return True
        return False

    def isThereATowerInFront(self,tower,destY,destX):
        if destX != tower.x:
            return True
        towardBot = True
        if destY<tower.y:
            towardBot = False
        for checkTower in self.p0Towers+self.p1Towers:
            if checkTower.x != tower.x or checkTower.y != tower.y:
                if checkTower.x == tower.x:
                    if towardBot and checkTower.y > tower.y and checkTower.y < destY:
                        return True
                    elif not towardBot and checkTower.y<tower.y and checkTower.y>destY:
                        return True
        return False

    def NoRetreat(self,tower,destY):
        if tower.indexPlayer == 0 and destY>tower.y:
            return True
        elif tower.indexPlayer == 1 and destY<tower.y:
            return True
        else:
            return False

    def squareIsEmpty(self,x,y):
        for tower in self.p0Towers+self.p1Towers:
            if tower.x == x and tower.y == y:
                return False
        return True

    def selectLastTurnColorTower(self):
        if self.playerTurn == 0:
            checkTowers = self.p0Towers
        else:
            checkTowers = self.p1Towers
        for tower in checkTowers:
            if tower.colorKey == self.lastTurnColor:
                self.selectedTower = tower
        if not self.isAbleToMove(self.selectedTower):
            self.changeTurn()
            self.lastTurnColor = self.board[self.selectedTower.y][self.selectedTower.x]
            self.selectLastTurnColorTower()

    def playerSelectDestination(self,pos):
        x = math.trunc(pos[0] / self.squareSizeX)
        y = math.trunc(pos[1] / self.squareSizeY)
        if self.squareIsEmpty(x,y):
            if not self.isThereATowerInFront(self.selectedTower,y,x) or not self.isTHereATowerInDiagonale(self.selectedTower,y,x):
                if self.NoRetreat(self.selectedTower,y):
                    self.selectedTower.y = y
                    self.selectedTower.x = x
                    self.lastTurnColor = self.board[y][x]
                    self.selectedTower = None
                    self.changeTurn()
                    if self.currentTurn > 0:
                        self.selectLastTurnColorTower()
                    else:
                        self.lastTurnColor = self.board[self.selectedTower.y][self.selectedTower.x]


import numpy as np
import re
import string
import ast

def preprocess_data(df):
    replacements = {'1': " one ", '2':" two ", '3':" three ", '4':" four ", '5':" five ", '6':" six ", '7':" seven ", '8':" eight ", '9':" nine ", '0':" zero "}
    df['English'] = df['English'].apply(lambda x: re.sub('(\d)', lambda m: replacements[m.group()], x))
    df['ASL Gloss'] = df['ASL Gloss'].apply(lambda x: re.sub('(\d)', lambda m: replacements[m.group()], x))
    df['English'] = df['English'].apply(lambda x: x.strip())
    df['ASL Gloss'] = df['ASL Gloss'].apply(lambda x: x.strip())
    df['English'] = df['English'].apply(lambda x: x.lower())
    df['ASL Gloss'] = df['ASL Gloss'].apply (lambda x: x.lower())
    df['English'] = df['English'].apply(lambda x: x.replace('  ', ' '))
    df['ASL Gloss'] = df['ASL Gloss'].apply(lambda x: x.replace('  ', ' '))
    df['English'] = df['English'].apply(lambda x: ''.join (ch for ch in x if ch not in set(string.punctuation)))
    df['ASL Gloss'] = df['ASL Gloss'].apply(lambda x: ''.join (ch for ch in x if ch not in set(string.punctuation)))
    df['English'] = df['English'].apply(lambda x : 'START_ ' + x + ' _END')

    return df

def get_variables(df):
    # Vocabulary of English
    all_eng_words = set()
    for eng in df['English']:
        for word in eng.split():
            if word not in all_eng_words:
                all_eng_words.add(word)

    # Vocabulary of ASL
    all_ASL_words = set()
    for asl in df['ASL Gloss']:
        for word in asl.split():
            if word not in all_ASL_words:
                all_ASL_words.add(word)

    # Max Length of source sequence and target sequence
    length_list=[]
    for l in df ['English']:
        length_list.append(len(l.split(' ')))
    max_length_tar = np.max(length_list)
    print("Max length target: ", max_length_tar)

    length_list=[]
    for l in df ['ASL Gloss']:
        length_list.append(len(l.split(' ')))
    max_length_src = np.max(length_list)
    print("Max length sorce: ", max_length_src)

    input_words = sorted(list(all_ASL_words))
    target_words = sorted(list(all_eng_words))

    # Calculate Vocab size for both source and target
    num_encoder_tokens = len(all_ASL_words) + 1
    num_decoder_tokens = len(all_eng_words) + 2

    # Create word to token dictionary for both source and target
    input_token_index = dict([(word, i+1) for i, word in enumerate(input_words)])
    target_token_index = dict([(word, i+1) for i, word in enumerate(target_words)])

    # Create token to word dictionary for both source and target
    reverse_target_char_index = dict((i, word) for word, i in target_token_index.items())

    return max_length_src, max_length_tar, num_encoder_tokens, num_decoder_tokens, input_token_index, target_token_index, reverse_target_char_index

def write_list_to_file(var_list):
    outputFile = open( "../myVars.txt", "w")
    outputFile.write(str(var_list))
    outputFile.flush()
    outputFile.close()

def read_list_from_file():
    inputFile = open( "../myVars.txt", "r")
    lines = inputFile.readlines()

    objects = []
    for line in lines:
        objects.append(ast.literal_eval(line))

    return objects[0][0], objects[0][1], objects[0][2], objects[0][3], objects[0][4], objects[0][5]


import tkinter as tk
from tkinter import messagebox
import sqlite3

# Create a database connection
conn = sqlite3.connect("library.db")
c = conn.cursor()

# Create the main application window
root = tk.Tk()
root.title("Reporting")
root.geometry("400x300")
root.config(bg="lightgray")

# Function to generate the list of available books report
def generate_available_books_report():
    c.execute("SELECT * FROM books WHERE id NOT IN (SELECT book_id FROM borrowings WHERE return_date IS NULL)")
    books = c.fetchall()

    report_text = ""
    if books:
        report_text = "Available Books:\n"
        for book in books:
            report_text += f"Title: {book[1]}\nAuthor: {book[2]}\nISBN: {book[3]}\nPublication Date: {book[4]}\n\n"
    else:
        report_text = "No available books."

    # Display the report in a message box
    messagebox.showinfo("Available Books Report", report_text)

# Function to generate the list of borrowed books report
def generate_borrowed_books_report():
    c.execute("SELECT * FROM books WHERE id IN (SELECT book_id FROM borrowings WHERE return_date IS NULL)")
    books = c.fetchall()

    report_text = ""
    if books:
        report_text = "Borrowed Books:\n"
        for book in books:
            report_text += f"Title: {book[1]}\nAuthor: {book[2]}\nISBN: {book[3]}\nPublication Date: {book[4]}\n\n"
    else:
        report_text = "No borrowed books."

    # Display the report in a message box
    messagebox.showinfo("Borrowed Books Report", report_text)

# Function to generate the list of overdue books report
def generate_overdue_books_report():
    c.execute("SELECT * FROM books WHERE id IN (SELECT book_id FROM borrowings WHERE return_date IS NULL AND due_date < DATE('now'))")
    books = c.fetchall()

    report_text = ""
    if books:
        report_text = "Overdue Books:\n"
        for book in books:
            report_text += f"Title: {book[1]}\nAuthor: {book[2]}\nISBN: {book[3]}\nPublication Date: {book[4]}\n\n"
    else:
        report_text = "No overdue books."

    # Display the report in a message box
    messagebox.showinfo("Overdue Books Report", report_text)

# Generate Available Books Report button
btn_available_books_report = tk.Button(root, text="Generate Available Books Report", command=generate_available_books_report, bg="lightgray", fg="black", font=("Arial", 12))
btn_available_books_report.pack()

# Generate Borrowed Books Report button
btn_borrowed_books_report = tk.Button(root, text="Generate Borrowed Books Report", command=generate_borrowed_books_report, bg="lightgray", fg="black", font=("Arial", 12))
btn_borrowed_books_report.pack()

# Generate Overdue Books Report button
btn_overdue_books_report = tk.Button(root, text="Generate Overdue Books Report", command=generate_overdue_books_report, bg="lightgray", fg="black", font=("Arial", 12))
btn_overdue_books_report.pack()

# Run the Tkinter event loop
root.mainloop()

# Close the database connection when the application is closed
conn.close()


#!/usr/bin/env python3
"""
Copy a gear test using hard links for the files to avoid wasting a
lot of space.  The files need to be hard links so they will show
up in the Docker container (symbolic links show up as symbolic links
to nowhere).
"""

import os
import shutil
import subprocess as sp
import argparse

def copy(src, dst):
    """ Copies a test directory, deletes all old log files.  """

    if os.path.isdir(src):

        try:
            # here's the beef:
            shutil.copytree(src, dst, copy_function=os.link)

        except Exception as e:
            LOG.error(e)
            print(e)
            msg='WARNING: continuing despite errors'
            print(msg)
            LOG.info('WARNING: continuing despite errors')

        # and remove the old test's logs (if any)
        shutil.rmtree(dst+'/logs')
        os.mkdir(dst+'/logs')

        # delete the hard-linked config.json and actually
        # copy it so it can be edited without modifying the
        # old config.
        os.remove(dst + '/config.json')
        shutil.copyfile(src + '/config.json',dst + '/config.json')

        msg = 'Copied test from\n  ' + src + '\nto\n  ' + dst
        print(msg)
        LOG.info(msg)

        msg = 'NOTE: all files were copied as HARD links except for \n'+\
              '"confid.json".  Unless you want to modify a file in the \n'+\
              'old test that was copied, DELETE the file and create a new one'
        print(msg)

    else:
        print('ERROR: "'+args.src+'" not found.  It should be in')
        print('ls '+TEST+'tests/')
        result = sp.run(['ls',TEST+'tests/'])

def init_by_copying():
    """ This is called from setup.py.  To let the user knonw that
    they can call copy_test.py from the command line, this does just that
    This is a whole lot of wrapping around the tiny bit of code above """

    print("Copying an existing test...\n")

    msg = "Choose a test to copy:\n"
    tests = os.listdir(TEST+'tests/')
    nn = 1
    dir_name = dict()
    choices = []
    for tt in tests:
        if tt[0] != '.' and tt[0] != '_':
            msg += "  "+str(nn)+") "+tt+"\n"
            dir_name[nn] = tt
            choices.append(str(nn))
            nn += 1

    not_done = True

    while not_done:

        ans = get_user_input(msg,"Which would you like to use?",choices)

        new_name = input('Please enter a name for the new test: ')

        print("The new test will be created with this command:\n")
        cmd = 'utils/copy_test.py '+dir_name[int(ans)]+' '+new_name
        print('  '+cmd+'\n')
        print('(You can run that command yourself instead of this script)')

        go_nogo = get_user_input("","",['Proceed','Re-enter','Quit?'])

        if go_nogo == 'p':
            not_done = False
        elif go_nogo == 'q':
            sys.exit()

    command = TEST+cmd # add full path
    print('Running: '+command)
    LOG.info('Running" '+command)
    command = [ w for w in command.split() ]
    result = sp.run(command)

if __name__ == '__main__':

    from find_gear import *
    from get_user_input import *

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("src",help="(old) source test direcory name (no path)")
    parser.add_argument("dst",help="(new) destination directory name")
    args = parser.parse_args()

    src = TEST+'tests/'+args.src
    dst = TEST+'tests/'+args.dst

    copy(src,dst)

else:

    from .find_gear import *
    from .get_user_input import *

# vi:set autoindent ts=4 sw=4 expandtab : See Vim, :help 'modeline'


from playwright.sync_api import Playwright, sync_playwright, expect

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    page = context.new_page()

    page.goto("https://einstructor.datasena.com/login")

    page.get_by_placeholder("Número Identificación").click()

    page.get_by_placeholder("Número Identificación").fill("1014737507")

    page.get_by_placeholder("Contraseña").click()

    page.get_by_placeholder("Contraseña").fill("1014737507")

    page.get_by_role("button", name="Ingresar").click()
    page.wait_for_url("https://einstructor.datasena.com/home")

    page.get_by_role("link", name=" Ejecutar evaluación").click()
    page.wait_for_url("https://einstructor.datasena.com/assessment")

    page.get_by_label("Digite el código de la evaluación").click()

    page.get_by_label("Digite el código de la evaluación").fill("FY9rqS2vxZ")

    page.get_by_role("button", name="Confirmar").click()

    page.locator(".btn").first.click()

    page.locator("#answers1").get_by_text("Siempre").click()

    page.locator("#answers2").get_by_text("Siempre").click()

    page.locator("#answers3").get_by_text("Siempre").click()

    page.locator("#answers4").get_by_text("Siempre").click()

    page.locator("#answers5").get_by_text("Siempre").click()

    page.locator("#answers6").get_by_text("Siempre").click()

    page.locator("#answers7").get_by_text("Siempre").click()

    page.locator("#answers8").get_by_text("Siempre").click()

    page.locator("#answers9").get_by_text("Siempre").click()

    page.locator("#answers10").get_by_text("Siempre").click()

    page.locator("#answers11").get_by_text("Siempre").click()

    page.locator("#answers12").get_by_text("Siempre").click()

    page.get_by_role("button", name="Enviar").click()

    page.get_by_role("button", name="Aceptar").click()

    page.get_by_role("link").nth(1).click()
    page.wait_for_url("https://einstructor.datasena.com/")

    # ---------------------
    context.close()
    browser.close()

with sync_playwright() as playwright:
    run(playwright)


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

from server.webserver import Webserver, App
from store import Store, load_store
from crawler import Crawler
#from myHTML import myHTML

class SearchApp(App):
    """
    Webanwendung für eine Suchmaschine auf einer Domain.

    Diese sehr einfache Anwendung demonstriert die Verwendung des Server-Frameworks.
    Die Klasse SearchApp benötigt zwei Methoden:
    1. Registrierung der Routen
    2. Definition eines Request-Handlers
    """
    def __init__(self, s, **kwargs):
        self.store = s
        App.__init__(self, **kwargs)  # super init

    def register_routes(self):
        self.add_route('', self.search)  # there is only one route for everything

    def pageStart(self):
        """Returns the start of a PageStart.
        """
        return """

"""

    def pageEnd(self):
        """Returns the HTML of the End ResultPage.
        """
        return """
"""

    def addFound(self, url, count ,title, teaser):
        """Returns a HTML of a found result.
        :param url the url.
        :param count the amount of found strings in the result
        :param title the title of the Page
        :param teaser a small teaser of a found result
        """
        msg = """

({amount}): """.format(amount=count) + title + """
""" #Header
        msg += """

{link}

""".format(
            domain=self.store.netloc, link=url) # The link

        msg += """
""" + teaser + """
""" #the teaser

        msg += """

"""  # horizonatal Line

        return msg

    #
    def search(self, request, response, pathmatch=None):
        """Search for query string.
        :param request the given request of the html.
        :param response where the response should be given to
        """
        msg = ''
        q = ''
        if 'q' in request.params:  # check if parameter is given
            q = request.params['q']

            #Regex Safe Query
            q = re.sub('[^\s\d\w]', '', q).strip() #only words, digits, whitespaces

            hitlist = self.store.search(q) #runs the search method
            msg = "

Ergebnis für '{}':
".format(q) #beginning of creating the response message

            msg += self.pageStart()
            if hitlist != None:
                #print(hitlist)
                for (url, values) in hitlist:
                    msg += self.addFound(url,values,self.store.pages[url]['title'],self.store.get_teaser(url, q))
            msg += self.pageEnd()

        response.send_template('templates/search/search.tmpl', {'q': q, 'netloc': self.store.netloc, 'msg': msg})

if __name__ == '__main__':
    # entry = 'https://www.inf.uni-osnabrueck.de'
    # entry = 'https://www.virtuos.uni-osnabrueck.de'
    entry = 'http://vm009.rz.uos.de'

    s = load_store(entry)
    if not s:
        s = Store(entry)
        c = Crawler(s)
        c.crawl()
        s.save()

    w = Webserver()
    w.add_app(SearchApp(s, prefix=''))
    w.serve()
    webbrowser.open_new_tab("http://localhost:8080/")


import openpyxl as pxl
wdict = pxl.load_workbook('C:/Users/m.shcherbina/PycharmProjects/ITOIUItransfer/dictionary_simple.xlsx')
wSdict = wdict.active
wbook = pxl.load_workbook('C:/Users/m.shcherbina/PycharmProjects/ITOIUItransfer/For_powershell_task_3_output.xlsx')
wSbook = wbook.active

replacedict = {}
for i in range(1, wSdict.max_row + 1):

    cell_value_class = wSdict.cell(i, 1).value
    cell_value_id = wSdict.cell(i, 2).value
    replacedict[cell_value_id] = cell_value_class
#    define[cell_value_id] = cell_value_class
#    replacedict.append(define)
print(replacedict)
print(wSdict.max_row)
j=0
for i in range(1, wSbook.max_row + 1):
   for key in replacedict:
      if wSbook.cell(i, 1).value == key:
        newCell = replacedict[key]
        wSbook.cell(i, 1).value = newCell
        j += 1
        print('Выполнена замена', key, 'на', replacedict[key], 'в строке', i)
wbook.save('C:/Users/m.shcherbina/PycharmProjects/ITOIUItransfer/output.xlsx')
print('Файл сохранен, выполнено', j, 'замен')


import shutil

import numpy as np
import torchvision.transforms as transforms

from globals import Globals
from mix import Ent
from utils import Rotate
from utils import mkdir, TMix, TGen, TExp

g = Globals()

mkdir(g.default_repo_dir)
shutil.rmtree(g.default_repo_dir + "labels", ignore_errors=True)
tasks = []

# Generate samples and features
if False:
    tasks.append(TGen('Gen', 'lsun', 'true', 9, 'resnet34'))
    tasks.append(TGen('Gen', 'lsun', 'DCGAN', 9, 'resnet34'))
    tasks.append(TGen('Gen', 'celeba', 'true', 24, 'resnet34'))
    tasks.append(TGen('Gen', 'celeba', 'DCGAN', 24, 'resnet34'))
    tasks.append(TGen('Gen', 'cifar10', 'true', 400, 'resnet34'))
    tasks.append(TGen('Gen', 'cifar10', 'WGAN', 1900, 'resnet34'))

    tasks.append(TGen('Gen', 'lsun', 'true', 9, 'vgg16'))
    tasks.append(TGen('Gen', 'lsun', 'DCGAN', 9, 'vgg16'))
    tasks.append(TGen('Gen', 'celeba', 'true', 24, 'vgg16'))
    tasks.append(TGen('Gen', 'celeba', 'DCGAN', 24, 'vgg16'))

    tasks.append(TGen('Gen', 'lsun', 'true', 9, 'inception_v3'))
    tasks.append(TGen('Gen', 'lsun', 'DCGAN', 9, 'inception_v3'))
    tasks.append(TGen('Gen', 'celeba', 'true', 24, 'inception_v3'))
    tasks.append(TGen('Gen', 'celeba', 'DCGAN', 24, 'inception_v3'))

trans = transforms.Compose([transforms.Scale(64), transforms.ToTensor(
), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trans_rand = transforms.Compose([transforms.Scale(64), transforms.Pad(4), transforms.RandomCrop(
    64), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trans_rotate = transforms.Compose([transforms.Scale(
    64), Rotate(-1), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

# Metrics on different mixtures
# Only `*_smax` features are suggested to be used for `Incep`, `ModeScore` and `FID`
if False:
    for sampleSize in [2000]:
        for data in ['cifar10', 'celeba', 'lsun']:
            if data == 'celeba':
                model = 'DCGAN24'
            if data == 'lsun':
                model = 'DCGAN9'
            if data == 'cifar10':
                model = 'WGAN1900'

            for mix_ratio in np.arange(0, 1.1, 0.1):
                dataList = []
                if mix_ratio > 0:
                    dataList.append(
                        Ent(mix_ratio, data, 'true_test', trans, imageMode=0))
                if 1 - mix_ratio > 0:
                    dataList.append(
                        Ent(1 - mix_ratio, data, model, None, dup=1, imageMode=0))

                for featureType in ['resnet34_conv', 'pix']:
                    tasks.append(
                        TMix('Mix', sampleSize, data, featureType, dataList))

                tasks.append(
                    TMix('Incep', sampleSize, data, 'resnet34_smax', dataList))
                tasks.append(
                    TMix('ModeScore', sampleSize, data, 'resnet34_smax', dataList))
                tasks.append(
                    TMix('FID', sampleSize, data, 'resnet34_smax', dataList))

# Metrics on different number of samples
if False:
    for sampleSize in [100, 200, 400, 800, 1600, 3200, 6400, 12800]:
        for data in ['celeba', 'lsun']:
            for featureType in ['resnet34', 'vgg16', 'inception_v3']:
                for foldername in ['DCGAN24' if data == 'celeba' else 'DCGAN9', 'true_test']:
                    dataList = []
                    dataList.append(Ent(1.0, data, foldername, trans))

                    tasks.append(
                        TMix('Mix', sampleSize, data, featureType + '_conv', dataList))
                    tasks.append(
                        TMix('Incep', sampleSize, data, featureType + '_conv', dataList))
                    tasks.append(
                        TMix('ModeScore', sampleSize, data, featureType + '_conv', dataList))
                    tasks.append(
                        TMix('FID', sampleSize, data, featureType + '_conv', dataList))

# For robustness
# When using `trans_rotate` and `trans_rand`, only resnet34 is used for feature extraction.
if False:
    for sampleSize in [2000]:
        for data in ['celeba', 'lsun']:
            if data == 'celeba':
                model = 'DCGAN24'
            if data == 'lsun':
                model = 'DCGAN9'

            for mix_ratio in np.arange(0, 1.1, 0.1):
                for image_mode in [1, 2]:
                    dataList = []
                    if mix_ratio > 0:
                        dataList.append(Ent(
                            mix_ratio, data, 'true_test', trans_rotate if image_mode == 2 else trans_rand, imageMode=image_mode))
                    if 1 - mix_ratio > 0:
                        dataList.append(
                            Ent(1 - mix_ratio, data, 'true_test2', None))

                    for featureType in ['resnet34_conv', 'pix']:
                        tasks.append(
                            TMix('Mix', sampleSize, data, featureType, dataList))

                    tasks.append(
                        TMix('Incep', sampleSize, data, 'resnet34_smax', dataList))
                    tasks.append(
                        TMix('ModeScore', sampleSize, data, 'resnet34_smax', dataList))
                    tasks.append(
                        TMix('FID', sampleSize, data, 'resnet34_smax', dataList))

# Mode collapse, mode drop, overfit
if True:
    for data in ['celeba', 'lsun']:
        for exp in ['collapse', 'drop', 'overfit']:
            tasks.append(TExp(exp, data))

print(len(tasks))
np.save(g.default_repo_dir + "tasks", tasks)


from termcolor import colored
from sqlalchemy import inspect
from ...model.kingdom import Kingdom
from ...model.city import City
from ...model.shop import Shop
from ...model.item import Item
from ...model.item_type import ItemType
from ...model.shop_type import ShopType
import os

def clear_terminal():
    _ = os.system("clear")

def add_entity(session, entity_class, context):
    entity_attributes = {}
    entity_columns = [column.key for column in entity_class.__table__.columns if column.key != 'id']

    parent_entity_name = get_parent_entity_name(entity_columns)
    if parent_entity_name:
        parent_entity = get_parent_entity(session, parent_entity_name, context)
        if parent_entity:
            entity_attributes[parent_entity_name.lower()] = parent_entity
            entity_columns.remove(f'{parent_entity_name.lower()}_id')

    for column in entity_columns:
        if column not in entity_attributes:
            value = get_column_value(session, entity_class, column)
            entity_attributes[column] = value

    new_entity = entity_class(**entity_attributes)
    session.add(new_entity)
    session.commit()
    print(colored(f"{entity_class.__name__} added successfully!", 'green'))
    clear_terminal()

def get_parent_entity_name(entity_columns):
    for column_name in entity_columns:
        if column_name.endswith('_id'):
            return column_name[:-3].capitalize()
    return None

def get_parent_entity(session, parent_entity_name, context):
    entity_mapping = {
    "Kingdom": Kingdom,
    "City": City,
    "Shop": Shop,
    "Item": Item,
    "ItemType": ItemType,
    "ShopType": ShopType
    }
    parent_entity_name_in_context = context.get(parent_entity_name)
    if parent_entity_name_in_context:
        parent_entity_class = entity_mapping[parent_entity_name]
        return session.query(parent_entity_class).filter_by(name=parent_entity_name_in_context).first()
    return None

def get_column_value(session, entity_class, column):
    if column == 'name':
        return get_unique_name(session, entity_class)
    else:
        return input(colored(f"{entity_class.__name__} {column}:", attrs=['bold']))

def get_unique_name(session, entity_class):
    while True:
        name = input(colored(f"{entity_class.__name__} name:", attrs=['bold']))
        existing_entity = session.query(entity_class).filter_by(name=name).first()
        if existing_entity:
            print(colored("Name already exists. Please enter a different name.", 'red'))
        else:
            return name

def get_foreign_key_column(entity_class, parent_entity_class):
    foreign_key_columns = []
    for column in entity_class.__table__.columns:
        if column.foreign_keys:
            for foreign_key in column.foreign_keys:
                if foreign_key.column.table.name == parent_entity_class.__tablename__:
                    foreign_key_columns.append(column)
    if not foreign_key_columns:
        raise ValueError(f"No foreign key columns found in {entity_class.__name__} referencing {parent_entity_class.__name__}")
    return foreign_key_columns[0]

def show_entities(session, entity_class, parent_entity):
    if parent_entity:
        parent_entity_id_field = get_foreign_key_column(entity_class, parent_entity.__class__)
        entities = session.query(entity_class).filter(getattr(entity_class, parent_entity_id_field.key) == parent_entity.id).all()
    else:
        entities = session.query(entity_class).all()

    if not entities:
        print(colored(f"No {entity_class.__name__} entities found.", 'red'))
    else:
        print(colored(f"Available {entity_class.__name__} entities:", 'cyan', attrs=['bold']))
        for entity_obj in entities:
            print(colored(entity_obj.name, 'yellow'))
        print("")


import torch

import numpy as np

from .basemodel_torch import BaseModelTorch
from .deepfm_lib.models.deepfm import DeepFM as DeepFMModel
from .deepfm_lib.inputs import SparseFeat, DenseFeat

'''
    DeepFM: A Factorization-Machine based Neural Network for CTR Prediction
     (https://www.ijcai.org/proceedings/2017/0239.pdf)

    Code adapted from: https://github.com/shenweichen/DeepCTR-Torch
'''

class DeepFM(BaseModelTorch):

    def __init__(self, params, args):
        super().__init__(params, args)

        if args.objective == "classification":
            print("DeepFM not yet implemented for classification")
            import sys
            sys.exit()

        if args.cat_idx:
            dense_features = list(set(range(args.num_features)) - set(args.cat_idx))
            fixlen_feature_columns = [SparseFeat(str(feat), args.cat_dims[idx])
                                      for idx, feat in enumerate(args.cat_idx)] + \
                                     [DenseFeat(str(feat), 1, ) for feat in dense_features]

        else:
            # Add dummy sparse feature, otherwise it will crash...
            fixlen_feature_columns = [SparseFeat("dummy", 1)] + \
                                     [DenseFeat(str(feat), 1, ) for feat in range(args.num_features)]

        self.model = DeepFMModel(linear_feature_columns=fixlen_feature_columns,
                                 dnn_feature_columns=fixlen_feature_columns,
                                 task=args.objective, device=self.device, dnn_dropout=self.params["dnn_dropout"],
                                 gpus=self.gpus)

    def fit(self, X, y, X_val=None, y_val=None):
        X = np.array(X, dtype=np.float)
        X_dict = {str(name): X[:, name] for name in range(self.args.num_features)}

        X_val = np.array(X_val, dtype=np.float)
        X_val_dict = {str(name): X_val[:, name] for name in range(self.args.num_features)}

        if self.args.objective == "binary":
            loss = "binary_crossentropy"
            metric = "binary_crossentropy"
            labels = [0, 1]
        elif self.args.objective == "regression":
            loss = "mse"
            metric = "mse"
            labels = None

        self.model.compile(optimizer=torch.optim.AdamW(self.model.parameters()),
                           loss=loss, metrics=[metric])

        # Adding dummy spare feature
        if not self.args.cat_idx:
            X_dict["dummy"] = np.zeros(X.shape[0])
            X_val_dict["dummy"] = np.zeros(X_val.shape[0])

        loss_history, val_loss_history = self.model.fit(X_dict, y, batch_size=self.args.batch_size,
                                                        epochs=self.args.epochs,
                                                        validation_data=(X_val_dict, y_val), labels=labels,
                                                        early_stopping=True,
                                                        patience=self.args.early_stopping_rounds)
        return loss_history, val_loss_history

    def predict_helper(self, X):
        X = np.array(X, dtype=np.float)
        X_dict = {str(name): X[:, name] for name in range(self.args.num_features)}

        # Adding dummy spare feature
        if not self.args.cat_idx:
            X_dict["dummy"] = np.zeros(X.shape[0])
        return self.model.predict(X_dict, batch_size=self.args.batch_size)

    @classmethod
    def define_trial_parameters(cls, trial, args):
        params = {
            "dnn_dropout": trial.suggest_float("dnn_dropout", 0, 0.9),
        }
        return params

        # dnn_dropout, l2_reg_linear, l2_reg_embedding, l2_reg_dnn, dnn_hidden_units?


import cv2
import numpy as np
import onnxruntime
from swap_mukham.utils.device import OnnxInferenceSession

class Occluder(OnnxInferenceSession):
    def __init__(self, *args, **kwargs):
        super().__init__(**kwargs)

        inputs = self.session.get_inputs()
        self.input_name = inputs[0].name

        if "in_face" in self.input_name:
            # xseg occluder
            self.crop_size = inputs[0].shape[1:3]
            self.pre_order = (0, 1, 2, 3)
            self.post_order = (0, 1, 2)
        else:
            # generic occluder
            self.crop_size = (256, 256)
            self.pre_order = (0, 3, 1, 2)
            self.post_order = (1, 2, 0)

    def predict(self, img):
        img_size = img.shape[:2]
        img = cv2.resize(img, self.crop_size)
        img = np.expand_dims(img, axis=0).astype("float32") / 255
        img = img.transpose(*self.pre_order)

        mask = self.session.run(None, {self.input_name: img})[0][0]
        mask = mask.transpose(*self.post_order)
        mask = mask.clip(0, 1).astype("float32")
        mask = cv2.resize(mask, img_size)

        return mask

    def delete_session(self):
        if hasattr(self, "session"):
            del self.session


from django.db import models

# Create your models here.
from django.contrib.auth import get_user_model

User = get_user_model()

class Post(models.Model):
    text = models.TextField(
        verbose_name='Текст поста',
        help_text='Напишите что-нибудь'
    )
    pub_date = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Дата публикации'
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='Автор поста'
    )
    group = models.ForeignKey(
        'Group',
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name='Группа',
        blank=True,
        null=True,
        help_text='Здесь можно выбрать группу'
    )

    class Meta:
        ordering = ('-pub_date',)
        default_related_name = 'posts'
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'

class Group(models.Model):
    title = models.CharField(
        max_length=200,
        verbose_name='Заголовок'
    )
    slug = models.SlugField(
        null=False,
        unique=True
    )
    description = models.TextField(
        verbose_name='Описание группы'
    )

    def __str__(self):
        return self.title


from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, Panel, Slope, PreText, Paragraph, Div
from bokeh.layouts import column, row
import numpy as np
import statsmodels.formula.api as sm
from statsmodels.tsa.stattools import coint
from scipy.odr import *

class Linreg:
    def __init__(self, data):
        self.source = ColumnDataSource(data=dict(date=[], Close=[], Norm=[], Time=[], Colors=[]))
        self.xcorrsouce= ColumnDataSource()
        self.xcorrsouce2 = ColumnDataSource()
        self.source.data = self.source.from_df(data[['t1', 't2', 't1_normal', 't2_normal', 'Time', 'Colors']])

        self.t1 = data.keys()[0]
        self.t2 = data.keys()[2]

        linreg = np.polyfit(data.t1, data.t2, 1)
        self.gradient_ols = linreg[0]
        self.intercept_ols = linreg[1]
        self.smols = sm.ols(formula="t2 ~ t1", data=data[['t1', 't2']]).fit()
        self.tls_out = self.tls(data.t1, data.t2)
        self.gradient_tls=self.tls_out.beta[0]
        self.intercept_tls = self.tls_out.beta[1]
        self.smols_summary=str(self.smols.summary(yname=self.t2, xname=['Intercept','Gradient'],  title=str("Ordinary least squares of " + self.t2 + " on " + self.t1)))
        self.tls_summary = "\n Total least squares: \n" + "slope: " + str(self.tls_out.beta[0]) + " intercept: " + str(self.tls_out.beta[1])

        self.tools = 'reset'

        self.p = figure(plot_width=450, plot_height=450, tools='reset')
        self.p.scatter(x='t1', y='t2', marker='asterisk', size=5, color='Colors', alpha=0.6,  source=self.source)
        self.p.circle('t1', 't2', size=2, source=self.source, selection_color="orange", alpha=0.2,  selection_alpha=0.2)

        self.slope_ols = Slope(gradient=self.gradient_ols, y_intercept=self.intercept_ols, line_color='green', line_dash='dashed', line_width=2.5)
        self.slope_tls = Slope(gradient=self.gradient_tls, y_intercept=self.intercept_tls, line_color='blue', line_dash='dashed', line_width=2.5)

        self.p.add_layout(self.slope_ols)
        self.p.add_layout(self.slope_tls)
        self.p.xaxis.axis_label = self.t1
        self.p.yaxis.axis_label = self.t2

        score, pvalue, _ = coint(data.t1, data.t2)
        self.cointext = "coint: " + str(pvalue)
        self.stats = PreText(text='', width=750)

        corrcoeff = np.corrcoef(data.t1, data.t2)[0][1]
        self.filedatetext1 = data.t1.index[:1][0].__str__().split()[0]
        self.filedatetext2 = data.t2.index[:1][0].__str__().split()[0]
        if self.filedatetext1 != self.filedatetext2:
            self.filedatetext3 = " File enddate diff!"
        else:
            self.filedatetext3 = " OK"

        #self.stats.text = str(data[[self.t1, self.t2, self.t1 + '_normal', self.t2 + '_normal']].describe()) + "\nEOF    " + self.filedatetext1 +"   " + self.filedatetext2 + self.filedatetext3 + "\ncorrelation : " + str(corrcoeff)
        self.stats.text = self.smols_summary + "\n" + self.tls_summary + "\nEOF    " + self.filedatetext1 +"   " + self.filedatetext2 + self.filedatetext3 + "\ncorrelation : " + str(corrcoeff) + "\n" + self.cointext
        self.p.grid.grid_line_color = None
        self.p.background_fill_color = "#eedddd"

        self.h = figure(title="Cross Correlation", background_fill_color="#E8DDCB", plot_height=250, plot_width=480, y_range=(-1, 1))
        lags, ccor = self.crosscorr(data.t1, data.t2)
        self.xcorrsouce2.data = {'lags': lags, 'ccor':ccor}
        self.verticalLine = Slope(gradient=1, y_intercept=0, line_color='black', line_dash='dashed',line_width=1.5)
        self.h.add_layout(self.verticalLine)

        hist, edges = np.histogram(ccor, density=True, bins=50)
        self.xcorrsouce.data = {'hist': hist, 'left': edges[:-1], 'right':edges[1:]}

        #self.h.quad(top='hist', bottom=0, left='left', right='right', fill_color="#036564", line_color="#033649", source = self.xcorrsouce)
        self.h.line('lags', 'ccor', source=self.xcorrsouce2, line_width=2, color='red', alpha=0.4)
        self.h.ygrid.band_fill_alpha = 0.1
        self.h.ygrid.band_fill_color = "navy"

        layout = row(column(self.p,self.h),self.stats)
        self.tab = Panel(child=layout, title='Linear Regression')

    def tls(self, x, y):
        def linear_func(p, x):
            m, c = p
            return m * x + c

        # Create a model for fitting.
        linear_model = Model(linear_func)

        # Create a RealData object using our initiated data from above.
        data = RealData(x, y)

        # Set up ODR with the model and data.
        odr = ODR(data, linear_model, beta0=[0., 1.])

        # Run the regression.
        out = odr.run()
        return out

    def crosscorr(self, x, y):
        npts = x.count()
        lags = np.arange(-npts + 1, npts)
        ccov = np.correlate(x - x.mean(), y - y.mean(), mode='full')
        ccor = ccov / (npts * x.std() * y.std())
        return lags, ccor

    def update(self, data):
        print("linreg updating...")
        self.source.data = self.source.from_df(data[['t1', 't2', 't1_normal', 't2_normal', 'Time', 'Colors']])

        crosscorr = np.correlate(data.t1, data.t2, "full")
        hist, edges = np.histogram(crosscorr, density=True, bins=50)
        self.xcorrsouce.data = {'hist': hist, 'left': edges[:-1], 'right':edges[1:]}
        lags, ccor = self.crosscorr(data.t1, data.t2)
        self.xcorrsouce2.data = {'lags': lags, 'ccor':ccor}

        self.t1 = data.keys()[0]
        self.t2 = data.keys()[2]
        corrcoeff = np.corrcoef(data.t1, data.t2)[0][1]

        self.smols = sm.ols(formula="t2 ~ t1", data=data[['t1', 't2']]).fit()
        self.tls_out = self.tls(data.t1, data.t2)
        #for cointegration
        score, pvalue, _ = coint(data.t1, data.t2)
        self.cointext = "coint: " + str(pvalue)
        print("self.cointext", self.cointext)

        self.smols_summary=str(self.smols.summary(yname=self.t2, xname=['Intercept','Gradient'], title=str("Ordinary least squares of " + self.t2 + " on " + self.t1)))
        self.tls_summary = "\n Total least squares: \n" + "slope: " + str(self.tls_out.beta[0]) + " intercept: " + str(self.tls_out.beta[1])
        self.stats.text = self.smols_summary + "\n" + self.tls_summary + "\nEOF    " + self.filedatetext1 +"   " + self.filedatetext2 + self.filedatetext3 + "\ncorrelation : " + str(corrcoeff) + "\n" + self.cointext

        self.filedatetext1 = data.t1.index[:1][0].__str__().split()[0]
        self.filedatetext2 = data.t2.index[:1][0].__str__().split()[0]
        if self.filedatetext1 != self.filedatetext2:
            self.filedatetext3 = " File enddate diff!"
        else:
            self.filedatetext3 = " OK"

        self.stats.text = self.smols_summary + "\n" + self.tls_summary + "\nEOF    " + self.filedatetext1 +"   " + self.filedatetext2 + self.filedatetext3 + "\ncorrelation : " + str(corrcoeff) + "\n" + self.cointext

        self.p.xaxis.axis_label = self.t1
        self.p.yaxis.axis_label = self.t2
        #Slope update
        linreg = np.polyfit(data.t1, data.t2, 1)
        self.gradient_ols = linreg[0]
        self.intercept_ols = linreg[1]
        self.slope_ols.gradient = self.gradient_ols
        self.slope_ols.y_intercept = self.intercept_ols
        self.gradient_tls=self.tls_out.beta[0]
        self.intercept_tls = self.tls_out.beta[1]
        self.slope_tls.gradient = self.gradient_tls
        self.slope_tls.y_intercept = self.intercept_tls


# programmers - Lv2 - 다리를 지나는 트럭 (2020-09-15)
# https://programmers.co.kr/learn/courses/30/lessons/42583

import sys
sys.stdin = open("programmers/[Lv2]다리를지나는트럭.txt",'r')
from collections import deque

def solution(bridge_length, weight, truck_weights):
    drive_weight = deque() # 다리에 운전중인 트럭들의 무게
    drive_len = deque() # 다리에 운전중인 트럭들의 위치

    drive_weight.append(truck_weights.pop(0))
    drive_len.append(1)

    answer = 1 # 총 시간

    while(drive_weight):

        if drive_len[0] >= bridge_length :  # 맨 앞의 트럭이 다리를 건넜을때,
            drive_len.popleft()
            drive_weight.popleft()

        for i in range(len(drive_len)): # 트럭의 위치를 한칸씩 증가
            drive_len[i] += 1

        if len(truck_weights) > 0 : # 대기중인 트럭 있는지 여부
            if truck_weights[0] + sum(drive_weight) <= weight: # 대기중 첫 트럭과 운행중 트럭의 합이 weight가 걸리는지
                drive_len.append(1)
                drive_weight.append(truck_weights.pop(0))

        answer += 1

    return answer

T = int(input())
for _ in range(T):
    bridge_length, weight = map(int, input().split())
    truck_weights = list(map(int, input().split()))

    print(solution(bridge_length, weight, truck_weights))

[Lv2]다리를지나는트럭.py


import numpy as np
from scipy.stats import pearsonr

def zeroElimination(lst):
    for i in range(len(lst)):
        if list[i] == 0:
            list[i] = 0.0001

def regressionValues(strategyDict, columns):
    listOfReqVal = ['dBTC ', 'd24BTC ', 'dMarket ', 'dM24 ', 'bvsv ', 'dBTC5m ', 'Pump1H ', 'Dump1H ', 'd24h ', 'd3h ',
                    'd1h ', 'd15m ', 'd5m ', 'd1m ', 'dBTC1m ', 'Vd1m ']
    tempListOFprofit = []
    tempListSecondParamValForStrat = []
    tempListSecondParamValForEl = []
    tempCorrValList = []
    profitDict = {}
    secondparamDict = {}
    corrDict = {}
    el = 0
    # i = 0
    for stratName in strategyDict[1]:
        # this for is needed to iterate over every strategy
        # in it we calculate regression for this strategies
        while el < strategyDict[1][stratName].__len__():  # el is number of trades in strategy
            tempListOFprofit.append(int(strategyDict[1][stratName][el][1][6]))
            # we add the value of profit of every
            # trade (num of trade is el) of the strategy we are currently on
            # (strategy name iterates on first for by stratName value)
            el = el + 1
        # i = i + 1
        # service check of list
        # print(' Num of str: ' + str(i) + ' | Num of elem in list: ' + str(el)
        #      + ' | list: ' + str(listOfprofit)
        # regrassion calculations
        el = 0

        for val in listOfReqVal:
            while el < strategyDict[1][stratName].__len__():
                index = columns.index(val)
                # тут по порядку для каждой сделки все данные listOfReqVal
                tempListSecondParamValForEl.append(strategyDict[1][stratName][el][1][int(index)])
                el = el + 1
            el = 0
            tempListSecondParamValForStrat.append(tempListSecondParamValForEl)
            tempListSecondParamValForEl = []

        secondparamDict[stratName] = tempListSecondParamValForStrat  # list with all the market data from log file
        profitDict[stratName] = tempListOFprofit  # data for regression calculation
        tempListSecondParamValForStrat = []
        tempListOFprofit = []

    for stratName in strategyDict[1]:
        Y = np.array(profitDict[stratName])  # Y -  dependent variables whose values are to be predicted
        for el in listOfReqVal:  # параметры рынка
            X = np.array(secondparamDict[stratName][listOfReqVal.index(el)])
            # X : numpy array or sparse matrix of shape [n_samples,n_features]
            if 0 in X:
                zeroElimination(X)
            if X.__len__() < 1:
                tmcor = 'Not enough data'
                tempCorrValList.append(tmcor)
            elif X.__len__() > 1:
                tmcor = pearsonr(X, Y)
                tempCorrValList.append(tmcor[0])
            tmcor = []
            # print(tmcor[1])
        corrDict[stratName] = tempCorrValList
        tempCorrValList = []

    # for stratName in strategyDict[1]:
    #     print('\nCorrelations for strategy ' + str(stratName))
    #     if corrDict[stratName].__len__() == 0:
    #         print('Not Enough data')
    #     else:
    #         for el in listOfReqVal:
    #             print('parameter: ' + str(el) + ' is ' + '{0:g}'.format(corrDict[stratName][listOfReqVal.index(el)]))

    # print('\n')

    return corrDict, listOfReqVal

# TODO
#   X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
#                 # X_train = X_train.reshape(-1, 1)
#                 # y_train = y_train.reshape(-1, 1)
#                 # regressor = LinearRegression()
#                 # regressor.fit(X_train, y_train)
#             #y_pred = regressor.predict(X_test)
#             #df_pred = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
#             #print(df_pred)
#             # Y_pred = linearRegression.predict(X)  # make predictions\

# TODO How to print graph
#     # plt.scatter(X, Y)
#     # plt.plot(X, Y_pred, color='red')
#     # plt.title('Strategy ' + str(stratName) + ', regression for ' + str(el))
#     # plt.xlabel('profit')
#     # plt.ylabel(el)
#     # plt.show()
#     # print(profitDict[stratName]) np.array(
#     # print(secondparamDict[stratName][el])


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

import os
import subprocess
import sys
import time
import vlc

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio, Gdk, GLib

class Handler:

    def on_play_here_realize(self, widget):
        vlcOptions = "--no-xlib"
        self.win_id = widget.get_window().get_xid()
        self.setup_player(vlcOptions)
        self.player.audio_set_mute(False)
        self.is_playing = False

    def on_rotate_toggled(self, widget):
        pos = self.player.get_position()
        self.player.stop()
        self.player.release()
        self.vlcInstance.release()
        if widget.get_active():
            vlcOptions = "--no-xlib --video-filter=transform{type=180}"
        else:
            vlcOptions = "--no-xlib"
        self.setup_player(vlcOptions)
        self.player.set_mrl(self.video)
        self.player.play()
        self.player.set_position(pos)
        if not self.is_playing:
            time.sleep(.05)
            self.player.pause()

    def setup_player(self, options):
        self.vlcInstance = vlc.Instance(options)
        self.player = self.vlcInstance.media_player_new()
        self.player.set_xwindow(self.win_id)

    def on_backward_clicked(self, widget):
        skip_pos = go.slider.get_value() - 10
        if skip_pos < 0:
            self.player.set_position(0)
            go.slider.set_value(0)
        else:
            self.player.set_position(skip_pos / 100)
            go.slider.set_value(skip_pos)

    def on_forward_clicked(self, widget):
        skip_pos = go.slider.get_value() + 10
        if skip_pos > 100:
            self.player.pause()
            self.player.set_position(0.99)
            go.slider.set_value(100)
        else:
            self.player.set_position(skip_pos / 100)
            go.slider.set_value(skip_pos)

    def on_playpause_togglebutton_toggled(self, widget):
        if widget.get_active():
            img = Gtk.Image.new_from_icon_name(Gtk.STOCK_MEDIA_PLAY,
                                               Gtk.IconSize.BUTTON)
            widget.set_property("image", img)
            self.is_playing = False
        else:
            img = Gtk.Image.new_from_icon_name(Gtk.STOCK_MEDIA_PAUSE,
                                               Gtk.IconSize.BUTTON)
            widget.set_property("image", img)
            self.is_playing = True
        self.player.pause()
        GLib.timeout_add(1000, self.update_slider)

    def on_vbutton_clicked(self, widget):
        self.video = "file://" + os.path.abspath("mediaplayer.avi")
        self.duration = go.get_duration(self.video)
        self.player.set_mrl(self.video)
        self.is_playing = True
        go.slider.set_value(0)
        go.obj("playpause_togglebutton").set_active(False)
        go.obj("playpause_togglebutton").set_sensitive(True)
        go.obj("mute").set_sensitive(True)
        go.obj("rotate").set_sensitive(True)
        self.player.play()
        GLib.timeout_add(1000, self.update_slider)

    def on_ibutton_clicked(self, widget):
        image = "file://" + os.path.abspath("mediaplayer.jpg")
        self.player.set_mrl(image)
        self.is_playing = False
        self.player.play()
        go.obj("playpause_togglebutton").set_sensitive(False)
        go.obj("mute").set_sensitive(False)
        go.obj("rotate").set_sensitive(False)

    def on_mute_toggled(self, widget):
        if widget.get_active():
            widget.set_label("Unmute")
        else:
            widget.set_label("Mute")
        self.player.audio_toggle_mute()

    def on_progress_change_value(self, widget, scroll, value):
        self.player.set_position(value / 100)
        widget.set_value(value)

    def update_slider(self):
        if not self.is_playing:
            return False # cancel timeout
        else:
            pos = go.slider.get_value()
            new_pos = (pos + 100 / self.duration)
            go.slider.set_value(new_pos)
            if new_pos > 100:
                self.is_playing = False
        return True # continue calling every x milliseconds

class VlcPlayer:

    def __init__(self):
        self.app = Gtk.Application.new("org.media.player", Gio.ApplicationFlags(0))
        self.app.connect("activate", self.on_app_activate)

    def on_app_activate(self, app):
        # setting up builder
        builder = Gtk.Builder()
        builder.add_from_file("20_vlc_player.glade")
        builder.connect_signals(Handler())
        self.obj = builder.get_object
        # slider position is float between 0..100
        self.slider = self.obj("progress")
        window = self.obj("window")
        window.set_application(app)
        window.show_all()

    def get_duration(self,video):
        command = ["ffprobe",
                   "-v", "error",
                   "-show_entries", "format=duration",
                   "-of", "default=noprint_wrappers=1:nokey=1",
                   video,
                   ]
        ffprobe_cmd = subprocess.run(command, stdout=subprocess.PIPE)
        # stdout of subprocess is byte variable, convert into float then into integer
        return int(float(ffprobe_cmd.stdout.decode()))

    def run(self, argv):
        self.app.run(argv)

go = VlcPlayer()
go.run(None)


import pandas as pd, DataBase, DataBase_wheels
from excel2py import xl2PM

def df(x,kwargs):
	"""
	Modify x using kwargs.
	"""
	return x if x not in kwargs else kwargs[x]

class nt:
	"""
	Small class of nesting trees
	"""
	def __init__(self,tree_name="",tree=None,kwargs_database={},**kwargs):
		self.name= tree_name
		self.tree=tree
		self.type_io = 'input'
		self.version = 'std'
		self.n = 'n'
		self.nn = 'nn'
		self.nnn = 'nnn'
		self.map_ = 'map_'+self.name # map branches to knots
		self.kno = 'kno_'+self.name # knots
		self.bra = 'bra_'+self.name # branches
		self.inp = 'inp_'+self.name # inputs: Branch, not knot
		self.out = 'out_'+self.name # outputs: Knot, not branch.
		self.temp_namespace = None # Dictionary/mapping that can be applied to pandas indices.
		self.update(kwargs)
		if self.type_io=='input' and 'type_f' not in kwargs:
			self.type_f = 'CES' # set default type to ces
		elif self.type_io=='output' and 'type_f' not in kwargs:
			self.type_f = 'CET' # set default type to cet
		self.database = DataBase.GPM_database(alias=pd.MultiIndex.from_tuples([(self.n, self.nn), (self.n, self.nnn)]),**{**{'name': self.name},**kwargs_database})

	def apply_namespace(self):
		if self.temp_namespace is not None:
			return DataBase_wheels.small_updates.set_values(self.database,self.n,self.temp_namespace)

	def run_all(self,Q2P=None,**kwargs):
		self.mapping_from_tree()
		self.set_from_tree()
		self.knots_from_tree()
		self.branches_from_tree()
		self.inputs_from_tree()
		self.outputs_from_tree()
		self.database.update_aliased_sets(ign_alias=False)
		if self.version =='Q2P':
			self.version_Q2P(Q2P,**kwargs)
		self.apply_namespace()

	def mapping_from_tree(self):
		temp = []
		for key in self.tree:
			temp += [(value,key) for value in self.tree[key]]
		self.database[self.map_] = pd.MultiIndex.from_tuples(temp,names=[self.n,self.nn])
		self.database[self.map_].name = self.map_

	def set_from_tree(self):
		temp = []
		for key in self.tree:
			temp += self.tree[key]+[key]
		self.database[self.n] = pd.Index(temp,name=self.n).unique()

	def knots_from_tree(self):
		self.database[self.kno] = pd.Index(set(self.database.get(self.map_).get_level_values(1)),name=self.n)

	def branches_from_tree(self):
		self.database[self.bra] = pd.Index(set(self.database.get(self.map_).get_level_values(0)),name=self.n)

	def inputs_from_tree(self):
		self.database[self.inp] = pd.Index(set(self.database.get(self.map_).get_level_values(0))-set(self.database.get(self.map_).get_level_values(1)),name=self.n)

	def outputs_from_tree(self):
		self.database[self.out] = pd.Index(set(self.database.get(self.map_).get_level_values(1))-set(self.database.get(self.map_).get_level_values(0)),name=self.n)

	def update(self,kwargs):
		for key,value in kwargs.items():
			setattr(self,key,value)

	@staticmethod
	def tree_from_mu(mu):
		return {x: mu.index.get_level_values(0)[mu.index.get_level_values(1)==x].to_list() for x in mu.index.get_level_values(1).unique()}

	def version_Q2P(self,q2p,q2pname=None,q2p_agg_name =None,OnlyQname=None):
		"""
		Adjusts the tree to a version where prices and quantities are not defined over the same sets.
		A mapping q2p indicates a subset of q-elements, that are essentially the same, and thus they face the same price.
		The following adjustments are made:
			- q2p are added to the database, as well as its name (mapping).
			- The aggregates that q-elements are mapped to are defined.
			- Create new subset of elements, that prices are not defined over (q-part).
			- Update inputs to include the elements from the q2p mapping (p-part).
			- The mapping q2p are automatically updated to include '(x,x)' mappings, in case the (p,q) sets are overlapping.
			- Update the set of all elements in the sector, to include the (potentially) new ones from q2p.
			- Add the new elements that prices are defined over to 'inputs'.
			- Update 'version' of tree (default is 'std') to 'QPS'.
		"""
		self.q2p = 'q2p_'+self.name if q2pname is None else q2pname
		self.q2p_agg = 'q2p_agg_'+self.name if q2p_agg_name is None else q2p_agg_name
		self.OnlyQ = 'OnlyQ_'+self.name if OnlyQname is None else OnlyQname # name of subset with only Q defined over it - not P.
		self.database[self.q2p_agg] = pd.Index(q2p.get_level_values(1).unique(), name=self.n) # add aggregate part.
		self.database[self.inp] = pd.Index(set(self.database.get(self.inp)) - set(q2p.get_level_values(0)), name =self.n)
		self.database[self.OnlyQ] = pd.Index(q2p.get_level_values(0).unique(), name=self.n)
		self.database[self.inp] = pd.Index(set(self.database.get(self.inp)).union(set(q2p.get_level_values(1))), name=self.n)
		# Expand mapping n2nn with ('x'-'x') elements for overlapping combinations of the two sets (p,q):
		self.database[self.q2p] = q2p.union(pd.MultiIndex.from_tuples([(x,x) for x in set(self.database.get(self.n))-set(q2p.get_level_values(0))], names = [self.n, self.nn]))
		self.database[self.n] = pd.Index( self.database.get(self.n).union(
												self.database.get(self.q2p).get_level_values(0)).union(
												self.database.get(self.q2p).get_level_values(1)),
												name = self.n).unique()
		self.version='Q2P'

class tree_from_data(nt):
	"""
	Initialize tree from data, where data is the file-path for an excel file.
	"""
	def __init__(self,data_path,sheet,sym_name='mu',rtype='vars',tree_name="",**kwargs):
		symbol = xl2PM.pm_from_workbook(data_path,{sheet:rtype})[sym_name]
		super().__init__(tree=nt.tree_from_mu(symbol),tree_name=tree_name,**{**{'n':symbol.domains[0], 'nn': symbol.domains[1]}},**kwargs)


"""
Practical programming Chapter 10 Exercise 3

**Instruction**
All of the file-reading functions we have seen in this chapter read forward
through the file from the first character or line to the last.
Complete P2 function that would read from the last line through a file
and return a list whose elements are lines of the input file from the last.

For example, when you run P2 on alkaline_metals.txt (same text file as P1),
it should return
['radium 88 226', 'barium 56 137.327\n', 'strontium 38 87.62\n', 'calcium 20 20.078\n', 'magnesium 12 24.305\n', 'beryllium 4 9.012\n']

"""
#import os
#os.chdir('C:\\Users\\user\Desktop\김동현\수업\데사컴\HW5')
def P2(filename: str) -> list:
    L1 = []
    L2 = []
    with open(filename, 'r') as lines:
        for i in lines:
            L1.append(i)
        for i in range(len(L1)):
            L2.append(L1[len(L1)-i-1])
        return L2


"""
    ----------------------------------------
    PyPlastimatch

    Viz tools for notebook testing
    ----------------------------------------

    ----------------------------------------
    Author: Dennis Bontempi
    Email:  dbontempi@bwh.harvard.edu
    ----------------------------------------

"""

import numpy as np
import ipywidgets as ipyw
import matplotlib.pyplot as plt

from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch

class AxialSliceFigure:
  """
  Base class for the interactive slice-wise visualisation widgets

  Init of all the figure parameters that are always set.

  @Params:
    ct_cmap - required : colormap for the CT viz.
    figsize - required : size of the figure (in inches).
    dpi     - required : DPI of the figure.
    min_hu  - required : minimum HU to be visualised
    max_hu  - required : maximum HU to be visualised
  """

  def __init__(self, ct_cmap, figsize, dpi, min_hu, max_hu):

    self.ct_cmap = ct_cmap
    self.figsize = figsize
    self.dpi = dpi

    self.min_hu = min_hu
    self.max_hu = max_hu

  def views(self):
    """
    method description goes here

    """

    ipyw.interact(self.plot_slice,
                  axial_idx = ipyw.IntSlider(min = 0, max = self.max_axial,
                                             step = 1, continuous_update = True,
                                             description = 'Axial slice:'))

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

class AxialSliceComparison(AxialSliceFigure):
  """
  class description goes here

  """

  def __init__(self, ct_volume_left, ct_volume_right,
               title_left = "", title_right = "",
               ct_cmap = "gray", figsize = (12, 12), dpi = 100,
               min_hu = -1024, max_hu = 3072):

    super().__init__(ct_cmap, figsize, dpi, min_hu, max_hu)

    # the only constraint should be on the number of axial slice of the volumes to visualise
    assert ct_volume_left.shape[0] == ct_volume_right.shape[0]

    self.ct_volume_left = ct_volume_left
    self.ct_volume_right = ct_volume_right
    self.max_axial = self.ct_volume_left.shape[0] - 1

    self.title_left = title_left
    self.title_right = title_right

    ipyw.interact(self.views)

  def plot_slice(self, axial_idx):
    """
    method description goes here

    """

    fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize = self.figsize, dpi = self.dpi)

    # plot CT axial slices
    ax_left.set_title(self.title_left)
    ax_left.imshow(self.ct_volume_left[axial_idx, :, :], cmap = self.ct_cmap,
                   vmin = self.min_hu, vmax = self.max_hu)

    ax_right.set_title(self.title_right)
    ax_right.imshow(self.ct_volume_right[axial_idx, :, :], cmap = self.ct_cmap,
                    vmin = self.min_hu, vmax = self.max_hu)

    plt.subplots_adjust(hspace = 0.2)
    plt.show()

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

class AxialSliceSegmaskComparison(AxialSliceFigure):
  """
  class description goes here

  """

  def __init__(self, ct_volume, segmask_ai_dict, segmask_manual_dict,
               segmask_cmap_dict, segmask_alpha = 0.6, title_left = "", title_right = "",
               ct_cmap = "gray", figsize = (12, 12), dpi = 100,
               min_hu = -1024, max_hu = 3072):

    super().__init__(ct_cmap, figsize, dpi, min_hu, max_hu)

    self.ct_volume = ct_volume
    self.max_axial = self.ct_volume.shape[0] - 1

    self.segmask_ai_dict = segmask_ai_dict
    self.segmask_manual_dict = segmask_manual_dict

    self.segmask_cmap_dict = segmask_cmap_dict
    self.segmask_alpha = segmask_alpha

    self.title_left = title_left
    self.title_right = title_right

    ipyw.interact(self.views)

  def plot_slice(self, axial_idx):
    """
    method description goes here

    """

    fig, (ax_ai, ax_manual) = plt.subplots(1, 2, figsize = self.figsize, dpi = self.dpi)

    # plot CT axial slices
    ax_ai.set_title(self.title_left)
    ax_ai.imshow(self.ct_volume[axial_idx, :, :], cmap = self.ct_cmap,
                 vmin = self.min_hu, vmax = self.max_hu)

    ax_manual.set_title(self.title_right)
    ax_manual.imshow(self.ct_volume[axial_idx, :, :], cmap = self.ct_cmap,
                     vmin = self.min_hu, vmax = self.max_hu)

    # check the lenght of cmaps is enough to colour all the structures
    assert len(self.segmask_cmap_dict) == np.max([len(self.segmask_ai_dict),
                                                  len(self.segmask_manual_dict)])

    # plot overlaying masks
    for key in self.segmask_ai_dict:
      segmask_ai = self.segmask_ai_dict[key]
      segmask_cmap = self.segmask_cmap_dict[key]
      ax_ai.imshow(segmask_ai[axial_idx, :, :], label = key,
                   cmap = segmask_cmap, alpha = self.segmask_alpha)

    for key in self.segmask_manual_dict:
      segmask_manual = self.segmask_manual_dict[key]
      segmask_cmap = self.segmask_cmap_dict[key]
      ax_manual.imshow(segmask_manual[axial_idx, :, :], label = key,
                       cmap = segmask_cmap, alpha = self.segmask_alpha)

    plt.subplots_adjust(hspace = 0.2)
    plt.show()

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

class AxialSliceSegmaskViz(AxialSliceFigure):
  """
  class description goes here

  """

  def __init__(self, ct_volume, segmask_dict, segmask_cmap_dict,
               segmask_alpha = 0.4,
               random_cmap = False, # FIXME - legend in the figure is wrong
               fig_title = "",
               ct_cmap = "gray", figsize = (6, 6), dpi = 100,
               min_hu = -1024, max_hu = 3072):

    """
    constructor description goes here

    """

    super().__init__(ct_cmap, figsize, dpi, min_hu, max_hu)

    self.ct_volume = ct_volume
    self.max_axial = self.ct_volume.shape[0] - 1

    self.segmask_dict = segmask_dict

    self.fig_title = fig_title

    if random_cmap:
      self.segmask_cmap_dict = self.get_random_cmap_dict(segmask_dict.keys())
    else:
      self.segmask_cmap_dict = segmask_cmap_dict

    self.segmask_alpha = segmask_alpha

    ipyw.interact(self.views)

  def get_random_cmap_dict(self, dict_keys):
    """
    method description goes here

    """

    segmask_cmap_dict = dict()

    for idx, key in enumerate(dict_keys):
      # dummy random colormap creation
      vals = np.linspace(0, 1, 256)
      np.random.shuffle(vals)

      # color map to sample from
      my_cmap = plt.cm.jet(vals)
      my_cmap[:, -1] = np.linspace(0, 1, 256)

      segmask_cmap_dict[key] = ListedColormap(my_cmap)

    return segmask_cmap_dict

  def plot_slice(self, axial_idx):
    """
    method description goes here

    """

    fig, ax = plt.subplots(1, 1, figsize = self.figsize, dpi = self.dpi)

    try:
      len(legend_elements)
    except:
      legend_elements = list()

    # plot CT axial slices
    ax.set_title(self.fig_title)
    ax.imshow(self.ct_volume[axial_idx, :, :], cmap = self.ct_cmap,
              vmin = self.min_hu, vmax = self.max_hu)

    # check the lenght of cmaps is enough to colour all the structures
    assert len(self.segmask_cmap_dict) == len(self.segmask_dict)

    # plot overlaying masks
    for key in self.segmask_dict:
      segmask = self.segmask_dict[key]
      segmask_cmap = self.segmask_cmap_dict[key]

      ax.imshow(segmask[axial_idx, :, :], label = key,
                cmap = segmask_cmap, alpha = self.segmask_alpha)

      if not len(legend_elements) == len(self.segmask_dict):
        legend_elements.append(Patch(facecolor = segmask_cmap(0.7),
                                     edgecolor = 'k',
                                     label = key))

    plt.subplots_adjust(hspace = 0.2)
    plt.show()

    ax.legend(handles = legend_elements,
              loc = 'upper left',
              bbox_to_anchor = (1, 1))


from django.urls import path,re_path,include
from . import views

urlpatterns=[
       path('',views.home,name='home'),
       path('forms/',views.forms,name='forms'),
       path('announcements/',views.AnnouncementsListView.as_view(),name='announcement_list'),
       path('contact-info/',views.contact,name='contact'),
       path('townhall-and-sc-meetings/',views.MeetingListView.as_view(),name='meeting_list'),
       path('grievances/',views.grievances,name='grievances'),
       path('student-activities/',views.club,name='club'),
       path('documents/',views.DocumentsListView.as_view(),name='documents_list'),
]


from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
validator_fn = [
    ##RegexValidator(r'[#]s+', "Hashtag #.....(любой символ)"),
    RegexValidator(r'@[w.]*','Login @...(0-9,a-z,_)')

]
validator_fn2 = [
    RegexValidator(r'[#]s+', "Hashtag #.....(любой символ)"),

]
def valid(value):
    err = None
    if (value[0] == "@"):
        for validator in validator_fn:
            try:
                validator(value)
            # Valid value, return it
                return value
            except ValidationError:
                return "Введенные данные: " + value + ". Неправильный формат для логина, логин: @....( вместо точек любая буква английского алфавита, цифра или нижнее подчеркивание)"

    if (value[0] == "#"):
        for validator in validator_fn:
            try:
                validator(value)
            # Valid value, return it
                return value
            except ValidationError:
                return "Введенные данные: " + value + ". Неправильный формат для хештега, хештег: #....( вместо точек любой символ кроме пробела)"
    else:
        return


class Employ:
    z =10
    def __init__(self):
        print("In constructor")
        self.x =20
        self.y =30
    def disp(self):
        print(self.x)
        print(self.y)
    print(z)
obj = Employ()
obj.disp()


from collections import defaultdict

import numpy as np

from .base.stage_summarizer_base import StageSummarizerBase

class LogregSummarizer(StageSummarizerBase):
    def summarize(self):
        # group values
        grouped = defaultdict(list)
        for key, value in self.all_log_entries.items():
            if "accuracy1" not in key:
                continue
            assert len(value) == 1
            key = key.replace("_split1", "").replace("_split2", "").replace("_split3", "")
            grouped[key].append(value[0])
        # stats
        for key, values in grouped.items():
            mean = float(np.mean(values))
            std = float(np.std(values))
            self.logger.info(f"{key}: mean={mean:.4f} std={std:.4f}")
            self.summary_provider[f"{key}/mean"] = mean
            self.summary_provider[f"{key}/std"] = std


import enderInput
from math import pi
n = enderInput.getInt(prompt="How many numbers would you like to use?")
sln = 0
for i in range(n):
	if (i%2 == 1):
		sln -= (4/((i*2)+1))
	else:
		sln += (4/((i*2)+1))
print(sln)
print("The estimation is off by: %.9f" %(pi - sln))


# function for bubble sort
def Bubble_Sort(list):
    for i in range(0, len(list) - 1):
        for j in range(0, len(list) - i - 1):
            # do swapping
            if list[j] > list[j + 1]:
                list[j], list[j + 1] = list[j + 1], list[j]

# function to print list
def Print_list(list):
    for i in range(0, len(list)):
        print(list[i], end = " ")

    print()

list = [2, 4, 3, 1, 6, 8, 4]

Bubble_Sort(list)

Print_list(list)

# Output
# 1 2 3 4 4 6 8


import abc
from typing import Any, Mapping, Optional, TYPE_CHECKING

from marshmallow import Schema, fields as fs, ValidationError

from templates import Interaction
from utils import EmbedFactory

if TYPE_CHECKING:
    from templates.views.dnd_resource_menus.framework import ResourceMenu

class UnionField(fs.Field):
    def __init__(self, fields: list[fs.Field] = None, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        if fields:
            self.fields = fields
        else:
            raise AttributeError('No types provided for UnionField')

    def _deserialize(
        self,
        value: Any,
        attr: Optional[str],
        data: Optional[Mapping[str, Any]],
        **kwargs,
    ):
        errors = []
        for field in self.fields:
            try:
                value = field._deserialize(value, attr, data, **kwargs)
                return value
            except ValidationError as e:
                errors.append(e)
                continue
        raise ValidationError(errors)

    def _serialize(self, value: Any, attr: str, obj: Any, **kwargs):
        for field in self.fields:
            try:
                value = field._serialize(value, attr, obj, **kwargs)
                return value
            except Exception:
                continue

        raise AttributeError(f"Could not serialize value for {self.__repr__()}")

    def __repr__(self) -> str:
        return f"<UnionField fields=[{', '.join(repr(field) for field in self.fields)}]>"

class APIModel(abc.ABC):
    schema: Schema

BASE_URL = "https://www.dnd5eapi.co"

class ResourceModel(APIModel, abc.ABC):
    @property
    def full_url(self) -> str:
        if hasattr(self, 'url'):
            return f"{BASE_URL}{self.url}"
        raise NotImplementedError

    def to_menu(
            self,
            interaction: Interaction,
            factory: EmbedFactory,
            ephemeral: bool = False
    ) -> 'ResourceMenu':
        raise NotImplementedError


def two_teams(sailors):
    boats = [[], []]
    for sailor in sailors:
        if 20 <= sailors[sailor] <= 40:
            boats[1].append(sailor)
        else:
            boats[0].append(sailor)
        boats[0].sort()
        boats[1].sort()
    return boats

print(two_teams({
        'Smith': 34,
        'Wesson': 22,
        'Coleman': 45,
        'Abrahams': 19}))