# Test conversion sites <--> coords
import numpy as np
from numpy.testing import assert_equal

import pytest

from mc_lib.lattices import tabulate_neighbors

from mc_lib.lattices._cubic import get_coord, get_site
from mc_lib.lattices._cubic import get_neighbors_sc
import mc_lib.lattices._triang as triang

def test_roundtrip():
    L = (5, 5, 5)
    for site in range(L[0] * L[1] * L[2]):
        xyz = get_coord(site, L)
        site1 = get_site(xyz, L)
        #print(site, xyz, site1)
        assert_equal(site, site1)

def test_coords():
    L = (4, 4, 4)
    site = get_site((2, 2, 2), L)
    neighb_sites = get_neighbors_sc(site, L)
    assert neighb_sites == [58, 38, 41, 43, 46, 26]

    coords = [tuple(get_coord(site1, L)) for site1 in neighb_sites]
    assert_equal(sorted(coords),
                 [(1, 2, 2), (2, 1, 2), (2, 2, 1),
                  (2, 2, 3), (2, 3, 2), (3, 2, 2)])

    site = get_site((3, 2, 2), L)
    neighb_sites = get_neighbors_sc(site, L)
    assert_equal(sorted(neighb_sites),
                 [10, 42, 54, 57, 59, 62])

    coords = [tuple(get_coord(site1, L)) for site1 in neighb_sites]
    assert_equal(sorted(coords),
                 [(0, 2, 2), (2, 2, 2), (3, 1, 2),
                 (3, 2, 1), (3, 2, 3), (3, 3, 2)])

def test_simple_cubic_2D():
   nn = tabulate_neighbors((4, 4, 1), kind='sc')
   assert_equal(nn,
                np.array([[ 4,  1,  3, 12,  4],
                          [ 4,  0,  5,  2, 13],
                          [ 4,  1,  3, 14,  6],
                          [ 4,  0,  2,  7, 15],
                          [ 4,  0,  8,  5,  7],
                          [ 4,  1,  4,  9,  6],
                          [ 4,  2, 10,  5,  7],
                          [ 4, 11,  3,  4,  6],
                          [ 4,  9, 11,  4, 12],
                          [ 4,  8, 13, 10,  5],
                          [ 4,  9, 11,  6, 14],
                          [ 4,  8, 10, 15,  7],
                          [ 4,  8,  0, 13, 15],
                          [ 4,  9, 12,  1, 14],
                          [ 4, 10,  2, 13, 15],
                          [ 4,  3, 11, 12, 14]])
   )

   nn1 = tabulate_neighbors((1, 4, 4), kind='sc')
   assert_equal(nn, nn1)

def test_simple_cubic_1D():
   nn = tabulate_neighbors((4, 1, 1), kind='sc')
   assert_equal(nn,
                np.array([[ 2, 1, 3],
                          [ 2, 0, 2],
                          [ 2, 1, 3],
                          [ 2, 0, 2]])
   )

   nn1 = tabulate_neighbors((1, 1, 4), kind='sc')
   assert_equal(nn, nn1)

####################### Triangular lattice 2D ################

def test_triang_roundtrip():
    L = (3, 3)
    for site in range(L[0] * L[1]):
        xyz = triang.get_coord(site, L)
        site1 = triang.get_site(xyz, L)
        #print(site, xyz, site1)
        assert_equal(site, site1)

def test_triang_coords():
    L = (3, 3)
    coords = {0: (0, 0), 1: (0, 1), 2: (0, 2),
              3: (1, 0), 4: (1, 1), 5: (1, 2),
              6: (2, 0), 7: (2, 1), 8: (2, 2),
    }

    for site in coords:
        assert_equal(triang.get_coord(site, L),
                     coords[site])

def test_triang_2D():
    nn = tabulate_neighbors((3, 3), kind='triang')
    assert_equal(nn,
                 np.array([[6, 1, 2, 3, 4, 6, 8],  # site = 0
                           [6, 0, 2, 4, 5, 6, 7],  #        1
                           [6, 0, 1, 3, 5, 7, 8],  #        2
                           [6, 0, 2, 4, 5, 6, 7],  #        3
                           [6, 0, 1, 3, 5, 7, 8],  #        4
                           [6, 1, 2, 3, 4, 6, 8],  #        5
                           [6, 0, 1, 3, 5, 7, 8],  #        6
                           [6, 1, 2, 3, 4, 6, 8],  #        7
                           [6, 0, 2, 4, 5, 6, 7]]) #        8

    )


arr = list(input())
path = ['']*3

def recur(level, start):

    if level==3:
        for j in range(3):
            print(path[j], end='')
        print()
        return

    for i in range(start, len(arr)):
        path[level]=arr[i]
        recur(level+1, i)

recur(0, 0)


# Find pixels with photons
import h5py, psana
import numpy as np
from hitFinderMaster import runmaster
from hitFinderClient import runclient

from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
assert size>1, 'At least 2 MPI ranks required'
numClients = size-1

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-e','--exp', help="experiment name (e.g. cxic0415)", type=str)
parser.add_argument('-r','--run', help="run number (e.g. 24)", type=int)
parser.add_argument("-d","--detectorName",help="psana detector alias, (e.g. pnccdBack, DsaCsPad)", type=str)
parser.add_argument("-o","--outDir",help="output directory",default="", type=str)
parser.add_argument("-n","--noe",help="number of events, all events=-1",default=-1, type=int)
parser.add_argument("-a","--algorithm",help="algorithm number",default=2, type=int)
parser.add_argument("-p","--pruneInterval",help="number of events to update running background",default=-1, type=float)
parser.add_argument("-l","--litPixelThreshold",help="number of ADUs to be considered a lit pixel",default=-1, type=float)
parser.add_argument("-t","--hitThreshold",help="number of pixels above litPixelThreshold to be considered a hit",default=-1, type=float)
parser.add_argument("--userMask_path",help="full path to user mask numpy array",default=None, type=str)
parser.add_argument("--streakMask_on",help="streak mask on",default="False", type=str)
parser.add_argument("--streakMask_sigma",help="streak mask sigma above background",default=0., type=float)
parser.add_argument("--streakMask_width",help="streak mask width",default=0, type=float)
parser.add_argument("--psanaMask_on",help="psana mask on",default="False", type=str)
parser.add_argument("--psanaMask_calib",help="psana calib on",default="False", type=str)
parser.add_argument("--psanaMask_status",help="psana status on",default="False", type=str)
parser.add_argument("--psanaMask_edges",help="psana edges on",default="False", type=str)
parser.add_argument("--psanaMask_central",help="psana central on",default="False", type=str)
parser.add_argument("--psanaMask_unbond",help="psana unbonded pixels on",default="False", type=str)
parser.add_argument("--psanaMask_unbondnrs",help="psana unbonded pixel neighbors on",default="False", type=str)
parser.add_argument("-v","--verbose",help="verbosity of output for debugging, 1=print, 2=print+plot",default=0, type=int)
parser.add_argument("--localCalib", help="use local calib directory, default=False", action='store_true')
parser.add_argument("--tag",help="cxi file tag",default="", type=str)
args = parser.parse_args()

def getNoe(args):
    runStr = "%04d" % args.run
    ds = psana.DataSource("exp="+args.exp+":run="+runStr+':idx')
    run = next(ds.runs())
    times = run.times()
    # check if the user requested specific number of events
    if args.noe == -1:
        numJobs = len(times)
    else:
        if args.noe <= len(times):
            numJobs = args.noe
        else:
            numJobs = len(times)
    return numJobs

if args.localCalib: psana.setOption('psana.calib-dir','./calib')

if rank == 0:
    runStr = "%04d" % args.run
    if args.tag:
        fname = args.outDir + "/" + args.exp + "_" + runStr + "_" + args.tag + ".cxi"
    else:
        fname = args.outDir + "/" + args.exp + "_" + runStr + ".cxi"
    # Get number of events to process
    numJobs = getNoe(args)

    # Create hdf5 and save psana input
    myHdf5 = h5py.File(fname, 'w')
    myHdf5['/status/findHits'] = 'fail'
    dt = h5py.special_dtype(vlen=bytes)
    myInput = ""
    for key,value in vars(args).items():
        myInput += key
        myInput += " "
        myInput += str(value)
        myInput += "\n"
    dset = myHdf5.create_dataset("/psana/input",(1,), dtype=dt)
    dset[...] = myInput

    grpName = "/entry_1/result_1"
    dset_nHits = "/nHitsAll"
    if grpName in myHdf5:
        del myHdf5[grpName]
    #myHdf5.flush()
    grp = myHdf5.create_group(grpName)
    myHdf5.create_dataset(grpName+dset_nHits, data=np.ones(numJobs,)*-1, dtype='int')
    #myHdf5.flush()
    myHdf5.close()

comm.Barrier()

if rank==0:
    runmaster(args,numClients)
else:
    runclient(args)

MPI.Finalize()


class Node:
    def __init__(self,data):
        self.val = data
        self.left = None
        self.right = None

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root == None:
            self.root = Node(data)
        else:
            cur = self.root
            while 1:
                if data<cur.val:
                    if cur.left:
                        cur = cur.left
                    else:
                        cur.left = Node(data)
                        break
                elif data>cur.val:
                    if cur.right:
                        cur = cur.right
                    else:
                        cur.right = Node(data)
                        break
                else:
                    break
traversal = []

def postOrder(root):
    if root==None:
        return
    postOrder(root.left)
    postOrder(root.right)
    global traversal
    traversal.append(root.val)

tree = BinarySearchTree()
nodes = [6,8,7,9,4,3,5]
for i in nodes:
    tree.insert(i)
postOrder(tree.root)
print(*traversal)

Level 1/Tree/Postorder traversal recursive.py


from rope import Rope

FILE = "day09/test-input-2.txt"
# FILE = "day09/input.txt"

with open(FILE) as f:
    moves = f.readlines()
    moves = [move.strip() for move in moves]
print(moves)

# Part 1
def part1():
    rope = Rope(2)
    for move in moves:
        direction, amount = move.split()
        for _ in range(int(amount)):
            rope.move(direction)
    print(len(set(rope.visited_by_tail)))

# Part 2
def part2():
    rope = Rope(10)
    for move in moves:
        direction, amount = move.split()
        for _ in range(int(amount)):
            rope.move(direction)
    print(len(set(rope.visited_by_tail)))

part1()
part2()


import json
import os
import requests
import sys

def main(token, tag_name, file_names):
    headers = {"Authorization": "bearer {token}".format(token=token)}
    data = {'tag_name': tag_name}
    response = requests.post("https://api.github.com/repos/neo4j-graphql/neo4j-graphql-java/releases",
                             data=json.dumps(data), headers=headers)
    release_json = response.json()
    print(release_json)
    release_id = release_json["id"]

    for file_name in file_names:
        with open(file_name, "rb") as file_name_handle:
            upload_url = "https://uploads.github.com/repos/neo4j-graphql/neo4j-graphql-java/releases/{release_id}/assets?name={file_name}".format(
                release_id=release_id, file_name=file_name.split("/")[-1]
            )
            print(upload_url)

            headers["Content-Type"] = "application/java-archive"

            response = requests.post(upload_url, headers=headers, data=file_name_handle.read())
            print(response.text)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python release.py [tag_name] [file_name]")
        sys.exit(1)

    token = os.getenv("GITHUB_TOKEN")
    tag_name = sys.argv[1]
    file_name = sys.argv[2:]
    print("Deploying release for tag " + tag_name + "  and " + str(file_name))
    main(token, tag_name, file_name)


from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union

import attr

from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.codat_data_contracts_datasets_account_transaction import CodatDataContractsDatasetsAccountTransaction
    from ..models.codat_data_contracts_datasets_account_transaction_paged_response_links import (
        CodatDataContractsDatasetsAccountTransactionPagedResponseLinks,
    )

T = TypeVar("T", bound="CodatDataContractsDatasetsAccountTransactionPagedResponse")

@attr.s(auto_attribs=True)
class CodatDataContractsDatasetsAccountTransactionPagedResponse:
    """
    Attributes:
        page_number (int):
        page_size (int):
        total_results (int):
        results (Union[Unset, None, List['CodatDataContractsDatasetsAccountTransaction']]):
        field_links (Union[Unset, None, CodatDataContractsDatasetsAccountTransactionPagedResponseLinks]):
    """

    page_number: int
    page_size: int
    total_results: int
    results: Union[Unset, None, List["CodatDataContractsDatasetsAccountTransaction"]] = UNSET
    field_links: Union[Unset, None, "CodatDataContractsDatasetsAccountTransactionPagedResponseLinks"] = UNSET

    def to_dict(self) -> Dict[str, Any]:
        page_number = self.page_number
        page_size = self.page_size
        total_results = self.total_results
        results: Union[Unset, None, List[Dict[str, Any]]] = UNSET
        if not isinstance(self.results, Unset):
            if self.results is None:
                results = None
            else:
                results = []
                for results_item_data in self.results:
                    results_item = results_item_data.to_dict()

                    results.append(results_item)

        field_links: Union[Unset, None, Dict[str, Any]] = UNSET
        if not isinstance(self.field_links, Unset):
            field_links = self.field_links.to_dict() if self.field_links else None

        field_dict: Dict[str, Any] = {}
        field_dict.update(
            {
                "pageNumber": page_number,
                "pageSize": page_size,
                "totalResults": total_results,
            }
        )
        if results is not UNSET:
            field_dict["results"] = results
        if field_links is not UNSET:
            field_dict["_links"] = field_links

        return field_dict

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        from ..models.codat_data_contracts_datasets_account_transaction import (
            CodatDataContractsDatasetsAccountTransaction,
        )
        from ..models.codat_data_contracts_datasets_account_transaction_paged_response_links import (
            CodatDataContractsDatasetsAccountTransactionPagedResponseLinks,
        )

        d = src_dict.copy()
        page_number = d.pop("pageNumber")

        page_size = d.pop("pageSize")

        total_results = d.pop("totalResults")

        results = []
        _results = d.pop("results", UNSET)
        for results_item_data in _results or []:
            results_item = CodatDataContractsDatasetsAccountTransaction.from_dict(results_item_data)

            results.append(results_item)

        _field_links = d.pop("_links", UNSET)
        field_links: Union[Unset, None, CodatDataContractsDatasetsAccountTransactionPagedResponseLinks]
        if _field_links is None:
            field_links = None
        elif isinstance(_field_links, Unset):
            field_links = UNSET
        else:
            field_links = CodatDataContractsDatasetsAccountTransactionPagedResponseLinks.from_dict(_field_links)

        codat_data_contracts_datasets_account_transaction_paged_response = cls(
            page_number=page_number,
            page_size=page_size,
            total_results=total_results,
            results=results,
            field_links=field_links,
        )

        return codat_data_contracts_datasets_account_transaction_paged_response


#
# Class for particle-size distributions, one distribution at every
# x location of the electrode, and Fickian diffusion within each particle
#
import pybamm

from .base_distribution import BaseSizeDistribution

class FickianDiffusion(BaseSizeDistribution):
    """Class for molar conservation in particle-size distributions, one
    distribution at every x location of the electrode,
    with Fickian diffusion within each particle. Concentration varies with
    r (spherical coordinate), R (particle size), and x (electrode coordinate).

    Parameters
    ----------
    param : parameter class
        The parameters to use for this submodel
    domain : str
        The domain of the model either 'Negative' or 'Positive'

    **Extends:** :class:`pybamm.particle.size_distribution.BaseSizeDistribution`
    """

    def __init__(self, param, domain):
        super().__init__(param, domain)
        pybamm.citations.register("Kirk2021")

    def get_fundamental_variables(self):
        if self.domain == "Negative":
            c_s_distribution = pybamm.Variable(
                "Negative particle concentration distribution",
                domain="negative particle",
                auxiliary_domains={
                    "secondary": "negative particle size",
                    "tertiary": "negative electrode",
                    "quaternary": "current collector"
                },
                bounds=(0, 1),
            )
            R = pybamm.standard_spatial_vars.R_n

        elif self.domain == "Positive":
            c_s_distribution = pybamm.Variable(
                "Positive particle concentration distribution",
                domain="positive particle",
                auxiliary_domains={
                    "secondary": "positive particle size",
                    "tertiary": "positive electrode",
                    "quaternary": "current collector"
                },
                bounds=(0, 1),
            )
            R = pybamm.standard_spatial_vars.R_p

        variables = self._get_distribution_variables(R)

        # Standard concentration distribution variables (size-dependent)
        variables.update(
            self._get_standard_concentration_distribution_variables(c_s_distribution)
        )

        # Standard size-averaged variables. Average concentrations using
        # the volume-weighted distribution since they are volume-based
        # quantities. Necessary for output variables "Total lithium in
        # negative electrode [mol]", etc, to be calculated correctly
        f_v_dist = variables[
            self.domain + " volume-weighted particle-size distribution"
        ]
        c_s = pybamm.Integral(f_v_dist * c_s_distribution, R)
        c_s_xav = pybamm.x_average(c_s)
        variables.update(self._get_standard_concentration_variables(c_s, c_s_xav))

        return variables

    def get_coupled_variables(self, variables):
        c_s_distribution = variables[
            self.domain + " particle concentration distribution"
        ]
        R = variables[self.domain + " particle sizes"]

        # broadcast T to "particle size" domain then again into "particle"
        T_k = pybamm.PrimaryBroadcast(
            variables[self.domain + " electrode temperature"],
            [self.domain.lower() + " particle size"],
        )
        T_k = pybamm.PrimaryBroadcast(
            T_k, [self.domain.lower() + " particle"],
        )

        if self.domain == "Negative":
            N_s_distribution = (
                -self.param.D_n(c_s_distribution, T_k)
                * pybamm.grad(c_s_distribution)
            )
            f_a_dist = self.param.f_a_dist_n(R)
        elif self.domain == "Positive":
            N_s_distribution = (
                -self.param.D_p(c_s_distribution, T_k)
                * pybamm.grad(c_s_distribution)
            )
            f_a_dist = self.param.f_a_dist_p(R)

        # Size-dependent flux variables
        variables.update(
            self._get_standard_flux_distribution_variables(N_s_distribution)
        )

        # Size-averaged flux variables (perform area-weighted avg manually as flux
        # evals on edges)
        N_s = pybamm.Integral(f_a_dist * N_s_distribution, R)
        variables.update(self._get_standard_flux_variables(N_s, N_s))

        variables.update(self._get_total_concentration_variables(variables))
        return variables

    def set_rhs(self, variables):
        c_s_distribution = variables[
            self.domain + " particle concentration distribution"
        ]
        N_s_distribution = variables[self.domain + " particle flux distribution"]
        R = pybamm.PrimaryBroadcast(
            variables[self.domain + " particle sizes"],
            [self.domain.lower() + " particle"]
        )

        if self.domain == "Negative":
            self.rhs = {
                c_s_distribution: -(1 / self.param.C_n)
                * pybamm.div(N_s_distribution)
                / R ** 2
            }
        elif self.domain == "Positive":
            self.rhs = {
                c_s_distribution: -(1 / self.param.C_p)
                * pybamm.div(N_s_distribution)
                / R ** 2
            }

    def set_boundary_conditions(self, variables):
        # Extract variables
        c_s_distribution = variables[
            self.domain + " particle concentration distribution"
        ]
        c_s_surf_distribution = variables[
            self.domain + " particle surface concentration distribution"
        ]
        j_distribution = variables[
            self.domain + " electrode interfacial current density distribution"
        ]
        R = variables[self.domain + " particle sizes"]
        T_k = pybamm.PrimaryBroadcast(
            variables[self.domain + " electrode temperature"],
            [self.domain.lower() + " particle size"]
        )

        # Set surface Neumann boundary values
        if self.domain == "Negative":
            rbc = (
                -self.param.C_n
                * R
                * j_distribution
                / self.param.a_R_n
                / self.param.D_n(c_s_surf_distribution, T_k)
            )
        elif self.domain == "Positive":
            rbc = (
                -self.param.C_p
                * R
                * j_distribution
                / self.param.a_R_p
                / self.param.gamma_p
                / self.param.D_p(c_s_surf_distribution, T_k)
            )
        self.boundary_conditions = {
            c_s_distribution: {
                "left": (pybamm.Scalar(0), "Neumann"),
                "right": (rbc, "Neumann"),
            }
        }

    def set_initial_conditions(self, variables):
        c_s_distribution = variables[
            self.domain + " particle concentration distribution"
        ]

        if self.domain == "Negative":
            # Broadcast x_n to particle-size then into the particles
            x_n = pybamm.PrimaryBroadcast(
                pybamm.standard_spatial_vars.x_n, "negative particle size"
            )
            x_n = pybamm.PrimaryBroadcast(x_n, "negative particle")
            c_init = self.param.c_n_init(x_n)

        elif self.domain == "Positive":
            # Broadcast x_n to particle-size then into the particles
            x_p = pybamm.PrimaryBroadcast(
                pybamm.standard_spatial_vars.x_p, "positive particle size"
            )
            x_p = pybamm.PrimaryBroadcast(x_p, "positive particle")
            c_init = self.param.c_p_init(x_p)

        self.initial_conditions = {c_s_distribution: c_init}


# -*- coding: utf-8 -*-
import os

PROJECT_DIR = os.path.join(os.path.dirname(__file__), "..")
project_dir = lambda p: os.path.join(PROJECT_DIR, p)

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('Vadim Zabiiaka', 'v.zabiiaka@gmail.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['.vox.li.madprogrammer.net', '.voxlegum.com']

TIME_ZONE = 'Europe/Kiev'
LANGUAGE_CODE = 'uk'

gettext = lambda s: s
LANGUAGES = (
    ('uk', gettext('Uk')),
    ('ru', gettext('Ru')),
    ('en', gettext('En')),
)
MODELTRANSLATION_FALLBACK_LANGUAGES = ('uk',)

SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
SOLID_I18N_USE_REDIRECTS = False

MEDIA_ROOT = project_dir('media')
MEDIA_URL = '/media/'

STATIC_ROOT = project_dir('static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    project_dir('vox/static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '#rtme382a9z6o*q$l4&n13(7c5o3*5g*!+b@knn&%u@lm%0ee('

MIDDLEWARE_CLASSES = (
    'solid_i18n.middleware.SolidLocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'vox.urls'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = (
    project_dir('vox/templates'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.request",
    "django.contrib.messages.context_processors.messages",

)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'south',
    'sorl.thumbnail',
    'advanced_imagefield',
    'haystack',
    'rollyourown.seo',
    'modeltranslation',
    'apps.news',
    'apps.team',
    'apps.site',
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': project_dir('whoosh_index'),
    },
}

try:
    from tinymce_settings import *
except ImportError as ie:
    pass

try:
    from local_settings import *
except ImportError as ie:
    pass


import os
import re
import yaml

class UserAgentParser(object):
  def __init__(self, pattern, family_replacement=None, v1_replacement=None):
    """Initialize UserAgentParser.

    Args:
      pattern: a regular expression string
      family_replacement: a string to override the matched family (optional)
      v1_replacement: a string to override the matched v1 (optional)
    """
    self.pattern = pattern
    self.user_agent_re = re.compile(self.pattern)
    self.family_replacement = family_replacement
    self.v1_replacement = v1_replacement

  def MatchSpans(self, user_agent_string):
    match_spans = []
    match = self.user_agent_re.search(user_agent_string)
    if match:
      match_spans = [match.span(group_index)
                     for group_index in range(1, match.lastindex + 1)]
    return match_spans

  def Parse(self, user_agent_string):
    family, v1, v2, v3 = None, None, None, None
    match = self.user_agent_re.search(user_agent_string)
    if match:
      if self.family_replacement:
        if re.search(r'\$1', self.family_replacement):
          family = re.sub(r'\$1', match.group(1), self.family_replacement)
        else:
          family = self.family_replacement
      else:
        family = match.group(1)

      if self.v1_replacement:
        v1 = self.v1_replacement
      elif match.lastindex >= 2:
        v1 = match.group(2)

      if match.lastindex >= 3:
        v2 = match.group(3)
        if match.lastindex >= 4:
          v3 = match.group(4)
    return family, v1, v2, v3

class OSParser(object):
  def __init__(self, pattern, os_replacement=None ):
    """Initialize UserAgentParser.

    Args:
      pattern: a regular expression string
      os_replacement: a string to override the matched os (optional)
    """
    self.pattern = pattern
    self.user_agent_re = re.compile(self.pattern)
    self.os_replacement = os_replacement

  def MatchSpans(self, user_agent_string):
    match_spans = []
    match = self.user_agent_re.search(user_agent_string)
    if match:
      match_spans = [match.span(group_index)
                     for group_index in range(1, match.lastindex + 1)]
    return match_spans

  def Parse(self, user_agent_string):
    os, os_v1, os_v2, os_v3, os_v4 = None, None, None, None, None
    match = self.user_agent_re.search(user_agent_string)
    if match:
      if self.os_replacement:
        os = self.os_replacement
      else:
        os = match.group(1)

      if match.lastindex >= 2:
        os_v1 = match.group(2)
        if match.lastindex >= 3:
          os_v2 = match.group(3)
          if match.lastindex >= 4:
            os_v3 = match.group(4)
            if match.lastindex >= 5:
              os_v4 = match.group(5)

    return os, os_v1, os_v2, os_v3, os_v4

class DeviceParser(object):
  def __init__(self, pattern, device_replacement=None):
    """Initialize UserAgentParser.

    Args:
      pattern: a regular expression string
      device_replacement: a string to override the matched device (optional)
    """
    self.pattern = pattern
    self.user_agent_re = re.compile(self.pattern)
    self.device_replacement = device_replacement

  def MatchSpans(self, user_agent_string):
    match_spans = []
    match = self.user_agent_re.search(user_agent_string)
    if match:
      match_spans = [match.span(group_index)
                     for group_index in range(1, match.lastindex + 1)]
    return match_spans

  def Parse(self, user_agent_string):
    device = None
    match = self.user_agent_re.search(user_agent_string)
    if match:
      if self.device_replacement:
        if re.search(r'\$1', self.device_replacement):
          device = re.sub(r'\$1', match.group(1), self.device_replacement)
        else:
          device = self.device_replacement
      else:
        device = match.group(1)

    return device

def ParseAll(user_agent_string, **jsParseBits):
  """ Parse all the things
      Args:
          user_agent_string: the full user agent string
          jsParseBits: javascript override bits
      Returns:
          flat dictionary containing all parsed bits
  """
  jsParseBits = jsParseBits or {}

  resultUA = ParseUserAgent(user_agent_string, **jsParseBits)
  resultOS = ParseOS(user_agent_string, **jsParseBits)

  resultAll = {}
  for result in (resultUA, resultOS):
    resultAll.update(result)

  return resultAll

def ParseUserAgent(user_agent_string, **jsParseBits):
  """ Parses the user-agent string for user agent (browser) info.
      Args:
        user_agent_string: The full user-agent string.
        jsParseBits: javascript override bits
      Returns:
        flat dictionary containing parsed bits
  """
  if 'js_user_agent_family' in jsParseBits and jsParseBits['js_user_agent_family'] != '':
    family = jsParseBits['js_user_agent_family']
    if 'js_user_agent_v1' in jsParseBits:
      v1 = jsParseBits['js_user_agent_v1'] or None
    if 'js_user_agent_v2' in jsParseBits:
      v2 = jsParseBits['js_user_agent_v2'] or None
    if 'js_user_agent_v3' in jsParseBits:
      v3 = jsParseBits['js_user_agent_v3'] or None
  else:
    for uaParser in USER_AGENT_PARSERS:
      family, v1, v2, v3 = uaParser.Parse(user_agent_string)
      if family:
        break

  # Override for Chrome Frame IFF Chrome is enabled.
  if 'js_user_agent_string' in jsParseBits:
    js_user_agent_string = jsParseBits['js_user_agent_string']
    if (js_user_agent_string and js_user_agent_string.find('Chrome/') > -1 and
        user_agent_string.find('chromeframe') > -1):
      jsOverride = {}
      jsOverride = ParseUserAgent(js_user_agent_string)
      family = 'Chrome Frame (%s %s)' % (family, v1)
      v1 = jsOverride['v1']
      v2 = jsOverride['v2']
      v3 = jsOverride['v3']

  family = family or 'Other'
  return {'family': family, 'v1': v1,  'v2': v2, 'v3': v3}

def ParseOS(user_agent_string, **jsParseBits):
  """ Parses the user-agent string for operating system info
      Args:
        user_agent_string: The full user-agent string.
        jsParseBits: javascript override bits
      Returns:
        flat dictionary containing parsed bits
  """
  for osParser in OS_PARSERS:
    os, os_v1, os_v2, os_v3, os_v4 = osParser.Parse(user_agent_string)
    if os:
      break
  os = os or 'Other'
  return { 'os': os, 'os_v1': os_v1, 'os_v2': os_v2, 'os_v3': os_v3, 'os_v4': os_v4 }

def ParseDevice(user_agent_string, **jsParseBits):
  """ incomplete! """
  for deviceParser in DEVICE_PARSERS:
    device = deviceParser.Parse(user_agent_string)
    if device:
      break

  device = device or 'Other'
  return {'device': device}

def PrettyUserAgent(family, v1=None, v2=None, v3=None):
  """Pretty user agent string."""
  if v3:
    if v3[0].isdigit():
      return '%s %s.%s.%s' % (family, v1, v2, v3)
    else:
      return '%s %s.%s%s' % (family, v1, v2, v3)
  elif v2:
    return '%s %s.%s' % (family, v1, v2)
  elif v1:
    return '%s %s' % (family, v1)
  return family

def PrettyOS(os, os_v1=None, os_v2=None, os_v3=None, os_v4=None):
  """Pretty os string."""
  if os_v4:
    return '%s %s.%s.%s.%s' % (os, os_v1, os_v2, os_v3, os_v4)
  if os_v3:
    if os_v3[0].isdigit():
      return '%s %s.%s.%s' % (os, os_v1, os_v2, os_v3)
    else:
      return '%s %s.%s%s' % (os, os_v1, os_v2, os_v3)
  elif os_v2:
    return '%s %s.%s' % (os, os_v1, os_v2)
  elif os_v1:
    return '%s %s' % (os, os_v1)
  return os

def Parse(user_agent_string, js_user_agent_string=None,
          js_user_agent_family=None,
          js_user_agent_v1=None,
          js_user_agent_v2=None,
          js_user_agent_v3=None):
  """ backwards compatible. use one of the other Parse methods instead! """

  # Override via JS properties.
  if js_user_agent_family is not None and js_user_agent_family != '':
    family = js_user_agent_family
    v1 = None
    v2 = None
    v3 = None
    if js_user_agent_v1 is not None:
      v1 = js_user_agent_v1
    if js_user_agent_v2 is not None:
      v2 = js_user_agent_v2
    if js_user_agent_v3 is not None:
      v3 = js_user_agent_v3
  else:
    for parser in USER_AGENT_PARSERS:
      family, v1, v2, v3 = parser.Parse(user_agent_string)
      if family:
        break

  # Override for Chrome Frame IFF Chrome is enabled.
  if (js_user_agent_string and js_user_agent_string.find('Chrome/') > -1 and
      user_agent_string.find('chromeframe') > -1):
    family = 'Chrome Frame (%s %s)' % (family, v1)
    cf_family, v1, v2, v3 = Parse(js_user_agent_string)

  return family or 'Other', v1, v2, v3

def Pretty(family, v1=None, v2=None, v3=None):
  """ backwards compatible. use PrettyUserAgent instead! """
  if v3:
    if v3[0].isdigit():
      return '%s %s.%s.%s' % (family, v1, v2, v3)
    else:
      return '%s %s.%s%s' % (family, v1, v2, v3)
  elif v2:
    return '%s %s.%s' % (family, v1, v2)
  elif v1:
    return '%s %s' % (family, v1)
  return family

def GetFilters(user_agent_string, js_user_agent_string=None,
               js_user_agent_family=None,
               js_user_agent_v1=None,
               js_user_agent_v2=None,
               js_user_agent_v3=None):
  """Return the optional arguments that should be saved and used to query.

  js_user_agent_string is always returned if it is present. We really only need
  it for Chrome Frame. However, I added it in the generally case to find other
  cases when it is different. When the recording of js_user_agent_string was
  added, we created new records for all new user agents.

  Since we only added js_document_mode for the IE 9 preview case, it did not
  cause new user agent records the way js_user_agent_string did.

  js_document_mode has since been removed in favor of individual property
  overrides.

  Args:
    user_agent_string: The full user-agent string.
    js_user_agent_string: JavaScript ua string from client-side
    js_user_agent_family: This is an override for the family name to deal
        with the fact that IE platform preview (for instance) cannot be
        distinguished by user_agent_string, but only in javascript.
    js_user_agent_v1: v1 override - see above.
    js_user_agent_v2: v1 override - see above.
    js_user_agent_v3: v1 override - see above.
  Returns:
    {js_user_agent_string: '[...]', js_family_name: '[...]', etc...}
  """
  filters = {}
  filterdict = {
    'js_user_agent_string': js_user_agent_string,
    'js_user_agent_family': js_user_agent_family,
    'js_user_agent_v1': js_user_agent_v1,
    'js_user_agent_v2': js_user_agent_v2,
    'js_user_agent_v3': js_user_agent_v3
  }
  for key, value in filterdict.items():
    if value is not None and value != '':
      filters[key] = value
  return filters

# Build the list of user agent parsers from YAML
rootDir = os.path.abspath(os.path.dirname(__file__))
yamlFile = open(rootDir + '/resources/user_agent_parser.yaml')
yaml = yaml.load(yamlFile)
yamlFile.close()

USER_AGENT_PARSERS = []
for parser in yaml['user_agent_parsers']:
  regex = parser['regex']

  family_replacement = None
  if 'family_replacement' in parser:
    family_replacement = parser['family_replacement']

  v1_replacement = None
  if 'v1_replacement' in parser:
    v1_replacement = parser['v1_replacement']

  USER_AGENT_PARSERS.append(UserAgentParser(regex, family_replacement, v1_replacement))

OS_PARSERS = []
for parser in yaml['os_parsers']:
  regex = parser['regex']

  os_replacement = None
  if 'os_replacement' in parser:
    os_replacement = parser['os_replacement']

  OS_PARSERS.append(OSParser(regex, os_replacement))

DEVICE_PARSERS = []
for parser in yaml['device_parsers']:
  regex = parser['regex']

  device_replacement = None
  if 'device_replacement' in parser:
    device_replacement = parser['device_replacement']

DEVICE_PARSERS.append(DeviceParser(regex, device_replacement))


#----------------------------------------------------------------
#
# SAVEABLE SHOPPING LIST
#
# NB: To do this exercise you must have already completed one of
# the "shopping list" exercises.
#
# In the previous "shopping list" exercise you created a GUI
# which allowed the user to select grocery items and add them to
# a list of such items which was displayed in the user
# interface.  However, the list is lost when the GUI is closed
# down.  Extend your solution so that:
#
# a) It has a button labelled "Save" that can be pressed at
# any time; and
#
# b) When the "save" button is pressed the current contents of
# the list are written to a text file "shopping_list.txt".
#
# To do this you will need to use a list-valued variable to
# keep track of the current contents of the list.
#

# Import the necessary Tkinter functions
from tkinter import Tk, Text, Button, END, Label
from tkinter.ttk import Combobox

# Create a window
window = Tk()

# Give the window a title
window.title('Shopping list')

# Create a list of choices
groceries = ['Eggs', 'Milk', 'Bread', 'Coffee', 'Tea', 'Lettuce',
             'Tomatoes', 'Onions', 'Chicken', 'Cheese', 'Fish',
             'Sugar', 'Rice', 'Pasta', 'Soup', 'Cereal', 'Yogurt']

##### DEVELOP YOUR SOLUTION HERE, BASED ON YOUR PREVIOUS SHOPPING LIST CODE
def display_current_choice(cBox):
    if len(Choice.get("1.0", END)) == 1:
        Choice.insert(END,  cBox.get());
        FinishButton['text'] = "CheckOut";
    else:
        Choice.insert(END,  ", " + cBox.get());

def checkout():
    if len(Choice.get("1.0", END)) != 1:
        text_file = open("Groceries.txt", "w");
        text_file.write("Groceries List:\n%s" % str(Choice.get('1.0', END)));
        text_file.close();

        Choice.delete("1.0", END);
        FinishButton['text'] = "Items Saved";
        grossCombo.set("Please Select Yo Shizz");

CartLabel = Label(window, height = 1, width = 30, font = ('Arial', 12), text = 'Cart');
CartLabel.pack();
# 2. Create a Text area to display the user's choice and
#    pack it into the main window
Choice = Text(window, height = 20, width = 30, font = ('Arial', 12));
Choice.pack();

# 3. Create a Combobox widget whose parent container is the
#    main window and pack it
grossCombo = Combobox(window, width = 20, value = groceries);
grossCombo.set("Please Select Yo Shizz");
grossCombo.state(['readonly']);
grossCombo.bind("<<ComboboxSelected>>", lambda event:display_current_choice(grossCombo));
grossCombo.pack();
# 4. Create a Button to push when the user is happy with
#    their choice and pack it
FinishButton = Button(window, height = 1, width = 30, font = ('Arial', 12), text = 'CheckOut', command = checkout);
FinishButton.pack();

# Start the event loop to react to user inputs
window.mainloop()


"""Check that QE calculation can run."""

from ase.build import bulk

def verify(calc):
    assert calc.get_fermi_level() is not None
    assert calc.get_ibz_k_points() is not None
    assert calc.get_eigenvalues(spin=0, kpt=0) is not None
    assert calc.get_number_of_spins() is not None
    assert calc.get_k_point_weights() is not None

def test_main(espresso_factory):
    atoms = bulk('Si')
    atoms.calc = espresso_factory.calc()
    atoms.get_potential_energy()
    verify(atoms.calc)

def test_smearing(espresso_factory):
    atoms = bulk('Cu')
    input_data = {'system':{'occupations': 'smearing',
                            'smearing': 'fermi-dirac',
                            'degauss': 0.02}}
    atoms.calc = espresso_factory.calc(input_data=input_data)
    atoms.get_potential_energy()
    verify(atoms.calc)


from collections import defaultdict
transactions_file = open("bank2.txt", "r")

# Используем defaultdict, чтобы автоматически создавать ключи.
accounts = defaultdict(int)

total = 0
for transaction in transactions_file:
    account_from, account_to, amount = transaction.split(";")

    # Заполняем данными.
    accounts[account_from] -= int(amount)
    accounts[account_to] += int(amount)

# Удаляем словарь 000
del accounts["000"]

# Сразу сортируем словарь и формируем финальный результат.
print(";".join([f"{account} {balance}" for account, balance in sorted(accounts.items(), key=lambda a: a[1])]))

'''316. ACCOUNT REPORT
Difficulty: 7 out of 10

You have already calculated the balance of each account separately. Now it's time to build a report on all bank accounts.

Write a program that goes through all the transactions in the bank.txt file, and then displays all the accounts and the balance of each account.

The data must be output in the following format:
Account1 Balance1;Account2 Balance2;Account N; Balance N.
That is, the accounts are separated by a semicolon, and each account individually contains its number and balance, separated by a space.

Invoices should be displayed in ascending order of balance (see sample report below).

Please note that the file has account 000 - this is the bank's internal account, you do not need to display it:

000;123;200
123;456;100
456;789;200
789;123;500

> python program.py
789 -300;456 -100;123 600'''


from numpy import zeros, where, full, int64, float64
from numba import njit
from HSP2.utilities import initm, make_numba_dict, hourflag

ERRMSG = []

# english system
# parameters for variables with energy units
EFACTA = 407960.
EFACTB = 0.0

# parameters for variables with temperature units
TFACTA = 1.8
TFACTB = 32.0

# parameters for variables for dissolved gases with mass units
MFACTA = 0.2266
MFACTB = 0.

def pwtgas(io_manager, siminfo, uci, ts):
    ''' Estimate water temperature, dissolved oxygen, and carbon dioxide in the outflows
    from a pervious landsegment. calculate associated fluxes through exit gates'''
    simlen = siminfo['steps']

    ui = make_numba_dict(uci)
    ui['simlen'] = siminfo['steps']
    ui['uunits'] = siminfo['units']
    ui['errlen'] = len(ERRMSG)

    u = uci['PARAMETERS']
    if 'IDVFG' in u:
        ts['IDOXP'] = initm(siminfo, uci, u['IDVFG'], 'MONTHLY_IDOXP', u['IDOXP'])
    else:
        ts['IDOXP'] = full(simlen, u['IDOXP'])
    if 'ICVFG' in u:
        ts['ICO2P'] = initm(siminfo, uci, u['ICVFG'], 'MONTHLY_ICO2P', u['ICO2P'])
    else:
        ts['ICO2P'] = full(simlen, u['ICO2P'])
    if 'GDVFG' in u:
        ts['ADOXP'] = initm(siminfo, uci, u['GDVFG'], 'MONTHLY_ADOXP', u['ADOXP'])
    else:
        ts['ADOXP'] = full(simlen, u['ADOXP'])
    if 'GCVFG' in u:
        ts['ACO2P'] = initm(siminfo, uci, u['GCVFG'], 'MONTHLY_ACO2P', u['ACO2P'])
    else:
        ts['ACO2P'] = full(simlen, u['ACO2P'])

    ts['DAYFG'] = hourflag(siminfo, 0, dofirst=True).astype(float64)

    ############################################################################
    errors = _pwtgas_(ui, ts)  # run PWTGAS simulation code
    ############################################################################

    return errors, ERRMSG

@njit(cache=True)
def _pwtgas_(ui, ts):
    ''' Estimate water temperature, dissolved oxygen, and carbon dioxide in the outflows
    from a pervious landsegment. calculate associated fluxes through exit gates'''

    errorsV = zeros(int(ui['errlen'])).astype(int64)

    uunits = ui['uunits']
    simlen = int(ui['simlen'])

    CSNOFG = int(ui['CSNOFG'])
    sotmp  = ui['SOTMP']
    iotmp  = ui['IOTMP']
    aotmp  = ui['AOTMP']
    sodox  = ui['SODOX']
    soco2  = ui['SOCO2']
    iodox  = ui['IODOX']
    ioco2  = ui['IOCO2']
    aodox  = ui['AODOX']
    aoco2  = ui['AOCO2']
    sdlfac = ui['SDLFAC']
    slifac = ui['SLIFAC']
    ilifac = ui['ILIFAC']
    alifac = ui['ALIFAC']
    elev   = ui['ELEV']
    if uunits == 2:
        sotmp = (sotmp * 9. / 5.) + 32.
        iotmp = (iotmp * 9. / 5.) + 32.
        aotmp = (aotmp * 9. / 5.) + 32.
        elev = elev * 3.281  # m to ft
    elevgc = ((288.0 - 0.00198 * elev) / 288.0) ** 5.256

    if 'GDVFG' in ui:
        gdvfg = ui['GDVFG']
    else:
        gdvfg = 0

    IDOXP = ts['IDOXP']
    ICO2P = ts['ICO2P']
    ADOXP = ts['ADOXP']
    ACO2P = ts['ACO2P']

    for name in ['WYIELD', 'SURO', 'IFWO', 'AGWO', 'SURLI', 'IFWLI', 'AGWLI']:
        if name not in ts:
            ts[name] = zeros(simlen)
    WYIELD = ts['WYIELD']
    SURO   = ts['SURO']
    IFWO   = ts['IFWO']
    AGWO   = ts['AGWO']
    SURLI  = ts['SURLI']
    IFWLI  = ts['IFWLI']
    AGWLI  = ts['AGWLI']

    for name in ['SLTMP', 'ULTMP', 'LGTMP', 'SLITMP', 'SLIDOX', 'SLICO2']:
        if name not in ts:
            ts[name] = full(simlen, -1.0E30)
    SLTMP  = ts['SLTMP']
    ULTMP  = ts['ULTMP']
    LGTMP  = ts['LGTMP']
    SLITMP = ts['SLITMP']
    SLIDOX = ts['SLIDOX']
    SLICO2 = ts['SLICO2']

    for name in ['ILITMP', 'ILIDOX', 'ILICO2']:
        if name not in ts:
            ts[name] = full(simlen, -1.0E30)
    ILITMP = ts['ILITMP']
    ILIDOX = ts['ILIDOX']
    ILICO2 = ts['ILICO2']

    for name in ['ALITMP', 'ALIDOX', 'ALICO2']:
        if name not in ts:
            ts[name] = full(simlen, -1.0E30)
    ALITMP = ts['ALITMP']
    ALIDOX = ts['ALIDOX']
    ALICO2 = ts['ALICO2']

    # preallocate output arrays
    SOTMP  = ts['SOTMP']  = zeros(simlen)
    IOTMP  = ts['IOTMP']  = zeros(simlen)
    AOTMP  = ts['AOTMP']  = zeros(simlen)
    SODOX  = ts['SODOX']  = zeros(simlen)
    SOCO2  = ts['SOCO2']  = zeros(simlen)
    IODOX  = ts['IODOX']  = zeros(simlen)
    IOCO2  = ts['IOCO2']  = zeros(simlen)
    AODOX  = ts['AODOX']  = zeros(simlen)
    AOCO2  = ts['AOCO2']  = zeros(simlen)
    SOHT   = ts['SOHT']   = zeros(simlen)
    IOHT   = ts['IOHT']   = zeros(simlen)
    AOHT   = ts['AOHT']   = zeros(simlen)
    POHT   = ts['POHT']   = zeros(simlen)
    SODOXM = ts['SODOXM'] = zeros(simlen)
    SOCO2M = ts['SOCO2M'] = zeros(simlen)
    IODOXM = ts['IODOXM'] = zeros(simlen)
    IOCO2M = ts['IOCO2M'] = zeros(simlen)
    AODOXM = ts['AODOXM'] = zeros(simlen)
    AOCO2M = ts['AOCO2M'] = zeros(simlen)
    PODOXM = ts['PODOXM'] = zeros(simlen)
    POCO2M = ts['POCO2M'] = zeros(simlen)

    DAYFG = ts['DAYFG'].astype(int64)

    if uunits == 2:
        SLTMP = (SLTMP * 9. / 5.) + 32.
        ULTMP = (ULTMP * 9. / 5.) + 32.
        LGTMP = (LGTMP * 9. / 5.) + 32.
        WYIELD = WYIELD * 0.0394  # / 25.4
        SURO = SURO * 0.0394  # mm to inches
        IFWO = IFWO * 0.0394  # mm to inches
        AGWO = AGWO * 0.0394  # mm to inches

    for loop in range(simlen):
        dayfg   = DAYFG[loop]
        suro   = SURO[loop]
        wyield = WYIELD[loop]
        ifwo   = IFWO[loop]
        agwo   = AGWO[loop]
        surli  = SURLI[loop]
        ifwli  = IFWLI[loop]
        agwli  = AGWLI[loop]
        sltmp  = SLTMP[loop]
        slitmp = SLITMP[loop]
        slidox = SLIDOX[loop]
        slico2 = SLICO2[loop]
        ultmp  = ULTMP[loop]
        idoxp  = IDOXP[loop]
        ico2p  = ICO2P[loop]
        adoxp  = ADOXP[loop]
        aco2p  = ACO2P[loop]

        sotmp = -1.0e30
        sodox = -1.0e30
        soco2 = -1.0e30
        if suro > 0.0:  # there is surface outflow
            # local surface outflow temp equals surface soil temp
            sotmp = (sltmp - 32.0) * 5./9.
            if sotmp < 0.5:
                sotmp = 0.5  # min water temp
            if CSNOFG:      # effects of snow are considered
                # adjust surface outflow temperature if snowmelt is occurring
                if wyield > 0.0:
                    sotmp = 0.5  # snowmelt is occuring - use min temp

            # oxygen calculation
            dummy = sotmp * (0.007991 - 0.77774E-4 * sotmp)
            sodox = (14.652 + sotmp * (-0.41022 + dummy)) * elevgc

            # carbon dioxide calculation
            abstmp = sotmp + 273.16
            dummy = 2385.73 / abstmp - 14.0184 + 0.0152642 * abstmp
            soco2 = 10.0**dummy * 3.16e-04 * elevgc * 12000.0

            if surli > 0.0 and slifac > 0.0:  # check for effects of lateral inflow
                if slitmp >= -1.0e10:   # there is temperature of surface lateral inflow
                    sotmp = slitmp * slifac + sotmp * (1.0 - slifac)
                if slidox >= 0.0:    # there is do conc of surface lateral inflow
                    sodox = slidox * slifac + sodox * (1.0 - slifac)
                if slico2 >= 0.0:  #there is co2 conc of surface lateral inflow
                    soco2 = slico2 * slifac + soco2 * (1.0 - slifac)

        # get interflow lateral inflow temp and concentrations
        ilitmp = -1.0e30
        ilidox = -1.0e30
        ilico2 = -1.0e30
        if ifwli > 0.0:    # there is lateral inflow
            ilitmp = ILITMP[loop]
            ilidox = ILIDOX[loop]
            ilico2 = ILICO2[loop]

        if dayfg:    # it is the first interval of the day
            idoxp = IDOXP[loop]
            ico2p = ICO2P[loop]

        iotmp = -1.0e30
        iodox = -1.0e30
        ioco2 = -1.0e30
        if ifwo > 0.0:   # there is interflow outflow
            # local interflow outflow temp equals upper soil temp
            iotmp = (ultmp - 32.0) * 5./9.
            if iotmp < 0.5:
                iotmp = 0.5    # min water temp

            iodox = idoxp
            ioco2 = ico2p

            if ifwli > 0.0 and ilifac > 0.0:
                # check for effects of lateral inflow
                if ilitmp >= -1.0e10:   # there is temperature of interflow lateral inflow
                    iotmp = ilitmp * ilifac + iotmp * (1.0 - ilifac)
                if ilidox >= 0.0:       # there is do conc of interflow lateral inflow
                    iodox = ilidox * ilifac + iodox * (1.0 - ilifac)
                if ilico2 >= 0.0:       # there is co2 conc of interflow lateral inflow
                    ioco2 = ilico2 * ilifac + ioco2 * (1.0 - ilifac)

        # get baseflow lateral inflow temp and concentrations
        alitmp = -1.0e30
        alidox = -1.0e30
        alico2 = -1.0e30
        if agwli > 0.0:
            alitmp = ALITMP[loop]
            alidox = ALIDOX[loop]
            alico2 = ALICO2[loop]

        if dayfg:    #it is the first interval of the day
            if gdvfg:
                adoxp = ADOXP[loop]
                aco2p = ACO2P[loop]

        aotmp = -1.0e30
        aodox = -1.0e30
        aoco2 = -1.0e30
        if agwo > 0.0:   # there is baseflow
            aotmp = (LGTMP[loop] - 32.0) * 5./9.		# local baseflow temp equals lower/gw soil temp
            if aotmp < 0.5:     # min water temp
                aotmp = 0.5

            aodox = adoxp
            aoco2 = aco2p
            if agwli > 0.0 and alifac > 0.0:   #check for effects of lateral inflow
                if alitmp >= -1.0e10:   # there is temperature of baseflow lateral inflow
                    aotmp = alitmp * alifac + aotmp * (1.0 - alifac)
                if alidox >= 0.0:	# there is do conc of baseflow lateral inflow
                    aodox = alidox * alifac + aodox * (1.0 - alifac)
                if alico2 >= 0.0:    # there is co2 conc of baseflow lateral inflow
                    aoco2 = alico2 * alifac + aoco2 * (1.0 - alifac)

        # compute the outflow of heat energy in water - units are deg. c-in./ivl
        soht = sotmp * suro * EFACTA
        ioht = iotmp * ifwo * EFACTA
        aoht = aotmp * agwo * EFACTA
        POHT[loop] = soht + ioht + aoht

        # calculate outflow mass of dox - units are mg-in./l-ivl
        sodoxm = sodox * suro * MFACTA
        iodoxm = iodox * ifwo * MFACTA
        aodoxm = aodox * agwo * MFACTA
        PODOXM[loop] = sodoxm + iodoxm + aodoxm

        # calculate outflow mass of co2 - units are mg-in./l-ivl
        soco2m = soco2 * suro * MFACTA
        ioco2m = ioco2 * ifwo * MFACTA
        aoco2m = aoco2 * agwo * MFACTA
        POCO2M[loop] = soco2m + ioco2m + aoco2m

        SOTMP[loop] = sotmp
        if sotmp > -1e28 and uunits!= 2:
            SOTMP[loop] = (sotmp * 9.0 / 5.0) + 32.0

        IOTMP[loop] = iotmp
        if iotmp > -1e28 and uunits!= 2:
            IOTMP[loop] = (iotmp * 9.0 / 5.0) + 32.0

        AOTMP[loop] = aotmp
        if aotmp > -1e28 and uunits!= 2:
            AOTMP[loop] = (aotmp * 9.0 / 5.0) + 32.0

        SODOX[loop]  = sodox
        SOCO2[loop]  = soco2
        IODOX[loop]  = iodox
        IOCO2[loop]  = ioco2
        AODOX[loop]  = aodox
        AOCO2[loop]  = aoco2
        SOHT[loop]   = soht
        IOHT[loop]   = ioht
        AOHT[loop]   = aoht

        SODOXM[loop] = sodoxm
        SOCO2M[loop] = soco2m
        IODOXM[loop] = iodoxm
        IOCO2M[loop] = ioco2m
        AODOXM[loop] = aodoxm
        AOCO2M[loop] = aoco2m

        if uunits == 2:
            SOHT[loop] = SOHT[loop] / 3.96567 * 2.471  # btu/ac to kcal/ha
            IOHT[loop] = IOHT[loop] / 3.96567 * 2.471  # btu/ac to kcal/ha
            AOHT[loop] = AOHT[loop] / 3.96567 * 2.471  # btu/ac to kcal/ha
            POHT[loop] = POHT[loop] / 3.96567 * 2.471  # btu/ac to kcal/ha
            SODOXM[loop] = SODOXM[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            SOCO2M[loop] = SOCO2M[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            IODOXM[loop] = IODOXM[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            IOCO2M[loop] = IOCO2M[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            AODOXM[loop] = AODOXM[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            AOCO2M[loop] = AOCO2M[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            PODOXM[loop] = PODOXM[loop] / 2.205 * 2.471  # lbs/ac to kg/ha
            POCO2M[loop] = POCO2M[loop] / 2.205 * 2.471  # lbs/ac to kg/ha

    return errorsV


class Solution:
    def countPairs(self, deliciousness: List[int]) -> int:
        ans=0
        freq=defaultdict(int)
        for item in deliciousness:
            for i in range(22):
                ans+=freq[2**i-item]
            freq[item]+=1
        return ans%(10**9+7)


import ipaddress
import time
from hack.scapy_arp_one import scapy_arp_request
from multiprocessing import Process, Queue

def scapy_arp_scan(network):
    qyt_queue = Queue()
    net = ipaddress.ip_network(network)
    for ip in net:
        ip_addr = str(ip)
        arp_one = Process(target=scapy_arp_request, args=(ip_addr, qyt_queue))
        arp_one.start()
    time.sleep(1)

    ip_mac_list = []
    while True:
        if qyt_queue.empty():
            break
        else:
            ip, mac = qyt_queue.get()
            ip_mac_list.append((ip, mac))
    return ip_mac_list

if __name__ == "__main__":

    active_ip_mac = scapy_arp_scan('192.168.2.0/24')
    print("活动的Ip与MAC地址如下：")
    # print(active_ip_mac)
    for ip, mac in active_ip_mac:
        # print(11111)
        print(ip, mac)


class Solution:
    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
        def isMagic(row, column):
            rows = [grid[row + x][column: column + 3] for x in range(0,3)]
            nums = []
            [nums.extend(row) for row in rows]
            if sorted(nums) != list(range(1, 10)):
                return False
            columns = []
            for i in range(0,3):
                foo = []
                for j in range(0,3):
                    foo.append(grid[row + j][column + i])
                columns.append(foo)

            diags = [
                [grid[row][column], grid[row + 1][column + 1], grid[row + 2][column + 2]],
                [grid[row][column + 2], grid[row + 1][column + 1], grid[row + 2][column]]
            ]
            s = sum(rows[0])
            return all(sum(row) == s for row in rows) and all(sum(foo) == s for foo in columns) and all(sum(d) == s for d in diags)

        ret = 0
        for i in range(len(grid) - 2):
            for j in range(len(grid[0]) - 2):
                if isMagic(i, j):
                    ret += 1

        return ret


"""Keyframe Sequence Class"""
from struct import unpack
from PyM3G.util import obj2str, const2str
from PyM3G.objects.object3d import Object3D

class KeyframeSequence(Object3D):
    """
    Encapsulates animation data as a sequence of time-stamped, vector-valued keyframes
    """

    def __init__(self):
        super().__init__()
        self.interpolation = None
        self.repeat_mode = None
        self.encoding = None
        self.duration = None
        self.valid_range_first = None
        self.valid_range_last = None
        self.component_count = None
        self.keyframe_count = None
        self.time = []
        self.vector_value = []
        self.vector_bias = []
        self.vector_scale = []

    def __str__(self):
        return obj2str(
            "KeyframeSequence",
            [
                ("Interpolation", const2str(self.interpolation)),
                ("Repeat Mode", const2str(self.repeat_mode)),
                ("Encoding", self.encoding),
                ("Duration", self.duration),
                ("Valid Range First", self.valid_range_first),
                ("Valid Range Last", self.valid_range_last),
                ("Component Count", self.component_count),
                ("Keyframe Count", self.keyframe_count),
                ("Time", f"Array of {len(self.time)} items"),
                ("Vector Value", f"Array of {len(self.vector_value)} items"),
                ("Vector Bias", f"Array of {len(self.vector_bias)} items"),
                ("Vector Scale", f"Array of {len(self.vector_scale)} items"),
            ],
        )

    def read(self, reader):
        super().read(reader)
        (
            self.interpolation,
            self.repeat_mode,
            self.encoding,
            self.duration,
            self.valid_range_first,
            self.valid_range_last,
            self.component_count,
            self.keyframe_count,
        ) = unpack(reader.read(23), "<3B5I")
        if self.encoding == 0:
            for _ in range(self.keyframe_count):
                self.time.append(unpack(reader.read(4), "<I")[0])
                self.vector_value.append(
                    unpack(
                        reader.read(4 * self.component_count),
                        f"<{self.component_count}f",
                    )
                )
        elif self.encoding == 1:
            self.vector_bias = unpack(
                reader.read(4 * self.component_count), f"<{self.component_count}f"
            )
            self.vector_scale = unpack(
                reader.read(4 * self.component_count), f"<{self.component_count}f"
            )
            for _ in range(self.keyframe_count):
                self.time.append(unpack(reader.read(4), "<I")[0])
                self.vector_value.append(
                    unpack(
                        reader.read(self.component_count), f"<{self.component_count}B"
                    )
                )
        elif self.encoding == 2:
            self.vector_bias = unpack(
                reader.read(4 * self.component_count), f"<{self.component_count}f"
            )
            self.vector_scale = unpack(
                reader.read(4 * self.component_count), f"<{self.component_count}f"
            )
            for _ in range(self.keyframe_count):
                self.time.append(unpack(reader.read(4), "<I")[0])
                self.vector_value.append(
                    unpack(
                        reader.read(2 * self.component_count),
                        f"<{self.component_count}H",
                    )
                )


class hesap():
    def __init__(self, hesapIDcopy):
        self.hesapID = hesapIDcopy

    def hesabıSil(self, connector):
        with connector.cursor() as cursor:
            deleteHesap = f"""DELETE FROM hesaplar WHERE hesapID = {self.hesapID}"""
            cursor.execute(deleteHesap)

        connector.commit()
        return

    def getHesapBakiye(self, connector):
        with connector.cursor() as cursor:

            bakiyeGoster = f"SELECT bakiye FROM hesaplar WHERE hesapID={self.hesapID}"
            cursor = connector.cursor()
            cursor.execute(bakiyeGoster)
            bakiye = cursor.fetchone()

        return bakiye[0]

    def getHesapCur(self, connector):
        with connector.cursor() as cursor:

            curGoster = f"SELECT curTYPE FROM hesaplar WHERE hesapID={self.hesapID}"
            cursor.execute(curGoster)
            cur = cursor.fetchone()

        return cur[0]

    def getGelirGider(self, connector):
        islemler = self.getIslemler(connector)
        gelir = 0
        gider = 0

        for x in islemler:
            if x[1]=="Para Yatırma":
                gelir = gelir + x[4]
            elif x[1]=="Para Cekme":
                gider = gider + x[4]
            elif x[1] == "Transfer":
                if x[2] == self.hesapID:
                    gider = gider + x[4]
                else:
                    gelir = gelir + x[4]
            elif x[1]=="Kredi Borcu":
                gider = gider + x[4]

        return [gelir, gider]

    def getIslemler(self, connector):
        with connector.cursor() as cursor:

            islemGoster = f"SELECT * FROM islemler WHERE kaynakID={self.hesapID} OR hedefID={self.hesapID}"
            cursor.execute(islemGoster)
            return cursor.fetchall()


import os
from django.core.files.storage import FileSystemStorage
from django.utils.crypto import get_random_string

class RandomFilenameStorage(FileSystemStorage):
    def get_available_name(self, name):
        """
        Returns a semi random filename that's free on the target storage
        system, and available for new content to be written to.
        """
        dir_name, file_name = os.path.split(name)
        file_root, file_ext = os.path.splitext(file_name)
        while True:
            # file_ext includes the dot.
            name = os.path.join(dir_name, "%s%s" % (
            get_random_string(), file_ext))
            if not self.exists(name):
                break

        return name


import unittest
import jekpost.jekpost_create as jek

from datetime import date

class JekpostTests(unittest.TestCase):
    def test_date_gets_formatted(self):
        """
        Check
            31-DEC-2016 (2016-12-31)
            1-NOV-2015  (2015-11-01)
            11-JAN-2015 (2015-01-11)
        """
        sample_dates = [    (date(2014, 12, 31), '2014-12-31'),
                            (date(2015, 11, 1), '2015-11-01'),
                            (date(2015, 1, 11), '2015-01-11')
                       ]

        for date_object, expected_date in sample_dates:
            with self.subTest(i=date_object):
                formatted_date = jek.get_date_formatted(date_object)
                self.assertEqual(formatted_date, expected_date)

    def test_make_filename(self):
        date_formatted = '2014-12-31'
        title = 'Post 01'
        expected_filename = '2014-12-31-Post-01.md'

        result_filename = jek.make_filename(title, date_formatted)
        self.assertEqual(result_filename, expected_filename)

if __name__ == '__main__':
    unittest.main()


import sys
from .generator import genImage
from PIL import Image
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("line1")
parser.add_argument("line2")
parser.add_argument("--rupper", action="store_true")
parser.add_argument("--rlower", action="store_true")

args = parser.parse_args()

image = genImage(
	word_a=args.line1,
	word_b=args.line2,
	rainbow_upper=args.rupper,
	rainbow_lower=args.rlower
)

image.resize((int(image.size[0] * 0.75), int(image.size[1] * 0.75)), Image.Resampling.LANCZOS)

image.save(sys.stdout.buffer, "jpeg")


import uuid as uuid
from django.db import models
from WalletUser.models import WalletUser

class Transaction(models.Model):
    STATUS_TYPES = (
        ('C', 'Compleat'),
        ('S', 'Success'),
        ('I', 'Incompleat'),
        ('A', 'aborted'),
    )
    uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, db_index=True)
    status = models.CharField(choices=STATUS_TYPES, default='N', max_length=3)
    created_on = models.DateTimeField(auto_now_add=True, null=False)
    user = models.ForeignKey(WalletUser,on_delete=models.DO_NOTHING)
    amount = models.FloatField()

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


import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def draw_samples(dist, n, size):
    """
    Randomly pick n samples from a distribution and compute mean.
    :param dist: Distribution
    :param n: How often are samples drawn and mean determined
    :param size: How many samples should be drawn in one go
    :return: array with n means for every drawn step
    """
    means = np.zeros(n)
    for i in range(n):
        # Sample "size" samples from dist
        samples = np.random.choice(exp, size)
        means[i] = np.mean(samples)

    return means

# Create a exponential distribution
exp = np.random.exponential(.1, 1000000)

# Sample 100x 100 samples from distr
samples_exp = draw_samples(exp, 1000, 1000)

# Plotting
plt.subplot(2,1,1)
sns.distplot(exp)
plt.title("Exponential Dist")
plt.subplot(2,1,2)
sns.distplot(samples_exp)
plt.title("CLT")
plt.show()


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

# 下载服务器mt0~mt3

# 绘制地图
# http://mt0.google.cn/vt/lyrs=m@187000000&hl=zh-CN&gl=cn&src=app&x=104&y=52&z=7&s=Galil

# 卫星地图
# http://mt0.google.cn/vt/lyrs=s@118&hl=zh-CN&gl=cn&src=app&x=104&y=52&z=7&s=Gali

# 下载模板 需要传入4个参数使用

# 绘制地图
# DOWNURL = 'http://%s/vt/lyrs=m@187000000&hl=zh-CN&gl=cn&src=app&x=%d&y=%d&z=%d&s=Galil'

# 卫星地图
DOWNURL = 'http://%s/vt/lyrs=s@118&hl=zh-CN&gl=cn&src=app&x=%d&y=%d&z=%d&s=Gali'

TITLE = 'Google地图下载工具 v0.99'
WIDTH = 200
HEIGHT = 600

# 图片大小
# IMGSIZE = 256

# 标签文字

mapServers = ['mt0.google.cn', 'mt1.google.cn', 'mt2.google.cn', 'mt3.google.cn']

# 地图级别 0~19


import uvicorn
from fastapi import FastAPI, Depends, status
from database import get_db
from schemas import ProgressBase, StudentBase, StudentPublic, StudentWithProgress
from pymongo.collection import Collection

import service

app = FastAPI()

DEBUG = True

@app.get("/student/{id}")
async def get_single(id: int, db: Collection = Depends(get_db)):
    status = service.get_single_record(id, db)
    return status

@app.get('/student/')
def get_all(db: Collection = Depends(get_db)):
    status = service.get_all_record(db)
    return status

@app.post('/student/', status_code=status.HTTP_201_CREATED)
async def insert_single(student: StudentBase, progress: ProgressBase, db: Collection = Depends(get_db)):
    print(student)
    print(progress)
    status = service.insert_single_record(student, db)
    return status

@app.post('/students/', status_code=status.HTTP_201_CREATED)
async def insert_many(students: list[StudentWithProgress], db: Collection = Depends(get_db)):
    students_data = [data.student.dict() for data in students]
    print(students_data)
    status = service.insert_multiple_record(students_data, db)
    return status

@app.delete('/student/{id}')
def delete_single(id: int, db: Collection = Depends(get_db)):
    status = service.delete_single_record(id, db)
    return status

@app.delete('/student/')
def delete_all(db: Collection = Depends(get_db)):
    status = service.delete_all_record(db)
    return status

if __name__ == "__main__":
    uvicorn.run("main:app", debug=DEBUG, port=5000, reload=True)


import re

stroka = 'Privet menya zovut Alexey, mne 48 let, moi telephon 89632442231, a pochta akarpushev@yandex.ru'

# result = re.match(r'Privet menya zovut', stroka)
# print(result)
# print(result.group(0))
# print(result.start())
# print(result.end())
#
# result = re.search(r'telephon', stroka)
# print(result)
# print(result.group(0))
#
# result = re.split(r'moi', stroka)
# print(result)
#
# result = re.findall(r'telephon', stroka)
# print(result)

#phones = re.findall(r'\d+', stroka)
#pohnes =re.findall(r'\b\d\d\d\d\d\d\\b', stroka)
phones = re.findall(r'\d{7,11}', stroka)
print(phones)
email = re.findall(r'\w+@\w+\w+', stroka)
print(email)


import unittest
from unittest.mock import MagicMock

from pygame.surface import Surface
from parameterized import parameterized

from pygutils.animation import Animation

class AnimationTest(unittest.TestCase):
    animation_frames: list[Surface] = [
        Surface((10, 10)),
        Surface((20, 20)),
    ]

    def test_can_get_finished_status_from_animation(self):
        animation = Animation(self.animation_frames, 1)

        animation.index = 1
        self.assertFalse(animation.finished)

        animation.index = 2
        self.assertTrue(animation.finished)

    def test_can_retrieve_next_frame(self):
        animation = Animation(self.animation_frames, 1)
        animation.index = 0

        self.assertEqual(animation.next(), self.animation_frames[0])

    def test_can_reset_animation(self):
        animation = Animation(self.animation_frames, 1)
        animation.index = 1

        animation.reset()

        self.assertEqual(animation.index, 0)

    def test_update_do_nothing_for_finished_animation_that_isnt_a_loop(self):
        animation = Animation(self.animation_frames, 1, loop=False)
        animation.index = 1

        animation.update(1)

        self.assertEqual(animation.finished, True)
        self.assertEqual(animation.index, 2)

    def test_update_reset_finished_animation_when_it_is_a_loop(self):
        animation = Animation(self.animation_frames, 1)
        animation.index = 1

        animation.update(1)

        self.assertEqual(animation.finished, False)
        self.assertEqual(animation.index, 0)

    def test_call_callback_on_animation_finish(self):
        callback_mock = MagicMock(return_value=None)

        animation = Animation(self.animation_frames, 1, on_finish=callback_mock)
        animation.index = 1

        animation.update(1)

        callback_mock.assert_called_once()

    @parameterized.expand([(10, 0.02, 0.2), (10, 0.15, 1.5), (10, 0.1, 1)])
    def test_update_animation_index_relative_to_animation_speed_and_delta_time(
        self, animation_speed: int, delta_time: float, expected_index: float
    ):
        animation = Animation(self.animation_frames, animation_speed)
        animation.update(delta_time)

        self.assertEqual(animation.index, expected_index)

    def test_animation_can_make_a_copy_of_himself(self):
        animation = Animation(self.animation_frames, 1)
        animation.index = 1

        animation_copy = animation.copy()

        self.assertEqual(animation.loop, animation_copy.loop)
        self.assertEqual(animation.on_finish, animation_copy.on_finish)
        self.assertListEqual(animation.frames_sequence, animation_copy.frames_sequence)
        self.assertEqual(animation.animation_speed, animation_copy.animation_speed)
        self.assertEqual(0, animation_copy.index)


class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if len(nums)==len(set(nums)):
            return False
        for elem in set(nums):
            if nums.count(elem)>1:
                index=-100000
                for i in range(0,nums.count(elem)):
                    if nums.index(elem)-index<=k:
                        return True
                    else:
                        index=nums.index(elem)
                        nums[index]='a'
        return False


import streamlit as st
import pandas as pd

from hyperbench.provider import Provider

def display(datasets: list[Provider]):
    if datasets is None:
        st.write("The datasets attribute is left empty. It needs to be specified in the Options object.")
        return

    enabled = st.checkbox("Enable explorer")
    if enabled:
        table = pd.DataFrame([ds.stats for ds in datasets])
        table['dimension'] = table.n_rows * (table.n_columns + table.n_classes)
        st.dataframe(table)


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options=Options()
options.add_argument("--ignore-certificate-errors")
options.add_argument("--incognito")
driver=webdriver.Chrome(options=options)
driver.maximize_window()
driver.get("https://www.name.com/account/login")

element=driver.find_element_by_link_text("CREATE NEW ACCOUNT")
element.click()
time.sleep(1)
#driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")

element=driver.find_element_by_name("username")
element.send_keys("tto1991")

element=driver.find_element_by_name("password")
element.send_keys("123456789")

element=driver.find_element_by_xpath("//div[@class='checkbox form-tos control-group']/*/input")
print(element.tag_name)
time.sleep(1)
driver.execute_script("arguments[0].click();", element)

time.sleep(1)
select_country=driver.find_element_by_name("new-contact-country")
all_options=select_country.find_elements_by_tag_name("option")
for option in all_options:
	if(option.get_attribute("value")=="VN"):
		print(option.tag_name)
		option.click()

time.sleep(2)


#  coffee - 1.50
#  water - 1.00
#  coke - 1.40
#  snacks - 2.00

product_input = input()
product_quantity = int(input())

def total_price(product, quantity):
    price = 0
    if product == "coffee":
        price = quantity * 1.5
    elif product == "water":
        price = quantity * 1
    elif product == "coke":
        price = quantity * 1.4
    elif product == "snacks":
        price = quantity * 2
    return f"{price:.2f}"

print(total_price(product_input, product_quantity))


#!@PYTHON@
"""
Class :py:class:`FWViewAxis` is a widget with interactive axes
==============================================================

FWViewAxis <- FWView <- QGraphicsView <- QWidget

Usage ::

    Create FWViewAxis object within pyqt QApplication
    --------------------------------------------------
    import sys
    from PyQt4 import QtGui, QtCore
    from graphqt.FWViewAxis import FWViewAxis

    app = QtGui.QApplication(sys.argv)
    w = FWViewAxis(None, raxes=QtCore.QRectF(0, 0, 100, 100), origin='UL',\
                   scale_ctl='HV', rulers='TR')
    w.show()
    app.exec_()

    Connect/disconnecr recipient to signals
    ---------------------------------------

    Methods
    -------
    w.set_show_rulers(rulers='TBLR')
    w.reset_original_image_size()

    Internal methods
    -----------------

    Re-defines methods
    ------------------
    w.update_my_scene() # FWView.update_my_scene() + draw rulers
    w.set_style()       # sets FWView.set_style() + color, font, pen
    w.closeEvent()      # removes rulers, FWView.closeEvent()

Created on December 12, 2017 by Mikhail Dubrovin
"""
from __future__ import print_function

from graphqt.FWView  import FWView, QtGui, QtCore, Qt
from graphqt.FWRuler import FWRuler
#from graphqt.GUUtils import print_rect

class FWViewAxis(FWView) :

    def __init__(self, parent=None, rscene=QtCore.QRectF(0, 0, 10, 10), origin='UL', orient='U', **kwargs) :

        self.scale_ctl = kwargs.get('scale_ctl', True)
        self.wlength   = kwargs.get('wlength', 200)
        self.wwidth    = kwargs.get('wwidth', 50)

        self.set_origin(origin)
        self.orient = orient
        scale_ctl = orient if self.scale_ctl else ''

        FWView.__init__(self, parent, rscene, origin, scale_ctl='HV')

        self._name = self.__class__.__name__
        #self.set_style() # called in FWView
        self.update_my_scene()

    def set_style(self) :
        FWView.set_style(self)
        self.colax = QtGui.QColor(Qt.white)
        self.fonax = QtGui.QFont('Courier', 12, QtGui.QFont.Normal)
        self.penax = QtGui.QPen(Qt.white, 1, Qt.SolidLine)

        if self.orient in ('U', 'D') :
            self.setMinimumSize(self.wlength, 2)
            self.setFixedHeight(self.wwidth)
        else :
            self.setMinimumSize(2, self.wlength)
            self.setFixedWidth(self.wwidth)

        #self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)

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

    def update_my_scene(self) :
        FWView.update_my_scene(self)

        sc = self.scene()
        rs = sc.sceneRect()
        ra = rs
        self.ruler = FWRuler(sc, orient=self.orient, color=self.colax, pen=self.penax, font=self.fonax)

        return

        #print_rect(ra, cmt='YYY FWViewAxis axes rect')

        if self._origin_ul :
            if self.orient=='L' : self.ruler = FWRuler(s, 'L')
            if self.orient=='D' : self.ruler = FWRuler(s, 'D')
            if self.orient=='U' : self.ruler = FWRuler(s, 'U')
            if self.orient=='R' : self.ruler = FWRuler(s, 'R')
        return

        if self._origin_dl :
            pass

        elif self._origin_dr :
            pass

        elif self._origin_ur :
            #print 'UR'
            pass

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

    def reset_original_image_size(self) :
         # def in FWView.py with overloaded update_my_scene()
         self.reset_original_size()

#    def reset_original_image_size(self) :
#        self.set_view()
#        self.update_my_scene()
#        self.check_axes_limits_changed()

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

    def closeEvent(self, e):
        self.rulerl = None
        self.rulerb = None
        self.rulerr = None
        self.rulert = None
        FWView.closeEvent(self, e)
        #print 'FWViewAxis.closeEvent'

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

def test_guiview(tname) :
    print('%s:' % sys._getframe().f_code.co_name)
    app = QtGui.QApplication(sys.argv)
    w = None
    rs=QtCore.QRectF(0, 0, 100, 100)
    if   tname == '0': w=FWViewAxis(None, rs, origin='UL', orient='L')
    elif tname == '1': w=FWViewAxis(None, rs, origin='UL', orient='U')
    elif tname == '2': w=FWViewAxis(None, rs, origin='UL', orient='R')
    elif tname == '3': w=FWViewAxis(None, rs, origin='UL', orient='D')
    elif tname == '4': w=FWViewAxis(None, rs, origin='DR', orient='L')
    elif tname == '5': w=FWViewAxis(None, rs, origin='DR', orient='U')
    elif tname == '6': w=FWViewAxis(None, rs, origin='DR', orient='D')
    elif tname == '7': w=FWViewAxis(None, rs, origin='DR', orient='R')
    else :
        print('test %s is not implemented' % tname)
        return

    #w.connect_axes_limits_changed_to(w.test_axes_limits_changed_reception)
    #w.disconnect_axes_limits_changed_from(w.test_axes_limits_changed_reception)
    w.show()
    app.exec_()

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

if __name__ == "__main__" :
    import sys; global sys
    import numpy as np; global np
    tname = sys.argv[1] if len(sys.argv) > 1 else '0'
    print(50*'_', '\nTest %s' % tname)
    test_guiview(tname)
    sys.exit('End of Test %s' % tname)

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


# This script will copy snapshot with matching tags from "us-east-1" to "eu - central -1".

import boto3, json

session = boto3.Session(profile_name = 'development')

east1 = 'us-east-1'
central1 = 'eu-central-1'

ec2East = session.client('ec2', region_name = east1)
ec2Central = session.client('ec2', region_name = central1)

tag_match = ec2East.describe_snapshots ( Filters = [ {'Name': 'tag:Copy', 'Values': ['True'] } ] )
SnapshotIDs = []
snap = tag_match['Snapshots']
for i in snap:
    SnapshotIDs.append(i['SnapshotId'])
print('Target Snapshot ID: ', SnapshotIDs)

for j in SnapshotIDs:
    response = ec2Central.copy_snapshot(
        Description='This is my copied snapshot.',
        DestinationRegion = central1,
        SourceRegion = east1,
        SourceSnapshotId = j,
    )
print(response)


from bs4 import BeautifulSoup

def get_ingredients(page_text):
    soup = BeautifulSoup(page_text, "html.parser")
    all_ingredients = soup.findAll('span', itemprop="recipeIngredient")
    counts = [i.text.lower() for i in soup.findAll('span', class_='emotion-15im4d2')]
    return [ing.text.lower() for ing in all_ingredients], counts

def get_description(page_text):
    soup = BeautifulSoup(page_text, "html.parser")
    description = soup.find('span', class_="emotion-1x1q7i2")
    if description is None:
        return ""
    return description.text

def get_energy(page_text):
    soup = BeautifulSoup(page_text, "html.parser")
    calories = soup.find('span', itemprop='calories').text
    protein = soup.find('span', itemprop='proteinContent').text
    fat = soup.find('span', itemprop='fatContent').text
    carbohydrate = soup.find('span', itemprop='carbohydrateContent').text
    return [calories, protein, fat, carbohydrate]

def get_steps(page_text):
    soup = BeautifulSoup(page_text, "html.parser")
    steps = soup.findAll('div', itemprop='recipeInstructions')
    steps = [step.text for step in steps]
    return steps


'''
4. Реализуйте базовый класс Car:

    ● у класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А
    также методы: go, stop, turn(direction), которые должны сообщать, что машина
    поехала, остановилась, повернула (куда);

    ● опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar;

    ● добавьте в базовый класс метод show_speed, который должен показывать текущую
    скорость автомобиля;

    ● для классов TownCar и WorkCar переопределите метод show_speed. При значении
    скорости свыше 60 (TownCar) и 40 (WorkCar) должно выводиться сообщение о
    превышении скорости.

Создайте экземпляры классов, передайте значения атрибутов. Выполните доступ к атрибутам,
выведите результат. Вызовите методы и покажите результат.
'''

class Car:

    def __init__(self, name, speed, color, is_police=False):
        self.name = name
        self.speed = speed
        self.color = color
        self.is_police = is_police

    def go(self):
        return f'Машина {self.name} поехала.'

    def stop(self):
        return f'\nМашина {self.name} остановилась.'

    def turn(self, direction):
        return f'\nМашина {self.name} повернула {direction}'

    def show_speed(self):
        return f'\nСкорость: {self.speed}'

class TownCar(Car):
    def show_speed(self):
        if self.speed > 60:
            return f'\nВаша скорость {self.speed}. Это выше, чем разрешено!'
        else:
            return f'Скорость {self.name} нормальная'

class SportCar(Car):
    pass

class WorkCar(Car):
    def show_speed(self):
        if self.speed > 40:
            return f'\nВаша скорость {self.speed}. Это выше, чем разрешено!'
        else:
            return f'Скорость {self.name} нормальная'

class PoliceCar(Car):
    pass

town = TownCar('Audi', 65, 'blue', False)
print('1:' + town.go(), town.show_speed(),
      town.turn('налево'), town.turn('направо'), town.stop(), '\n')

sport = SportCar('Jaguar_XK', 120, 'red', False)
print('2:' + sport.go(), sport.show_speed(),
      sport.turn('налево'), sport.stop(), '\n')

work = WorkCar('MAZ', 50, 'red', False)
print('3:' + work.go(), work.show_speed(),
      work.turn('направо'), work.stop(), '\n')

work = WorkCar('MAZ', 39, 'red', False)
print('4:' + work.go(), work.show_speed(),
      work.turn('налево'), work.stop(), '\n')

police = PoliceCar('Porsche_911', 180, 'yellow', True)
print('5:' + police.go(), police.show_speed(),
      police.turn('направо'), police.stop())


##############################################################
# This a app to convert insulin units based on caloric grams.
# Author Joseph Nadeau
# Date 11/25/2019
###############################################################

import os
os.system('clear')

insulin_units = 0
carb_grams = 0
round_insulin_units = 0

print("  ********************************")
print("  *                              *")
print("  *  Carb Grams to Insulin Unit  *")
print("  *                              *")
print("  ********************************")
print("")

carb_grams = float(input("\tEnter carb grams.\n\n\t\t"))

print("")

blood_sugar = int(input("\tEnter blood sugar.\n\n\t\t"))
if(blood_sugar >= 181) and (blood_sugar <= 240):
    blood_sugar = insulin_units + 1

elif(blood_sugar >= 241) and (blood_sugar <= 320):
    blood_sugar = insulin_units + 2

else:
    (blood_sugar <= 181)
    blood_sugar = insulin_units + 0

print("")
insulin_units = carb_grams/15
print("  " + str(carb_grams) + " carb grams = " + str(round(insulin_units, 2))
 + " Insulin Units with adjustments of " + str(blood_sugar) + " Insulin units\n")


# SPDX-License-Identifier: GPL-2.0-or-later

from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QTabWidget, QWidget, QScrollArea, QApplication, QVBoxLayout
from PyQt5.QtGui import QPalette

from constants import KEYCODE_BTN_RATIO
from widgets.display_keyboard import DisplayKeyboard
from widgets.display_keyboard_defs import ansi_100, ansi_80, ansi_70, iso_100, iso_80, iso_70, mods, mods_narrow
from widgets.flowlayout import FlowLayout
from keycodes.keycodes import KEYCODES_BASIC, KEYCODES_ISO, KEYCODES_MACRO, KEYCODES_LAYERS, KEYCODES_QUANTUM, \
    KEYCODES_BOOT, KEYCODES_MODIFIERS, \
    KEYCODES_BACKLIGHT, KEYCODES_MEDIA, KEYCODES_SPECIAL, KEYCODES_SHIFTED, KEYCODES_USER, Keycode, \
    KEYCODES_TAP_DANCE, KEYCODES_MIDI, KEYCODES_BASIC_NUMPAD, KEYCODES_BASIC_NAV, KEYCODES_ISO_KR
from widgets.square_button import SquareButton
from util import tr, KeycodeDisplay

class AlternativeDisplay(QWidget):

    keycode_changed = pyqtSignal(str)

    def __init__(self, kbdef, keycodes, prefix_buttons):
        super().__init__()

        self.kb_display = None
        self.keycodes = keycodes
        self.buttons = []

        self.key_layout = FlowLayout()

        if prefix_buttons:
            for title, code in prefix_buttons:
                btn = SquareButton()
                btn.setRelSize(KEYCODE_BTN_RATIO)
                btn.setText(title)
                btn.clicked.connect(lambda st, k=code: self.keycode_changed.emit(title))
                self.key_layout.addWidget(btn)

        layout = QVBoxLayout()
        if kbdef:
            self.kb_display = DisplayKeyboard(kbdef)
            self.kb_display.keycode_changed.connect(self.keycode_changed)
            layout.addWidget(self.kb_display)
            layout.setAlignment(self.kb_display, Qt.AlignHCenter)
        layout.addLayout(self.key_layout)
        self.setLayout(layout)

    def recreate_buttons(self, keycode_filter):
        for btn in self.buttons:
            btn.deleteLater()
        self.buttons = []

        for keycode in self.keycodes:
            if not keycode_filter(keycode.qmk_id):
                continue
            btn = SquareButton()
            btn.setRelSize(KEYCODE_BTN_RATIO)
            btn.setToolTip(Keycode.tooltip(keycode.qmk_id))
            btn.clicked.connect(lambda st, k=keycode: self.keycode_changed.emit(k.qmk_id))
            btn.keycode = keycode
            self.key_layout.addWidget(btn)
            self.buttons.append(btn)

        self.relabel_buttons()

    def relabel_buttons(self):
        if self.kb_display:
            self.kb_display.relabel_buttons()

        KeycodeDisplay.relabel_buttons(self.buttons)

    def required_width(self):
        return self.kb_display.sizeHint().width() if self.kb_display else 0

    def has_buttons(self):
        return len(self.buttons) > 0

class Tab(QScrollArea):

    keycode_changed = pyqtSignal(str)

    def __init__(self, parent, label, alts, prefix_buttons=None):
        super().__init__(parent)

        self.label = label
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.alternatives = []
        for kb, keys in alts:
            alt = AlternativeDisplay(kb, keys, prefix_buttons)
            alt.keycode_changed.connect(self.keycode_changed)
            self.layout.addWidget(alt)
            self.alternatives.append(alt)

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        w = QWidget()
        w.setLayout(self.layout)
        self.setWidget(w)

    def recreate_buttons(self, keycode_filter):
        for alt in self.alternatives:
            alt.recreate_buttons(keycode_filter)
        self.setVisible(self.has_buttons())

    def relabel_buttons(self):
        for alt in self.alternatives:
            alt.relabel_buttons()

    def has_buttons(self):
        for alt in self.alternatives:
            if alt.has_buttons():
                return True
        return False

    def select_alternative(self):
        # hide everything first
        for alt in self.alternatives:
            alt.hide()

        # then display first alternative which fits on screen w/o horizontal scroll
        for alt in self.alternatives:
            if self.width() - self.verticalScrollBar().width() > alt.required_width():
                alt.show()
                break

    def resizeEvent(self, evt):
        super().resizeEvent(evt)
        self.select_alternative()

class SimpleTab(Tab):

    def __init__(self, parent, label, keycodes):
        super().__init__(parent, label, [(None, keycodes)])

def keycode_filter_any(kc):
    return True

def keycode_filter_masked(kc):
    return Keycode.is_basic(kc)

class FilteredTabbedKeycodes(QTabWidget):

    keycode_changed = pyqtSignal(str)
    anykey = pyqtSignal()

    def __init__(self, parent=None, keycode_filter=keycode_filter_any):
        super().__init__(parent)

        self.keycode_filter = keycode_filter

        self.tabs = [
            Tab(self, "Basic", [
                (ansi_100, KEYCODES_SPECIAL + KEYCODES_SHIFTED),
                (ansi_80, KEYCODES_SPECIAL + KEYCODES_BASIC_NUMPAD + KEYCODES_SHIFTED),
                (ansi_70, KEYCODES_SPECIAL + KEYCODES_BASIC_NUMPAD + KEYCODES_BASIC_NAV + KEYCODES_SHIFTED),
                (None, KEYCODES_SPECIAL + KEYCODES_BASIC + KEYCODES_SHIFTED),
            ], prefix_buttons=[("Any", -1)]),
            Tab(self, "ISO/JIS", [
                (iso_100, KEYCODES_SPECIAL + KEYCODES_SHIFTED + KEYCODES_ISO_KR),
                (iso_80, KEYCODES_SPECIAL + KEYCODES_BASIC_NUMPAD + KEYCODES_SHIFTED + KEYCODES_ISO_KR),
                (iso_70, KEYCODES_SPECIAL + KEYCODES_BASIC_NUMPAD + KEYCODES_BASIC_NAV + KEYCODES_SHIFTED +
                 KEYCODES_ISO_KR),
                (None, KEYCODES_ISO),
            ], prefix_buttons=[("Any", -1)]),
            SimpleTab(self, "Layers", KEYCODES_LAYERS),
            Tab(self, "Quantum", [(mods, (KEYCODES_BOOT + KEYCODES_QUANTUM)),
                                  (mods_narrow, (KEYCODES_BOOT + KEYCODES_QUANTUM)),
                                  (None, (KEYCODES_BOOT + KEYCODES_MODIFIERS + KEYCODES_QUANTUM))]),
            SimpleTab(self, "Backlight", KEYCODES_BACKLIGHT),
            SimpleTab(self, "App, Media and Mouse", KEYCODES_MEDIA),
            SimpleTab(self, "MIDI", KEYCODES_MIDI),
            SimpleTab(self, "Tap Dance", KEYCODES_TAP_DANCE),
            SimpleTab(self, "User", KEYCODES_USER),
            SimpleTab(self, "Macro", KEYCODES_MACRO),
        ]

        for tab in self.tabs:
            tab.keycode_changed.connect(self.on_keycode_changed)

        self.recreate_keycode_buttons()
        KeycodeDisplay.notify_keymap_override(self)

    def on_keycode_changed(self, code):
        if code == "Any":
            self.anykey.emit()
        else:
            self.keycode_changed.emit(Keycode.normalize(code))

    def recreate_keycode_buttons(self):
        prev_tab = self.tabText(self.currentIndex()) if self.currentIndex() >= 0 else ""
        while self.count() > 0:
            self.removeTab(0)

        for tab in self.tabs:
            tab.recreate_buttons(self.keycode_filter)
            if tab.has_buttons():
                self.addTab(tab, tr("TabbedKeycodes", tab.label))
                if tab.label == prev_tab:
                    self.setCurrentIndex(self.count() - 1)

    def on_keymap_override(self):
        for tab in self.tabs:
            tab.relabel_buttons()

class TabbedKeycodes(QWidget):

    keycode_changed = pyqtSignal(str)
    anykey = pyqtSignal()

    def __init__(self):
        super().__init__()

        self.target = None
        self.is_tray = False

        self.layout = QVBoxLayout()

        self.all_keycodes = FilteredTabbedKeycodes()
        self.basic_keycodes = FilteredTabbedKeycodes(keycode_filter=keycode_filter_masked)
        for opt in [self.all_keycodes, self.basic_keycodes]:
            opt.keycode_changed.connect(self.keycode_changed)
            opt.anykey.connect(self.anykey)
            self.layout.addWidget(opt)

        self.setLayout(self.layout)
        self.set_keycode_filter(keycode_filter_any)

    @classmethod
    def set_tray(cls, tray):
        cls.tray = tray

    @classmethod
    def open_tray(cls, target, keycode_filter=None):
        cls.tray.set_keycode_filter(keycode_filter)
        cls.tray.show()
        if cls.tray.target is not None and cls.tray.target != target:
            cls.tray.target.deselect()
        cls.tray.target = target

    @classmethod
    def close_tray(cls):
        if cls.tray.target is not None:
            cls.tray.target.deselect()
        cls.tray.target = None
        cls.tray.hide()

    def make_tray(self):
        self.is_tray = True
        TabbedKeycodes.set_tray(self)

        self.keycode_changed.connect(self.on_tray_keycode_changed)
        self.anykey.connect(self.on_tray_anykey)

    def on_tray_keycode_changed(self, kc):
        if self.target is not None:
            self.target.on_keycode_changed(kc)

    def on_tray_anykey(self):
        if self.target is not None:
            self.target.on_anykey()

    def recreate_keycode_buttons(self):
        for opt in [self.all_keycodes, self.basic_keycodes]:
            opt.recreate_keycode_buttons()

    def set_keycode_filter(self, keycode_filter):
        if keycode_filter == keycode_filter_masked:
            self.all_keycodes.hide()
            self.basic_keycodes.show()
        else:
            self.all_keycodes.show()
            self.basic_keycodes.hide()


from flask import Flask, render_template, request

import sqlite3 as sql

app = Flask(__name__)

@app.route("/")
def home():
    return render_template('home.html')

@app.route("/newstudent")
def new_student():
    return render_template('student.html')

@app.route("/addstudent", methods=['POST', 'GET'])
def addstudent():
    if request.method == 'POST':
        try:
            name = request.form['name']
            address = request.form['address']
            city = request.form['city']
            pin = request.form['pin']
            with sql.connect("database.db") as connection:
                my_cursor = connection.cursor()
                my_cursor.execute("INSERT INTO students (name, addr, city, pin) VALUES (?,?,?,?)", (name, address, city,
                                  pin))
                msg = "Record Successfully inserted"
        except:
            connection.rollback()
            msg = "Error inserting operations"
        finally:
            return render_template("result.html", msg=msg)
            connection.close()

@app.route("/list")
def list():
    connection = sql.connect("database.db")
    connection.row_factory = sql.Row
    my_cursor = connection.cursor()
    my_cursor.execute("SELECT * FROM students")
    rows = my_cursor.fetchall()
    return render_template('list.html', rows=rows)

if __name__ == '__main__':
    app.run(debug=True)


# -*- coding: utf-8 -*-
"""
Created on Fri May 13 13:10:10 2022

@author: GRCav
"""

#Faça o gráfico de dispersão do tamanho do pé (FootLen) em função da altura da pessoa (Height). Calcule (e mostre na tela) a correlação e plote a reta de regressão entre esses dados.

#importando a tabela
import pandas as pd
BDSinfo = pd.read_csv('https://raw.githubusercontent.com/rnwatanabe/BasesComputacionais2021/main/dados/BDSinfo.csv', delimiter = '\t')

#criando o gráfico de dispersão
import matplotlib.pyplot as plt
plt.figure()
plt.plot(BDSinfo['FootLen'], BDSinfo['Height'], marker = "o", color = 'red', linestyle = '')
plt.xlabel('Tamanho do pé (FootLen)')
plt.ylabel('Altura da pessoa (Height)')
plt.grid()
plt.show()

#Calcule (e mostre na tela) a correlação
corr_BDSinfo = BDSinfo['FootLen'].corr(BDSinfo['Height'])
print(corr_BDSinfo)

#plote a reta de regressão entre esses dados
#Calculando a Regressão
import numpy as np
x = BDSinfo['FootLen']
y = BDSinfo['Height']
mediaX = np.mean(x)
mediaY = np.mean(y)
DesvioX = x - mediaX
DesvioY = y - mediaY
m = np.sum(DesvioX * DesvioY)/np.sum(DesvioX**2)
b = mediaY - m * mediaX
print(m)
print(b)

#Fazendo o gráfico da reta estimada pela regressão
import matplotlib.pyplot as plt
plt.figure()
plt.plot(BDSinfo['FootLen'], BDSinfo['Height'], marker = "o", color = 'red', linestyle = '')
plt.plot(x, m * x + b, color = 'blue', linestyle = '-')
plt.xlabel('Tamanho do pé (FootLen)')
plt.ylabel('Altura da pessoa (Height)')
plt.grid()
plt.show()


import heapq
class Solution(object):
    def stoneGameVI(self, aliceValues, bobValues):
        n = len(aliceValues)
        vals = []
        for i in range(n):
            heapq.heappush(vals,(-aliceValues[i]-bobValues[i],i))
        t = 0
        alice,bob = 0,0
        while vals:
            _,i = heapq.heappop(vals)
            if t %2 ==0:
                alice += aliceValues[i]
            else:
                bob  += bobValues[i]
            t +=1
        re = alice-bob
        #print(alice,bob)
        if re == 0 :
            return 0
        return 1 if re>0 else -1

re = Solution().stoneGameVI(aliceValues = [1,2], bobValues = [3,1])
print(re)
print(1^1,0^1)