'''
    count_terms_in_w2v.py

    Run MATCH with PeTaL data.
    Last modified on 16 July 2021.

    DESCRIPTION

        count_terms_in_w2v.py analyses a w2v model file *.joint.emb
        which is formatted with rows such as:

        REFP_1996578662 0.225306 -0.056286 0.002683 0.012376 ...

        where the first item is a token and the rest are its embedding
        in a 100-dimensional space.

        It counts the number of tokens of each class (reference, venues,
        authors, MAG, MeSH, labels, other) and prints that to stdout.
        That's all.

    OPTIONS

        -f, --file PATH/TO/PeTaL.joint.emb
            path to w2v model file (must exist)

    USAGE

        python3 count_terms_in_w2v.py -f PATH/TO/PeTaL.joint.emb

    NOTES

        Not really necessary to run anyhow.

    Authors: Eric Kong (eric.l.kong@nasa.gov, erickongl@gmail.com)
'''

import click
from tqdm import tqdm

@click.command()
@click.option('-f', '--file', type=click.Path(exists=True), help='Path of w2v model file.')

def main(file):
    """Counts types of terms in a w2v model.

    Args:
        file (str): Path of w2v model file.
    """
    count(file)

def count(file):
    """Counts types of terms in a w2v model.

    Args:
        file (str): Path of w2v model file.
    """
    ref_terms = set()
    venue_terms = set()
    author_terms = set()
    MAG_terms = set()
    MESH_terms = set()
    label_terms = set()
    words = set()
    with open(file) as f:
        for line in tqdm(f):
            token = line.split()[0]
            if token.startswith('REFP_'):
                ref_terms.add(token)
            elif token.startswith('VENUE_'):
                venue_terms.add(token)
            elif token.startswith('AUTHOR_'):
                author_terms.add(token)
            elif token.startswith('MAG_'):
                MAG_terms.add(token)
            elif token.startswith('MESH_'):
                MESH_terms.add(token)
            elif token.startswith('LABEL_'):
                label_terms.add(token)
            else:
                words.add(token)
    num_refs, num_venues, num_authors, num_MAGs, num_MESHes, num_labels, num_others = (
        len(ref_terms), len(venue_terms), len(author_terms),
        len(MAG_terms), len(MESH_terms), len(label_terms), len(words)
    )
    print(f"Number of unique reference terms: {num_refs}")
    print(f"Number of unique venue terms: {num_venues}")
    print(f"Number of unique author terms: {num_authors}")
    print(f"Number of unique MAG terms: {num_MAGs}")
    print(f"Number of unique MeSH terms: {num_MESHes}")
    print(f"Number of unique label terms: {num_labels}")
    print(f"Number of unique other words: {num_others}")
    print(f"Total unique terms: {num_refs + num_venues + num_authors + num_MAGs + num_MESHes + num_labels + num_others}")

if __name__ == '__main__':
    main()


"""
A bunch of things to copy paste together fragments of C-code

This is like a literate style but without the readability.
"""

import os, numpy.f2py, tempfile

class compiler:
    """ to test if things can compile """
    def compile(self, cname, oname):
        ret = subprocess.run( " ".join([self.CC,] + self.CFLAGS +
                             ["-c", cname,"-o", oname]),
                                  shell = True, capture_output=True )
        return ret

# universal compiler flags:
UFL = "-Wmissing-prototypes -Wshadow -Wconversion"
UFL = "-std=c99 -fopenmp -Wall -Wall -Wstrict-prototypes -Wshadow -Wmissing-prototypes -Wconversion".split()

if "CONDA_PREFIX" in os.environ:
    UFL.append( "-I%s/include"%(os.environ['CONDA_PREFIX']) )
else:
    for p in ("/usr/include/hdf5/serial",):
        if os.path.exists( os.path.join(p, 'hdf5.h') ):
            UFL.append( "-I%s"%(p) )
            break

class GCC(compiler):
    CC = 'gcc'
    CFLAGS = UFL + [ '-O2', '-fsanitize=undefined']

class CLANG(compiler):
    CC = 'clang'
    CFLAGS = UFL + [ '-O2' ]

class ICC(compiler):
    # module load Intel/2020 at ESRF
    CC = 'icc'
    CFLAGS = ['-qopenmp', '-O2', '-Wall' ]

class cfrag:
    """ A fragment of C code to insert. May have a defer to
    put at the end of a logical block """
    def __init__(self, fragment, defer=None):
        self.fragment = fragment
        self.defer = defer

# Type maps for f2py wrappers
TMAP = {
    'char*': 'character*(*)',
    'uint8_t':'integer(kind=-1)',
    'int8_t': 'integer(kind=1)',
    'int16_t': 'integer(kind=2)',
    'int32_t': 'integer(kind=4)',
    'int64_t': 'integer(kind=8)',
    'uint16_t': 'integer(kind=-2)',
    'uint32_t': 'integer(kind=-4)',
    'uint64_t': 'integer(kind=-8)',
    'int': 'integer(kind=4)', # doubtful
    'size_t': 'integer(kind=8)', # surely wrong
    'size_t*' : 'integer(kind=8), intent(out)',
}

class cfunc:
    """ A C function, name, arguments, body """
    def __init__(self, name, args, body):
        self.name = name
        self.args = args
        self.body = body
    def signature(self):
        """ for a header"""
        types = [" ".join( a.split()[:-1]) for a in self.args ]
        return "%s ( %s );\n" % ( self.name, ", ".join( types ) )
    def definition(self):
        """ for the main source"""
        if self.name.startswith("void "):
            return "%s ( %s ){\n%s\n}\n" % ( self.name, ", ".join( self.args ), self.body )
        if self.name.startswith("int "):      # returning an error status
            return "%s ( %s ){\n%s\n    return 0;\n}\n" % (
                 self.name, ", ".join( self.args ), self.body )
        if self.name.startswith("size_t "):   # returning a memory size
            return "%s ( %s ){\n%s\n}" % (
                 self.name, ", ".join( self.args ), self.body )
        raise Exception("add a return type case!!! : "+  str(self.name) )
    def pyf(self):
        """ generate a pyf file to make a wrapper """
        anames = []
        tnames = []
        atypes = []
        for a in self.args:
            tokens = a.split( )
            anames.append( tokens[-1] )
        fname = self.name.split()[-1]
        sub = self.name.startswith("void") # no return value
        lines = ['\n']
        if sub:
            lines.append( "subroutine %s(%s)"%(fname, ",".join(anames)) )
        else:
            lines.append( "function %s(%s)"%(fname, ",".join(anames)) )
        lines.append( 'intent(c) %s'%(fname) )
        lines.append( 'intent(c)' )
        for argu in self.args:
#            lines.append('! %s'%(argu))
            tokens = argu.split( )
            a = tokens[-1]
            m = " ".join([ t for t in tokens[:-1] if t not in ('const','*')])
            t = " ".join(tokens[:-1])
            if t.find("*")>0 and t.find(" *")>0:
                if t.find("const")>=0:
                    intent = 'intent(in)'
                else:
                    intent = 'intent(inout)'
                dim = "dimension( %s_length)"%(a)
                try:
                    decl = ' , '.join( (TMAP[m], intent, dim ))
                except:
                    print(argu)
                    raise
                decl += ":: %s"%( a )
            elif a.endswith('_length'):
                decl = TMAP[m] + ' , intent( hide ), depend( %s ) :: %s'%(
                   a.replace('_length',''), a )
            else:
                decl = TMAP[m] + ' :: %s'%(a)
            lines.append( decl  )
        lines.append("threadsafe") # hmm
        if sub:
            lines.append( "end subroutine %s%(fname)" )
        else:
            ftype = " ".join( self.name.split()[:-1] )
            lines.append( TMAP[ftype] + " :: " + fname )
            lines.append( "end function %s"%(fname) )
        return lines +["\n"]

    def testcompile(self, cc=GCC() ):
        """ See if the thing can be compiled """
        with tempfile.NamedTemporaryFile( mode = 'w', suffix = '.c', dir=os.getcwd() ) as tmp:
            tmp.write( INCLUDES )
            tmp.write( MACROS )
            tmp.write( self.signature() )
            tmp.write( self.definition() )
            tmp.flush()
            ofile = tmp.name[:-1] + "o"
            ret = cc.compile( tmp.name, ofile )
        if os.path.exists( ofile ):
            os.remove( ofile )
            print("Compilation OK",cc.CC)
            if len(ret.stderr):
                print(ret.stderr.decode())
        else:
            print("Compilation failed")
            print(ret.stderr.decode())

class cfragments:
    """ a series of fragments """
    def __init__(self, **kwds):
        self.__dict__.update( kwds )
    def __add__(self, other):
        return cfragments( **{**self.__dict__, **other.__dict__} )
    def __call__(self, *names):
        lines = []
        for name in names:
            lines.append("/* begin: %s */"%(name))
            lines.append( self.__dict__[name].fragment )
            lines.append("/* ends: %s */"%(name))
        for name in names:
            if self.__dict__[name].defer is not None:
                lines.append("/* begin: %s */"%(name))
                lines.append( self.__dict__[name].defer )
                lines.append("/* end: %s */"%(name))
        return "\n".join(lines)

CLANG_FORMAT = "clang-format -i "
if os.path.exists(r"C:/program files/LLVM/bin/clang-format.exe"):
    CLANG_FORMAT = r'"C:/program files/LLVM/bin/clang-format.exe" -i '

def write_funcs(fname, funcs, includes, macros):
    """ Write a series of functions into a file """
    ks = sorted(funcs.keys())
    with open(fname, 'w') as cfile:
        cfile.write(includes)
        cfile.write(macros)
        for k in ks:
            print(k)
            cfile.write("/* Signature for %s */\n"%(k))
            cfile.write( funcs[k].signature() )
        for k in ks:
            print(k)
            cfile.write("/* Definition for %s */\n"%(k))
            cfile.write( funcs[k].definition() )
    os.system(CLANG_FORMAT + fname)

def write_pyf(modname, fname, funcs):
    """ Write a pyf file """
    ks = sorted(funcs.keys())
    with open(modname+'.pyf','w') as pyf:
        pyf.write("""
python module %s

interface
        """%(modname))
        for k in ks:
            pyf.write("\n".join(funcs[k].pyf()))
        pyf.write("end interface\n")
        pyf.write("end module %s\n"%(modname))
    numpy.f2py.run_main( [modname+".pyf"] )

def test_funcs_compile(funcs):
    for func in funcs.keys():
        print(func)
        for compiler in GCC(), CLANG():
            funcs[func].testcompile(cc=compiler)


from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from register.models import *
from django.views.generic import View
from django.contrib import messages
from django.shortcuts import redirect
from .models import *
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.list import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.detail import DetailView
from django.shortcuts import get_object_or_404

# Create your views here.

class CartView(View):
    def get(self, request, *args, **kwargs):
        cart_items = Korzina.objects.filter(user=request.user.id)
        total_price = 0
        for item in cart_items:
            food = item.id_food
            if item.size == 'mini':
                item.total_price = item.quantity * food.mini
                item.price_per_item = food.mini
            elif item.size == 'medium':
                item.total_price = item.quantity * food.medium
                item.price_per_item = food.medium
            elif item.size == 'mega':
                item.total_price = item.quantity * food.mega
                item.price_per_item = food.mega
            total_price += item.total_price
        return render(request, 'shoping/cart.html', {'cart_items': cart_items, 'total_price': total_price})

class PurchaseView(View):
    def get(self, request, *args, **kwargs):
        cart_items = Korzina.objects.filter(user=request.user)
        total_price = 0
        for item in cart_items:
            food = item.id_food
            if item.size == 'mini':
                item.total_price = item.quantity * food.mini
                item.price_per_item = food.mini
            elif item.size == 'medium':
                item.total_price = item.quantity * food.medium
                item.price_per_item = food.medium
            elif item.size == 'mega':
                item.total_price = item.quantity * food.mega
                item.price_per_item = food.mega
            total_price += item.total_price
        return render(request, 'shoping/purchase.html', {'cart_items': cart_items, 'total_price': total_price})

    def post(self, request, *args, **kwargs):
        cart_items = Korzina.objects.filter(user=request.user)
        total_price = 0
        for item in cart_items:
            food = item.id_food
            if item.size == 'mini':
                item.total_price = item.quantity * food.mini
                item.price_per_item = food.mini
            elif item.size == 'medium':
                item.total_price = item.quantity * food.medium
                item.price_per_item = food.medium
            elif item.size == 'mega':
                item.total_price = item.quantity * food.mega
                item.price_per_item = food.mega
            total_price += item.total_price

        payment = request.POST.get('payment')

        try:
            payment = float(payment)
        except ValueError:
            messages.error(request, 'Введите корректную сумму оплаты')
            return redirect('purchase')

        if payment < total_price:
            messages.error(request, 'Сумма оплаты меньше стоимости заказа')
            return redirect('purchase')
        elif payment > total_price:
            messages.error(request, 'Сумма оплаты больше стоимости заказа')
            return redirect('purchase')
        else:
            purchase = Purchase.objects.create(user=request.user, payment_received=True, total_price=total_price)
            for item in cart_items:
                if item.size == 'mini':
                        purchase_item = PurchaseItem.objects.create(
                            purchase=purchase,
                            food=item.id_food,
                            quantity=item.quantity,
                            size=item.size,
                            price=item.id_food.mini,
                        )
                elif item.size == 'medium':
                        purchase_item = PurchaseItem.objects.create(
                            purchase=purchase,
                            food=item.id_food,
                            quantity=item.quantity,
                            size=item.size,
                            price=item.id_food.medium,
                        )
                elif item.size == 'mega':
                        purchase_item = PurchaseItem.objects.create(
                            purchase=purchase,
                            food=item.id_food,
                            quantity=item.quantity,
                            size=item.size,
                            price=item.id_food.mega,
                        )

            cart_items.delete()
            messages.success(request, 'Оплата прошла успешно')
            return HttpResponseRedirect("/", locals())

class PurchaseListView(LoginRequiredMixin, ListView):
    model = Purchase
    template_name = 'purchase_list.html'
    context_object_name = 'purchases'
    paginate_by = 10

    def get_queryset(self):
        return Purchase.objects.filter(user=self.request.user).order_by('-date_created')

class PurchaseDetailView(LoginRequiredMixin, DetailView):
    model = Purchase
    template_name = 'shoping/purchase_detail.html'
    context_object_name = 'purchase'

    def get_object(self):
        purchase_id = self.kwargs.get('purchase_id')
        purchase = get_object_or_404(Purchase, id=purchase_id, user=self.request.user)
        return purchase

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        purchase = self.get_object()
        purchase_items = PurchaseItem.objects.filter(purchase=purchase)
        context['purchase_items'] = purchase_items
        return context


import numpy as np
import pandas as pd

# A linear combination is all the possible vectors that can be reached by scaling a combination of vectors
# If you have 2 vectors, as long as they aren't the same line, you can reach any point in 2d space
# If they are on the same line, all you can really do is move along that line.
# Similar for 3 vectors, if they are all at least slightly different, you can access any point in 3d space.
# If the 3rd dimension is the same across all vectors, you would make a plane in 3d space

# A redundant vector in this case would be Linearly dependant, it can be expressed as a linear combination of another
# Vectors that do add another dimension Linearly independant

# I'm not sure I understand the question, I've gone with:
# "Which of the given vectors are linear combinations of another?"

def plane(a ,b ,c):
    # returns false if the vectors don't define a plane and returns which are those vectors if true

    # This was challenging more for finding the syntax than solving the problem, I went with "if a vector mod vector results in all 0s, it's a factor"

    if np.all(np.mod(a ,b) == 0) or (np.all(np.mod(b ,a) == 0)):
        print(f"{a} and {b} are linear combinations")
        return[a ,b]
    if (np.all(np.mod(a ,c) == 0)) or (np.all(np.mod(c ,a) == 0)):
        print(f"{a} and {c} are linear combinations")
        return[a ,c]
    if (np.all(np.mod(b ,c) == 0) ) or (np.all(np.mod(c ,b) == 0)):
        print(f"{b} and {c} are linear combinations")
        return[b ,c]

    return False

v1 = [1,2,3]
v2 = [2,2,2]
v3 = [8,8,8]

plane(v1,v2,v3)


# Converts an RGB image into grayscale and saves it in the same directory

import cv2
import numpy as np

img = cv2.imread('bu.png',0)

cv2.imwrite('saved_bu.png',img)

cv2.namedWindow('B/W image',cv2.WINDOW_NORMAL | cv2.WINDOW_FREERATIO)

cv2.imshow('B/W image',img)

cv2.waitKey(0)

cv2.destroyAllWindows()


import mock

import google.auth.credentials
import google_auth_httplib2
import httplib2
import oauth2client.client
import unittest2 as unittest

from googleapiclient import _auth

class TestAuthWithGoogleAuth(unittest.TestCase):
    def setUp(self):
        _auth.HAS_GOOGLE_AUTH = True
        _auth.HAS_OAUTH2CLIENT = False

    def tearDown(self):
        _auth.HAS_GOOGLE_AUTH = True
        _auth.HAS_OAUTH2CLIENT = True

    def test_credentials_from_file(self):
        with mock.patch(
            "google.auth.load_credentials_from_file", autospec=True
        ) as default:
            default.return_value = (mock.sentinel.credentials, mock.sentinel.project)

            credentials = _auth.credentials_from_file("credentials.json")

            self.assertEqual(credentials, mock.sentinel.credentials)

    def test_credentials_from_file(self):
        with mock.patch(
            "google.auth.load_credentials_from_file", autospec=True
        ) as default:
            default.return_value = (mock.sentinel.credentials, mock.sentinel.project)

            credentials = _auth.credentials_from_file("credentials.json")

            self.assertEqual(credentials, mock.sentinel.credentials)
            default.assert_called_once_with(
                "credentials.json", scopes=None, quota_project_id=None
            )


from typing import Dict
from unittest.mock import patch

import dm_env
import numpy as np
import pytest
from _pytest.monkeypatch import MonkeyPatch
from dm_env.specs import DiscreteArray

from mava.utils.environments.flatland_utils import check_flatland_import
from mava.wrappers.env_preprocess_wrappers import (
    ConcatAgentIdToObservation,
    ConcatPrevActionToObservation,
    StackObservations,
)
from tests.conftest import EnvSpec, Helpers
from tests.enums import EnvSource

_has_flatland = check_flatland_import()
"""
TestEnvWrapper is a general purpose test class that runs tests for environment wrappers.
This is meant to flexibily test various environments wrappers.

    It is parametrize by an EnvSpec object:
        env_name: [name of env]
        env_source: [What is source env - e.g. PettingZoo, RLLibMultiEnv or Flatland]
            - Used in confest to determine which envs and wrappers to load.

    For new environments - you might need to update the Helpers class in conftest.py.
"""

# TODO (Kale-ab): Test dying agents.
@pytest.mark.parametrize(
    "env_spec",
    [
        EnvSpec("pettingzoo.mpe.simple_spread_v2"),
        EnvSpec("pettingzoo.mpe.simple_spread_v2"),
        EnvSpec("pettingzoo.sisl.multiwalker_v8"),
        EnvSpec("pettingzoo.sisl.multiwalker_v8"),
        EnvSpec("flatland", EnvSource.Flatland) if _has_flatland else None,
    ],
)
class TestEnvWrapper:
    # Test that we can load a env module and that it contains agents,
    #   agents and possible_agents.
    def test_loadmodule(self, env_spec: EnvSpec, helpers: Helpers) -> None:
        if env_spec is None:
            pytest.skip()
        env = helpers.get_env(env_spec)
        props_which_should_not_be_none = [env, env.agents, env.possible_agents]
        assert helpers.verify_all_props_not_none(
            props_which_should_not_be_none
        ), "Failed to load module"

    #  Test initialization of env wrapper, which should have
    #   a nested environment, an observation and action space for each agent.
    def test_wrapper_initialization(self, env_spec: EnvSpec, helpers: Helpers) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        num_agents = len(wrapped_env.agents)

        props_which_should_not_be_none = [
            wrapped_env,
            wrapped_env.environment,
            wrapped_env.observation_spec(),
            wrapped_env.action_spec(),
            wrapped_env.reward_spec(),
            wrapped_env.discount_spec(),
        ]

        assert helpers.verify_all_props_not_none(
            props_which_should_not_be_none
        ), "Failed to ini wrapped env."
        assert (
            len(wrapped_env.observation_spec()) == num_agents
        ), "Failed to generate observation specs for all agents."
        assert (
            len(wrapped_env.action_spec()) == num_agents
        ), "Failed to generate action specs for all agents."
        assert (
            len(wrapped_env.reward_spec()) == num_agents
        ), "Failed to generate reward specs for all agents."
        assert (
            len(wrapped_env.discount_spec()) == num_agents
        ), "Failed to generate discount specs for all agents."

    # Test of reset of wrapper and that dm_env_timestep has basic props.
    def test_wrapper_env_reset(self, env_spec: EnvSpec, helpers: Helpers) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        num_agents = len(wrapped_env.agents)

        timestep = wrapped_env.reset()
        if type(timestep) == tuple:
            dm_env_timestep, env_extras = timestep
        else:
            dm_env_timestep = timestep
        props_which_should_not_be_none = [dm_env_timestep, dm_env_timestep.observation]

        assert helpers.verify_all_props_not_none(
            props_which_should_not_be_none
        ), "Failed to ini dm_env_timestep."
        assert (
            dm_env_timestep.step_type == dm_env.StepType.FIRST
        ), "Failed to have correct StepType."

        assert (
            len(dm_env_timestep.observation) == num_agents
        ), "Failed to generate observation for all agents."
        assert wrapped_env._reset_next_step is False, "_reset_next_step not set."

        helpers.assert_env_reset(wrapped_env, dm_env_timestep, env_spec)

    # Test that observations from petting zoo get converted to
    #   dm observations correctly. This only runs
    #   if wrapper has a _convert_observations or _convert_observation functions.
    def test_convert_env_to_dm_env_0_no_action_mask(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Does the wrapper have the functions we want to test
        if hasattr(wrapped_env, "_convert_observations") or hasattr(
            wrapped_env, "_convert_observation"
        ):
            #  Get agent names from env and mock out data
            agents = wrapped_env.agents
            test_agents_observations = {}
            for agent in agents:
                observation_spec = wrapped_env.observation_spec()
                if isinstance(observation_spec[agent].observation, tuple):
                    # Using the first dim for mock observation
                    observation_shape = observation_spec[agent].observation[0].shape
                else:
                    observation_shape = observation_spec[agent].observation.shape

                test_agents_observations[agent] = np.random.rand(
                    *observation_shape
                ).astype(np.float32)

            # Parallel env_types
            dm_env_timestep = wrapped_env._convert_observations(
                test_agents_observations, dones={agent: False for agent in agents}
            )

            for agent in wrapped_env.agents:
                np.testing.assert_array_equal(
                    test_agents_observations[agent],
                    dm_env_timestep[agent].observation,
                )

                assert (
                    bool(dm_env_timestep[agent].terminal) is False
                ), "Failed to set terminal."

    # Test that observations from petting zoo get converted to
    #   dm observations correctly when empty obs are returned.
    def test_convert_env_to_dm_env_0_empty_obs(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Does the wrapper have the functions we want to test
        if hasattr(wrapped_env, "_convert_observations") or hasattr(
            wrapped_env, "_convert_observation"
        ):
            #  Get agent names from env and mock out data
            agents = wrapped_env.agents
            test_agents_observations: Dict = {}

            # Parallel env_types
            dm_env_timestep = wrapped_env._convert_observations(
                test_agents_observations, dones={agent: False for agent in agents}
            )

            # We have empty OLT for all agents
            for agent in wrapped_env.agents:
                observation_spec = wrapped_env.observation_spec()
                if isinstance(observation_spec[agent].observation, tuple):
                    observation_spec_list = []
                    for obs_spec in observation_spec[agent].observation:
                        observation_spec_list.append(
                            np.zeros(
                                obs_spec.shape,
                                dtype=obs_spec.dtype,
                            )
                        )

                    for i, obs in enumerate(observation_spec_list):
                        np.testing.assert_array_equal(
                            dm_env_timestep[agent].observation[i],
                            obs,
                        )
                else:
                    observation = np.zeros(
                        observation_spec[agent].observation.shape,
                        dtype=observation_spec[agent].observation.dtype,
                    )

                    np.testing.assert_array_equal(
                        dm_env_timestep[agent].observation,
                        observation,
                    )

                np.testing.assert_array_equal(
                    dm_env_timestep[agent].legal_actions,
                    np.ones(
                        wrapped_env.action_spaces[agent].shape,
                        dtype=wrapped_env.action_spaces[agent].dtype,
                    ),
                )

    # Test that observations **with actions masked** from petting zoo get
    #   converted to dm observations correctly. This only runs
    #   if wrapper has a _convert_observations or _convert_observation functions.
    def test_convert_env_to_dm_env_2_with_action_mask(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Does the wrapper have the functions we want to test
        if hasattr(wrapped_env, "_convert_observations") or hasattr(
            wrapped_env, "_convert_observation"
        ):
            #  Get agent names from env and mock out data
            agents = wrapped_env.agents
            test_agents_observations = {}
            for agent in agents:
                observation_spec = wrapped_env.observation_spec()
                if isinstance(observation_spec[agent].observation, tuple):
                    # Using the first dim for mock observation
                    observation_shape = observation_spec[agent].observation[0].shape
                else:
                    observation_shape = observation_spec[agent].observation.shape

                # TODO If cont action space masking is implemented - Update
                test_agents_observations[agent] = {
                    "observation": np.random.rand(*observation_shape).astype(
                        np.float32
                    ),
                    "action_mask": np.random.randint(
                        2, size=wrapped_env.action_spaces[agent].shape
                    ).astype(int),
                }
            # Parallel env_types
            dm_env_timestep = wrapped_env._convert_observations(
                test_agents_observations,
                dones={agent: False for agent in agents},
            )

            for agent in wrapped_env.agents:
                np.testing.assert_array_equal(
                    test_agents_observations[agent].get("observation"),  # type: ignore # noqa: E501
                    dm_env_timestep[agent].observation,
                )
                np.testing.assert_array_equal(
                    test_agents_observations[agent].get("action_mask"),  # type: ignore # noqa: E501
                    dm_env_timestep[agent].legal_actions,
                )
                assert (
                    bool(dm_env_timestep[agent].terminal) is False
                ), "Failed to set terminal."

    # Test we can take a action and it updates observations
    def test_step_0_valid_when_env_not_done(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Seed environment since we are sampling actions.
        # We need to seed env and action space.
        random_seed = 84
        wrapped_env.seed(random_seed)
        helpers.seed_action_space(wrapped_env, random_seed)

        #  Get agent names from env
        agents = wrapped_env.agents

        timestep = wrapped_env.reset()
        if type(timestep) == tuple:
            initial_dm_env_timestep, env_extras = timestep
        else:
            initial_dm_env_timestep = timestep
        # Parallel env_types
        test_agents_actions = {
            agent: wrapped_env.action_spaces[agent].sample() for agent in agents
        }
        curr_dm_timestep = wrapped_env.step(test_agents_actions)

        for agent in wrapped_env.agents:
            assert not np.array_equal(
                initial_dm_env_timestep.observation[agent].observation,
                curr_dm_timestep.observation[agent].observation,
            ), "Failed to update observations."

        assert (
            wrapped_env._reset_next_step is False
        ), "Failed to set _reset_next_step correctly."
        assert curr_dm_timestep.reward is not None, "Failed to set rewards."
        assert (
            curr_dm_timestep.step_type is dm_env.StepType.MID
        ), "Failed to update step type."

    # Test we only step in our env once.
    def test_step_1_valid_when_env_not_done(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Seed environment since we are sampling actions.
        # We need to seed env and action space.
        random_seed = 42
        wrapped_env.seed(random_seed)
        helpers.seed_action_space(wrapped_env, random_seed)

        #  Get agent names from env
        agents = wrapped_env.agents

        # Parallel env_types
        test_agents_actions = {
            agent: wrapped_env.action_spaces[agent].sample() for agent in agents
        }
        with patch.object(wrapped_env, "step") as parallel_step:
            parallel_step.return_value = None, None, None, None
            _ = wrapped_env.step(test_agents_actions)
            parallel_step.assert_called_once_with(test_agents_actions)

    # Test if all agents are done, env is set to done
    def test_step_2_invalid_when_env_done(
        self, env_spec: EnvSpec, helpers: Helpers, monkeypatch: MonkeyPatch
    ) -> None:
        if env_spec is None:
            pytest.skip()
        wrapped_env, _ = helpers.get_wrapped_env(env_spec)

        # Seed environment since we are sampling actions.
        # We need to seed env and action space.
        random_seed = 42
        wrapped_env.seed(random_seed)
        helpers.seed_action_space(wrapped_env, random_seed)

        #  Get agent names from env
        _ = wrapped_env.reset()
        agents = wrapped_env.agents

        # Parallel env_types
        test_agents_actions = {
            agent: wrapped_env.action_spaces[agent].sample() for agent in agents
        }

        monkeypatch.setattr(wrapped_env, "env_done", helpers.mock_done)

        curr_dm_timestep = wrapped_env.step(test_agents_actions)

        helpers.assert_env_reset(wrapped_env, curr_dm_timestep, env_spec)

        assert (
            wrapped_env._reset_next_step is True
        ), "Failed to set _reset_next_step correctly."
        assert (
            curr_dm_timestep.step_type is dm_env.StepType.LAST
        ), "Failed to update step type."

    def test_wrapper_env_obs_normalisation_attrs(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        """Test observations start attribute"""

        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        agents = wrapped_env.agents

        # Frist check if the death masking is list is empty
        assert len(wrapped_env.death_masked_agents) == 0

        wrapped_step = wrapped_env.reset()
        if type(wrapped_step) == tuple:
            wrapped_step, _ = wrapped_step

        concat_id = ConcatAgentIdToObservation(wrapped_env)
        assert (
            concat_id.obs_normalisation_start_index
            > wrapped_env.obs_normalisation_start_index
        )
        assert len(concat_id.death_masked_agents) == 0

        action_spec = concat_id.action_spec()
        discrete = isinstance(action_spec[agents[0]], DiscreteArray)
        if discrete:
            concat_id_action = ConcatPrevActionToObservation(concat_id)
            assert (
                concat_id_action.obs_normalisation_start_index
                > concat_id.obs_normalisation_start_index
            )
            assert len(concat_id_action.death_masked_agents) == 0

    def test_wrapper_env_obs_stacking(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        """Test observations frame staking wrapper"""

        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        stacked_env = StackObservations(wrapped_env, num_frames=4)
        agents = wrapped_env.agents
        num_frames = 4

        # test if the reset is done correctly
        normal_step = wrapped_env.reset()
        if type(normal_step) == tuple:
            normal_step, _ = normal_step

        stacked_step = stacked_env.reset()
        if type(stacked_step) == tuple:
            stacked_step, _ = stacked_step

        for agent in agents:
            wrap_obs = normal_step.observation[agent].observation
            stacked_obs = stacked_step.observation[agent].observation

            assert wrap_obs.shape[0] * num_frames == stacked_obs.shape[0]

        # test if step is done correctly
        test_agents_actions = {
            agent: wrapped_env.action_spaces[agent].sample() for agent in agents
        }
        stacked_step = stacked_env.step(test_agents_actions)
        if type(stacked_step) == tuple:
            stacked_step, _ = stacked_step

        for agent in agents:
            wrap_obs = normal_step.observation[agent].observation
            stacked_obs = stacked_step.observation[agent].observation

            assert wrap_obs.shape[0] * num_frames == stacked_obs.shape[0]

            size = wrap_obs.shape[0]
            old_obs = stacked_obs[:size]

            for k in range(num_frames - 1):
                assert np.array_equal(old_obs, stacked_obs[k * size : (k + 1) * size])

    def test_wrapper_env_obs_stacking_and_concate(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        """Test frame staking wrapper and concatenation wrappers"""

        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        stacked_env = StackObservations(wrapped_env, num_frames=4)
        agents = wrapped_env.agents

        stacked_step = stacked_env.reset()
        if type(stacked_step) == tuple:
            stacked_step, _ = stacked_step

        concat_id = ConcatAgentIdToObservation(stacked_env)

        action_spec = concat_id.action_spec()
        discrete = isinstance(action_spec[agents[0]], DiscreteArray)
        if discrete:
            concat_id_action = ConcatPrevActionToObservation(concat_id)

            concat_id_step = concat_id.reset()
            concat_id_action_step = concat_id_action.reset()

            if type(concat_id_step) == tuple:
                concat_id_step, _ = concat_id_step

            if type(concat_id_action_step) == tuple:
                concat_id_action_step, _ = concat_id_action_step

            for agent in agents:
                stacked_shape = stacked_step.observation[agent].observation.shape[0]
                concat_id_shape = concat_id_step.observation[agent].observation.shape[0]
                concat_id_action_shape = concat_id_action_step.observation[
                    agent
                ].observation.shape[0]

                assert (stacked_shape < concat_id_shape) and (
                    concat_id_shape < concat_id_action_shape
                )

    def test_wrapper_env_obs_stacking_and_concate_error(
        self, env_spec: EnvSpec, helpers: Helpers
    ) -> None:
        """Test that a ValueError exception is raise if we call a concatenation \
                wrapper before frame stacking."""

        if env_spec is None:
            pytest.skip()

        wrapped_env, _ = helpers.get_wrapped_env(env_spec)
        env_step = wrapped_env.reset()
        if type(env_step) == tuple:
            env_step, _ = env_step

        concat_id = ConcatAgentIdToObservation(wrapped_env)
        with pytest.raises(ValueError):
            StackObservations(concat_id, num_frames=4)


'''
Author 	        : 	Srikar Uddadi
UTA ID 		    : 	1001962906
Description 	:	The below program will build a connection with Server using a socket and gives command(to print files present in directory-a) to server to process the request.
                    Also, this program will print the synchronized data which is sent back from the Server1.

Citations 	    :   1)https://docs.python.org/3/library/os.path.html
                    2)https://realpython.com/python-sockets/
                    3)https://thispointer.com/python-get-list-of-files-in-directory-with-size/
                    4)https://www.geeksforgeeks.org/python-shutil-copy2-method/
                    5)https://codereview.stackexchange.com/questions/129455/python-program-to-lock-and-unlock-files
'''
import socket
import time
import sys
import os

result = []
result2 =[]
#Creating a Socket connection to Server1
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

clientSocket.connect((socket.gethostname(),8799))

#Creating arguements to pass to Server1
if len(sys.argv)<=1:
    msg = 'None'
    clientSocket.send(msg.encode())
else:
    ind = sys.argv[1]+" "+str(sys.argv[2])
    inp2 = ind.encode()
    #sending data to server1
    clientSocket.send(inp2)

#Receiving data from Server1
buffer = clientSocket.recv(8192)
output = buffer.decode('utf-8',"strict")
#Received data from Server1
result =eval(output)

i=0
while i<len(result):
    result2 += result[i]
    i+=1

time.sleep(5)
print()
#Printing the sorted data
print("The data :")
print()
i,j=0,0
#Printing the sorted data to the client terminal
while True:
    if not result2:
        print("No Files in the Servers. Please check again")
    elif(j<len(result2)):
        ret = os.access("/Users/srikaruddadi/Desktop/Distributed_Systems/Lab2/directory_a/"+result2[j], os.W_OK)
        if(ret==False):
            print("["+str(i)+"]"+" "+result2[j]+"\t"+result2[j+1]+"\t"+str(result2[j+2])+"\t"+"<locked>")
        else:
            print("["+str(i)+"]"+" "+result2[j]+"\t"+result2[j+1]+"\t"+str(result2[j+2]))
        j+=3
        i+=1
    else:
        break

print()
#Closing the socket connection
clientSocket.close()


from bot import (
    logger,
    commands,
    discord
    )

class BasicFunctionility(commands.Cog):

    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot
        self.logger = logger

    @commands.command(name='Ping')
    async def ping(self, ctx):
        """_summary_
        Ping the bot
        """
        await ctx.reply(f'Pong! {round(self.bot.latency * 1000)}ms')
        return

    @commands.command(aliases=['h'], help='Get help')
    async def help_(self, ctx):
        """_summary_
        Get help
        """
        # Create embed
        embed = discord.Embed(
            title = "Help",
            description = f"{self.bot.user.name} command list",
            color = discord.Color.blue(),
            )

        # Add commands
        for c in self.bot.commands:
            embed.add_field(
                name = f"{c.name}",
                value = f"{c.help}"
                )
        # Send embed
        await ctx.reply(embed=embed)
        return


from model.contact import Contact
import pytest
from fixture.contact_methods import ContactHelper
import re

def test_phones_on_home_page(app):
    if app.contact.count_contacts() == 0:
        app.contact.add_new_contact(
            Contact(firstname="Gleb", middlename="Alex", lastname="Kazarkin", nickname="gkazarkin", title="AccTitle",
                    company="TestCompany", address="Yakovleva 5",
                    homephone="515232", mobilephone="89539235812", workphone="367412", fax="89539234611",
                    email="gkazarkin@test.ru", email2="gkazarkin@test.com", homepage="gkazarkin.com", bday="11", bmonth="April", byear="1987", aday="11",
                    amonth="April", ayear="1987", address2="Yakovleva 5", secondaryphone="515232", notes="Test Note"))

    contact_from_home_page = app.contact.get_contact_list()[0]
    contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
    assert contact_from_home_page.all_phones_from_home_page == merge_phones_like_on_home_page(contact_from_edit_page)

def test_phones_on_contact_view_page(app):
    if app.contact.count_contacts() == 0:
        app.contact.add_new_contact(
            Contact(firstname="Gleb", middlename="Alex", lastname="Kazarkin", nickname="gkazarkin", title="AccTitle",
                    company="TestCompany", address="Yakovleva 5",
                    homephone="515232", mobilephone="89539235812", workphone="367412", fax="89539234611",
                    email="gkazarkin@test.ru", email2="gkazarkin@test.com", homepage="gkazarkin.com", bday="11", bmonth="April", byear="1987", aday="11",
                    amonth="April", ayear="1987", address2="Yakovleva 5", secondaryphone="515232", notes="Test Note"))

    contact_from_view_page = app.contact.get_contact_from_view_page(0)
    contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)
    assert contact_from_view_page.homephone == contact_from_edit_page.homephone
    assert contact_from_view_page.workphone == contact_from_edit_page.workphone
    assert contact_from_view_page.mobilephone == contact_from_edit_page.mobilephone
    assert contact_from_view_page.secondaryphone == contact_from_edit_page.secondaryphone

'''1- Склеиваем при помощи перевода строки, 2 - Отфильтровываем пустые строки, 3 - Удаляет все лишние символы,
4 - Отфильтровываются все пусты (None), 5 - Исходный список из 4 элементов'''
def merge_phones_like_on_home_page(contact):
    return "\n".join(  #
        filter(lambda x: x != "",
                            map(lambda x: clear(x),
                                filter(lambda x: x is not None,
                                       [contact.homephone, contact.mobilephone, contact.workphone, contact.secondaryphone]))))

''' Отсекаем лишние знаки (скобки, -, пробел и т.д.), "+" не отчищаем потому что он виден на главной странице
    1 параметр = что заменять, 2 = на что заменять (на пустую строчку ""), 3 = где заменять'''
def clear(s):
    return re.sub("[() -]", "", s)


from django.core.urlresolvers import resolve
from django.test import TestCase
from load_charts.views import get_updated_stats
from django.http import HttpRequest
import ast
import re

class AlertLogicTest(TestCase):

	def test_get_stats_returns_correct_content(self):
		""" test content returned by GET on /get-stats """

		response = self.create_request('/load_charts/get-stats/', 1.0)

		# test every keys
		for k in ['load', 'alert', 'value', 'ip', 'users', 'uptime', 'date']:
			self.assertTrue(k in response.keys())

		# test that alert is either 1 (>> alert level) or 0 (>> no-alert) or -1 (>> not enough value to compute average)
		self.assertTrue(response["alert"] in [1,0,-1])

		# lower threshold to trigger an alert signal
		threshold_alert = round(float(response["value"]))
		response_alert = self.create_request('/load_charts/get-stats/', threshold_alert)
		self.assertTrue(response_alert["alert"] == 1)

		# raise thrshold to trigger a recover signal
		threshold_recover = threshold_alert + 1
		response_recover = self.create_request('/load_charts/get-stats/', threshold_recover)
		self.assertTrue(response_recover["alert"] == 0)

	def test_url_resolves_correct_function(self):
		""" test that correct view function is called """
		found = resolve('/load_charts/get-stats/')
		self.assertEqual(found.func, get_updated_stats)

	def create_request(self, url, threshold):
		""" creates request call get_updated_stats and parse answer """
		request = HttpRequest()
		request.path = url
		request.GET = {'threshold': str(threshold)}
		cleaned_response = re.split('Content-Type: text/html; charset=utf-8\r\n\r\n', str(get_updated_stats(request)))[-1]
		return eval(cleaned_response)


#! /usr/bin/env python3

import sys
import os
os.chdir(os.path.dirname(sys.argv[0]))

from mule_local.JobMule import *
from mule.exec_program import *

#
# REXI specific
#
from mule_local.rexi.REXICoefficients import *
from mule_local.rexi.trexi.TREXI import *
from mule_local.rexi.cirexi.CIREXI import *
from mule_local.rexi.brexi.BREXI import *

#
# Cleanup potentially existing benchmarks
#
exec_program('mule.benchmark.cleanup_all', catch_output=False)

from itertools import product

#
# Generate new job generation instance
#
jg = JobGeneration()

jg.compile.unit_test = "test_rexi_pde2x2"

#
# Use file-based REXI method
#
jg.runtime.rexi_method = "file"
jg.compile.quadmath = "disable"
jg.runtime.verbosity = 20

rexi_file_methods = ["trexi", "cirexi", "brexi"]

#function_name_list = ["phi0", "phi1", "phi2", "phi3", "phi4", "ups1", "ups2", "ups3", "psi1", "psi2", "psi3"]
function_name_list = ["phi0", "phi1", "phi2", "phi3", "phi4", "ups1", "ups2", "ups3"]

efloat_mode = "float"
#efloat_mode = "mpfloat"

for function_name in function_name_list:

	for rexi_file_method in rexi_file_methods:

		if rexi_file_method == "trexi":

			if function_name != "phi0":
				continue

			trexi = TREXI(efloat_mode = efloat_mode)

			M_list = [64, 128, 256]
			h_list = [0.1, 0.2, 0.5]

			for (M, h) in product(M_list, h_list):
				coeffs = trexi.setup(M=M, h=h).toFloat()
				jg.runtime.rexi_files_coefficients = [coeffs]
				jg.gen_jobscript_directory()

				if True:
					# Validate with C-implementation of T-REXI method
					jg.runtime.rexi_method = "terry"
					jg.runtime.rexi_terry_m = M
					jg.runtime.rexi_terry_h = h
					jg.gen_jobscript_directory()

					# Back to original version
					jg.runtime.rexi_method = "file"

		elif rexi_file_method == "cirexi":

			cirexi = CIREXI(efloat_mode = efloat_mode)

			# CI-REXI: Number of quadrature poles
			N_list = [256, 512]

			# CI-REXI: Value on imaginary axis to be included
			lambda_include_imag_list = [15, 20]

			# CI-REXI: Maximum value of quadrature pole
			lambda_max_real_list = [5, 10]

			for (N, lambda_include_imag, lambda_max_real) in product(N_list, lambda_include_imag_list, lambda_max_real_list):
				coeffs = cirexi.setup(function_name=function_name, N=N, lambda_include_imag=lambda_include_imag, lambda_max_real=lambda_max_real).toFloat()
				jg.runtime.rexi_files_coefficients = [coeffs]
				jg.gen_jobscript_directory()

				if True:
					# Validate with C-implementation of CI-REXI method
					jg.runtime.rexi_method = "ci"
					jg.runtime.rexi_ci_n = N
					jg.runtime.rexi_ci_max_real = lambda_max_real
					jg.runtime.rexi_ci_max_imag = lambda_include_imag
					jg.gen_jobscript_directory()

					# Back to original version
					jg.runtime.rexi_method = "file"

		elif rexi_file_method == "brexi":

			if function_name != "phi0":
				continue

			brexi = BREXI(efloat_mode = efloat_mode)

			# CI-REXI: Number of quadrature poles
			#N_list = [8, 10, 12]
			N_list = [8, 10]

			quadrature_method_list = ["gauss", "radau", "chebyshev"]

			for (N, quadrature_method) in product(N_list, quadrature_method_list):
				coeffs = brexi.setup(N=N, quadrature_method=quadrature_method).toFloat()
				jg.runtime.rexi_files_coefficients = [coeffs]
				jg.gen_jobscript_directory()
			pass

		else:
			raise Exception("Unknown method "+rexi_file_methods)

exitcode = exec_program('mule.benchmark.jobs_run_directly', catch_output=False)
if exitcode != 0:
	sys.exit(exitcode)

print("Benchmarks successfully finished")

exec_program('mule.benchmark.cleanup_all', catch_output=False)


#  content of  test_sample.py
import pytest
def func(x):
    return x +1

def test_answer(cmdopt):
   if cmdopt == "type1":
       print("first1")
   elif cmdopt == "type2":
       print("second")
   assert 0

if __name__ == "__main__":
    pytest.main(["-s", "test_case1.py"])


class  base:
      __slots__ = ['w','b']
      bshuxing='bshuxing'
      '''当前类为工具类：主要为了打印str 方法，输出做一些内省的工具'''

      def __str__(self):

            return  '<instance of  %s , address %s , \n %s>' %(self.__class__.__name__,id(self),self.__attrnames())

      def __attrnames(self):
            '''
            这里可以做一些内省的工具：比如dict打印类实例的属性，或者利用dir(o )打印内置的一些方法和值
            :return:
            '''
            result=''

            for attr in sorted(self.__dict__):
                  result+='\t name  %s=%s  \n' %(attr,self.__dict__[attr])
            return  result

class super():

      def __init__(self):
            self.data1='dat1'

class  Te(super,base):
      def __init__(self):
         super.__init__(self)
         self.data2='date2'
         self.date3='date3'

if __name__ == '__main__':

      b=base()
      print(b)
      c=Te()
      print(c)


"""Given an array of strings, group anagrams together.

Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Idea: Categorize anagrams by sorted string.
Use a dict of key = tuple of sorted string, value = list of strings, that when sorted, equal the key.

Time: O(nklogk)
Space: O(nk)

n = length of string list
k = max length of string in string list
"""

def group_anagrams(strings):
    result = collections.defaultdict(list)
    for s in strings:
        # have to use tuple because lists are not hashable (tuples are immutable, whereas lists are mutable)
        result[tuple(sorted(s))].append(s)
    return list(result.values())

"""Another way, where the keys of the dict are the character counts of the strings. This cancels the need for sorting."""

def group_anagrams(strings):
    result = collections.defaultdict(list)
    for s in strings:
        count = [0] * 26  # assuming alphabet of input is only 26 chars (a-z)
        for c in s:
            # create key
            index = ord(c) - ord('a')
            count[index] += 1
        # add to dict
        result[tuple(count)].append(s)

    return list(result.values())


import sys
sys.stdin = open("바이러스.txt")

def dfs(x):
    visited[x] = 1

    for y in range(1, N+1):
        if visited[y] == 1:
            continue
        if nxn[x][y] == 1:
            dfs(y)

N = int(input())
M = int(input())

nxn = [[0 for _ in range(N+1)] for _ in range(N+1)]
visited = [0 for _ in range(N+1)]
for z in range(M):
    a, b = map(int, input().split())
    nxn[a][b] = 1
    nxn[b][a] = 1

dfs(1)
ans = visited.count(1)

print(ans-1)

알고리즘문제/바이러스.py


#!/bin/python3
import os
import random
import re
import sys
def simpleArraySum(ar):
    sum = 0
    for i in ar:
        sum+=i

    return sum

if __name__ == '__main__':
    print("Enter number of elements")
    ar_count = int(input())

    print("Enter the elements")
    ar = list(map(int, input().rstrip().split()))

    result = simpleArraySum(ar)

    print('Total sum is:'+str(result) + '\n')


"""
# Date: 09/07/2020
# Created by Raihan Sayeed Khan
# book title: The Complete Works of William Shakespeare
# Author:  William Shakespeare
# link: http://www.gutenberg.org/ebooks/100
# wordcloud helpful resources:
    - https://www.datacamp.com/community/tutorials/wordcloud-python
"""

# import
import codecs # to open utf-8 file
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

path = r'.\100-0.txt' # path to file
# reading file
with codecs.open(path, encoding='utf-8') as f:
    text = f.readlines()

text = [x for x in text if x.strip()] # removing whitespace elements
text = text[62:] # deleting everything before the content
text = [y for y in text if not y.strip().isnumeric()] # getting rid of numbers
text = ''.join(text) # joining all the elements to a single string

# words 'not' to include
stpwrds = ['i', 'I', 'my', 'you', 'You', 'thee', 'Thee', 'he', 'He', 'she',
           'She', 'us', 'one', 'mine', 'thy', 'thou', 'whose', 'tis','upon', 'thus','though', 'll']

article = ['a', 'A', 'an', 'An', 'the', 'The']

from_file = ['_Exit'] # commands inside the file

misc= ['sir', 'Sir', 'madam', 'Madam', 'ay', 'Ay', 'Yea','nay', 'Nay', 'mylord',
       'th', 'QUEEN', 'DUKE', 'KING', 'PRINCE', 'father', 'mother','son', 'daughter','brother', 'sister','man',
       'men', 'woman', 'women', 'will', 'll', 'ti', 'yet', 'much', 'hath', 'Enter', 'now', 'eye']

names = ['FALSTAFF', 'OTHELLO', 'CLEOPATRA', 'ANTONIO', 'ANTONY', 'HAMLET', 'BRUTUS', 'IAGO', 'ROMEO', 'CAESAR', 'ROSALIND', 'KINGHENRY', 'EMILIA', 'PETRUCHIO', 'KINGRICHARD',
         'DESDEMONA', 'HELENA', 'BEROWNE', 'TIMON', 'PANDARUS', 'CORIOLANUS', 'TROLIUS', 'MACBETH', 'OLIVIA'
         'JULIET','POMPEY', 'LUCIUS', 'PALAMON', 'CLAUDIO', 'CELIA', 'THESEUS', 'CRESSIDA', 'BENEDICK', 'CASSIUS'
         'SEBASTIAN', 'SIRTOBY', 'PORTIA', 'LEONTES', 'TROILUS', 'TITUS', 'LEONATO', 'ARCITE', 'Isay',
         'MENENIUS', 'VIOLA', 'HORATIO', 'DONPEDRO', 'ANGELO', 'OLIVIA', 'CASSIO', 'BEATRICE', 'BERTRAM', 'VALENTINE',
         'PROTEUS', 'ISABELLA', 'PERICLES', 'TRANIO']

places = ['GLOUCESTER', 'WARWICK', 'BUCKINGHAM', 'ORLANDO', 'SUFFOLK', 'SICINIUS']

# joining all the lists along with default STOPWORDS
stopwords = set(list(STOPWORDS)+stpwrds+misc+from_file+names+places)
# set command make sures only unique elements are used

# generating wordcloud
wc = WordCloud(stopwords=stopwords, background_color="white", max_font_size=50,
               min_font_size=10, max_words=100, random_state = 1, colormap = 'viridis')
wc.generate(text)

# plotting wordcloud
fig1 = plt.figure(figsize = (6, 4))
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()

# saving the image
#wc.to_file("./wordcloud_Shakespeare.png") # resolution is not good
fig1.savefig('wordcloud_Shakespeare.png', dpi = 600, bbox_inches='tight')


import boto3

ec2 = boto3.resource('ec2',region_name="us-west-2")
subnet_id = "subnet-02353173950f10872"
ami_id = "ami-09d50d5363fe58c51"

instance = ec2.create_instances(
    ImageId=ami_id,
    InstanceType='t2.micro',
    KeyName="python_keypair",
    MaxCount=1,
    MinCount=1,
    NetworkInterfaces=[
        {
            'SubnetId': subnet_id,
            'DeviceIndex': 0,
            'AssociatePublicIpAddress': True,
        }
    ],
    TagSpecifications=[
        {
        'ResourceType': 'instance',
        'Tags': [
            {
                'Key': 'Name',
                'Value': 'harsha_ec2_2'
            },
        ]
    }]
)
instance_id = instance[0].instance_id
print(f"EC2 instance created successfully with ID: {instance_id}")
print("END")


def table2str(table):
    rows = [[str(cell) for cell in row] for row in table]
    widths = [max(len(row[c]) for row in rows) for c in range(len(rows[0]))]
    widths = [(w // 8) * 8 for w in widths]
    rows = [[c.ljust(w) for c, w in zip(row, widths)] for row in rows]
    return "\n".join("\t".join(row) for row in rows) + "\n"

def is_increasing_with_delta(it, delta):
    it = iter(it)
    try:
        curr = next(it)
        while True:
            nxt = next(it)
            if nxt - curr != delta:
                return False
            curr = nxt
    except StopIteration:
        return True
    except TypeError:
        return False

def list2str(it):
    elements = list(it)
    if is_increasing_with_delta(elements, 1):
        if len(elements) < 3:
            return ", ".join(map(str, elements))
        return f"{elements[0]}..{elements[-1]}"
    ranges = []
    for cur, prev in zip(elements, [None] + elements):
        if any(not isinstance(x, int) for x in (cur, prev)) or cur - prev != 1:
            ranges.append([])
        ranges[-1].append(cur)
    return ", ".join(list2str(rng) for rng in ranges)

def groups_table_to_tsv(groups):
    has_deps = any(len(deps) for (_, deps, _) in groups.values())
    offset = (isinstance(groups[0].points, int) and groups[0].points > 0)
    offset = int(offset or groups[0].points is None)
    groups_table, total_points, total_tests = [], 0, 0
    for group, (points, deps, tests) in sorted(groups.items()):
        policy = [
            "no points are scored for passing this group",
            "points are scored if all tests are passed",
            "all tests are independently scored",
        ][bool(points) + (points == "sum")]
        points = sum(t.points for t in tests) if points == "sum" else points
        row = [group + offset, points, len(tests)]
        row += [list2str(range(total_tests + 1, total_tests + len(tests) + 1))]
        row += has_deps * [list2str(map(lambda g: g + offset, deps))]
        row += [policy]
        groups_table.append(row)
        if points is not None:
            total_points += points
        total_tests += len(tests)
    header = ["group", "points", "tests", "range"]
    header += ["depends on"] * has_deps + ["score policy"]
    total = ["total:", total_points, total_tests] + [""] * (2 + has_deps)
    return table2str([header] + groups_table + [total])


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

"""
 ██████╗ ███████╗███╗   ██╗███████╗████████╗██╗ ██████╗     ██████╗██╗████████╗██╗   ██╗
██╔════╝ ██╔════╝████╗  ██║██╔════╝╚══██╔══╝██║██╔════╝    ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝
██║  ███╗█████╗  ██╔██╗ ██║█████╗     ██║   ██║██║         ██║     ██║   ██║    ╚████╔╝
██║   ██║██╔══╝  ██║╚██╗██║██╔══╝     ██║   ██║██║         ██║     ██║   ██║     ╚██╔╝
╚██████╔╝███████╗██║ ╚████║███████╗   ██║   ██║╚██████╗    ╚██████╗██║   ██║      ██║
 ╚═════╝ ╚══════╝╚═╝  ╚═══╝╚══════╝   ╚═╝   ╚═╝ ╚═════╝     ╚═════╝╚═╝   ╚═╝      ╚═╝

Functions used for evaluation of city populations for algorithm.

By: Andres Rico - aricom@mit.edu
MIT Media Lab - City Science Group
                                                                                """

mutation_prob = .9 #Must be between 0 - 1
import numpy as np
from progressbar import printProgressBar #Import progress bar function.

def look_up_table(grid_size):
    source_i_2d=[[i]*grid_size for i in range(grid_size)]
    source_i=[j for sub in source_i_2d for j in sub]
    source_j=list(range(grid_size))*grid_size

    manhattan_distmat=np.array([[np.abs(source_i[ind]-i)+np.abs(source_j[ind]-j) for i in range(grid_size) for j in range(grid_size)] for ind in range(len(source_i))])

    return manhattan_distmat

#Function takes as input a vector with a city design and evaluates it according to the weight vector set on objevtive fucntion.
def evaluate_park(evcity):
    total_evaluation = 0
    wheights = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) #Weights used by function to evaluate. Places more interest in high numbers.
    unique, counts = np.unique(evcity,return_index=False, return_inverse=False, return_counts=True, axis=None)
    dictionary = dict(zip(unique, counts))
    for type in range(1,10):
        #print(dictionary[1])
        if type in evcity:
            total_evaluation = total_evaluation + (dictionary[type] * wheights[type - 1]) #Objective fucntion. This function will change as real city metrics are added to algorithm.
    return total_evaluation #This function should try to give an output of a matrix containing all nines or close to all nines.

def evaluate_balanced(evcity):
    total_evaluation = 0
    wheights = np.array([0, 0, 0, 0, 0, 10, 10, 10, 10]) #Weights used by function to evaluate. Places more interest in high numbers.
    unique, counts = np.unique(evcity,return_index=False, return_inverse=False, return_counts=True, axis=None)
    dictionary = dict(zip(unique, counts))
    for type in range(1,10):
        #print(dictionary[1])
        if type in evcity:
            total_evaluation = total_evaluation + (dictionary[type] * wheights[type - 1]) #Objective fucntion. This function will change as real city metrics are added to algorithm.
    return total_evaluation

def evaluate_simplethree(evcity, look_up):
    unique, counts = np.unique(evcity,return_index=False, return_inverse=False, return_counts=True, axis=None)
    if counts.size < 3:
        evaluation = 0

    elif counts[0] < 3 or counts[1] < 4 or counts[2] < 4:
        evaluation = 0

    else:
        evaluation = 1000
        homes = np.where(evcity == 3)
        offices = np.where(evcity == 1)
        parks = np.where(evcity == 2)

        for home in range(int(homes[0].shape[0])):
            for office in range(offices[0].shape[0]):
                evaluation = evaluation - look_up[homes[0][home], offices[0][office]]
            for park in range(parks[0].shape[0]):
                evaluation = evaluation - look_up[homes[0][home], parks[0][park]]

        for park in range(int(parks[0].shape[0])):
            for office in range(offices[0].shape[0]):
                evaluation = evaluation - look_up[parks[0][park], offices[0][office]]

    return evaluation

"""
else:
    evaluation = 1000 - abs(counts[0]- counts[1]) - abs(counts[0]- counts[2]) - abs(counts[1]- counts[2])
"""

def evaluate_cities(city_to_ev, population, look_up ): #Complete evaluation fucntion for looping through every individual of a population.
    printProgressBar(0, population, prefix = 'Population Evaluation Progress:', suffix = 'Complete', length = 50)
    ev_vector = np.arange(population)
    for pop in range(0, population):
        ev_vector[pop] = evaluate_simplethree(city_to_ev[pop,:], look_up) #Change line to change to desired weight function.
        printProgressBar(pop + 1, population, prefix = 'Population Evaluation Progress:', suffix = 'Complete', length = 50)
    return ev_vector #Returns evaluation vector.


from pathlib import Path

from langchain.prompts import (
    ChatPromptTemplate,
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate,
)

def get_prompt_template(
    user_prompt_template: str, system_prompt_template: str, input_vars: list[str]
) -> ChatPromptTemplate:
    if system_prompt_template is None:
        with open(Path(__file__).parent / "prompts" / "system.prompt") as f:
            system_template = f.read().strip()
    else:
        system_template = system_prompt_template

    if user_prompt_template is None:
        with open(Path(__file__).parent / "prompts" / "user.prompt") as f:
            human_template = f.read().strip()
    else:
        human_template = user_prompt_template

    return ChatPromptTemplate(
        messages=[
            SystemMessagePromptTemplate.from_template(system_template),
            HumanMessagePromptTemplate.from_template(human_template),
        ],
        input_variables=input_vars,
    )

def get_human_template() -> str:
    with open(Path(__file__).parent / "prompts" / "user.prompt") as f:
        return f.read().strip()

def get_system_template() -> str:
    with open(Path(__file__).parent / "prompts" / "system.prompt") as f:
        return f.read().strip()


from __future__ import print_function
import sys, readline
from os import environ

class InvalidCommandException(Exception):
    pass

class Autocomplete(object):
    def __init__(self, options):
        self.options = sorted(options)
    def complete(self, text, state):
        if state == 0:
            if not text:
                self.matches = self.options[:]
            else:
                self.matches = [s for s in self.options if s and s.startswith(text)]
        try:
            return self.matches[state]
        except IndexError:
            return None
    def display_matches(self, subsitution, matches, longest_match_length):
        line_buffer = readline.get_line_buffer()
        columns = environ.get("COLUMNS", 80)
        print()
        tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}"
        buffer = ""
        for match in matches:
            match = tpl.format(match[len(subsitution):])
            if len(buffer + match) > columns:
                print(buffer)
                buffer = ""
            buffer += match
        if buffer:
            print(buffer)
        print("> ",end="")
        sys.stdout.flush()

class ExampleHandler(object):
    def __init__(self):
        self.commands = {
            'help': 'view help menu',
            'exit': 'quits the shell'
        }
    def handle(self, cmd):
        if cmd == 'help':
            print('\n'.join(['{}: {}'.format(k, v) for k, v in self.commands.items()]))
        elif cmd == "exit":
            return "exit"
        else:
            raise InvalidCommandException("Command not found: {}".format(cmd))

def start_shell(cmd_handler):
    commands = cmd_handler.commands.keys()
    completer = Autocomplete(list(set(commands)))
    readline.set_completer_delims('\t')
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    readline.set_completion_display_matches_hook(completer.display_matches)
    while True:
        cmd = input("> ")
        try:
            res = cmd_handler.handle(cmd)
        except Exception as e:
            print("Error: "+str(e))
            res = None
        if res == "exit":
            break


import telebot
import random
import numpy as np
from backend import bag_of_words, model, words, labels, data

bot = telebot.TeleBot('5937779519:AAHQpSMYurGkcjw4-M_LPeJS6lDdgfsTBIE')

@bot.message_handler(func=lambda message: True)
def handle_message(message):
   # Procesar el mensaje y determinar la intención del usuario
    message_text = message.text  # obtenemos el texto del mensaje
    # creamos la representacion numerica del mensaje
    message_representation = bag_of_words(message_text, words)
    # hacemos la prediccion con el modelo entrenado
    result = model.predict([message_representation])
    # obtenemos el indice de la intencion con mayor probabilidad
    intent_index = np.argmax(result)
    if intent_index != None:
        intent = labels[intent_index]  # obtenemos la intencion correspondiente
        # Seleccionar una respuesta apropiada
        for intents in data['intents']:
            if intents['tag'] == intent:
                responses = intents['responses']
        # Seleccionar una respuesta al azar
        response = random.choice(responses)
    else:
        response = "Lo siento, no entendí tu mensaje. ¿Podrías aclararlo?"
    # Enviar respuesta al usuario
    bot.send_message(chat_id=message.chat.id, text=response)

bot.polling()


from time import sleep
import os
from selenium import webdriver

link = "http://suninjuly.github.io/file_input.html"

browser = webdriver.Chrome()
browser.get(link)
sleep(1)

try:
    form = browser.find_element_by_tag_name('form')

    form.find_element_by_name('firstname').send_keys('First Name')
    form.find_element_by_name('lastname').send_keys('Last Name')
    form.find_element_by_name('email').send_keys('email@email.com')

    current_dir = os.path.abspath(os.path.dirname(__file__))  # получаем путь к директории текущего исполняемого файла
    file_path = os.path.join(current_dir, 'file.txt')  # добавляем к этому пути имя файла

    form.find_element_by_id('file').send_keys(file_path)

    sleep(1)

    button = form.find_element_by_tag_name('button.btn')
    button.click()

# 28.88258850920861

finally:
    sleep(20)
    browser.quit()


import os
from setuptools import setup, find_packages

# Read long description
with open('README.md', 'r') as fh:
    long_description = fh.read()

# only specify install_requires if not in RTD environment
if os.getenv("READTHEDOCS") == "True":
    INSTALL_REQUIRES = []
#else:
with open("requirements.txt") as f:
    INSTALL_REQUIRES = [line.strip() for line in f.readlines()]

setup(
    name= 'bikeability',
    version= '0.0.1',
    description= 'An automated bikeabililty assessment tool.',
    long_description= long_description,
    long_description_content_type= 'text/markdown',
    classifiers = [
    'Intended Audience :: Researchers/ SCience',
    'Operating System :: OS Independent',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 3.7'],
    url='https://github.com/DchemistRae/Bikeability_calculator',
    author='Raymond Asimhi',
    author_email='rasimhi@gmx.de',
    packages= ['bikeability'],
    install_requires='INSTALL_REQUIRES',
)


from __future__ import absolute_import, division, print_function
from cctbx.xray.targets import r1
from scitbx.array_family import flex
from libtbx.test_utils import approx_equal
from six.moves import range
from six.moves import zip

def exercise(mt, n_refl, log):
  f_obs = mt.random_double(size=n_refl)
  f_calc = flex.complex_double(
    mt.random_double(size=f_obs.size()),
    mt.random_double(size=f_obs.size()))
  f_calc_abs = flex.abs(f_calc)
  trg = r1.target(f_obs=f_obs, f_calc=f_calc)
  def check_f_calc_abs_derivs():
    eps = 1e-6
    g_fin = flex.double()
    c_fin = flex.double()
    for ih in range(f_calc_abs.size()):
      fs = []
      gs = []
      c_orig = f_calc_abs[ih]
      for signed_eps in [eps, -eps]:
        f_calc_abs[ih] = c_orig + signed_eps
        trg_eps = r1.target(f_obs=f_obs, f_calc_abs=f_calc_abs)
        fs.append(trg_eps.t)
        gs.append(trg_eps.g[ih])
      g_fin.append((fs[0]-fs[1])/(2*eps))
      c_fin.append((gs[0]-gs[1])/(2*eps))
      f_calc_abs[ih] = c_orig
    print("g fin:", numstr(g_fin), file=log)
    print("  ana:", numstr(trg.g), file=log)
    assert approx_equal(trg.g, g_fin)
    print("c fin:", numstr(c_fin), file=log)
    print("  ana:", numstr(trg.c), file=log)
    assert approx_equal(trg.c, c_fin)
  def check_f_calc_derivs():
    eps = 1e-6
    g_fin = flex.complex_double()
    c_fin = flex.vec3_double()
    for ih in range(f_calc.size()):
      c_orig = f_calc[ih]
      g_fin_ab = []
      c_fin_ab = []
      for iab in [0,1]:
        fs = []
        gs = []
        for signed_eps in [eps, -eps]:
          if (iab == 0):
            f_calc[ih] = complex(c_orig.real + signed_eps, c_orig.imag)
          else:
            f_calc[ih] = complex(c_orig.real, c_orig.imag + signed_eps)
          trg_eps = r1.target(f_obs=f_obs, f_calc=f_calc)
          fs.append(trg_eps.t)
          gs.append(trg_eps.f_calc_gradients[ih])
        g_fin_ab.append((fs[0]-fs[1])/(2*eps))
        c_fin_ab.append((gs[0]-gs[1])/(2*eps))
      g_fin.append(complex(*g_fin_ab))
      assert approx_equal(c_fin_ab[0].imag, c_fin_ab[1].real)
      c_fin.append((c_fin_ab[0].real, c_fin_ab[1].imag, c_fin_ab[0].imag))
      f_calc[ih] = c_orig
    for pn,f,a in zip(
          g_fin.part_names(), g_fin.parts(), trg.f_calc_gradients.parts()):
      print("g fin %s:" % pn, numstr(f), file=log)
      print("  ana %s:" % pn, numstr(a), file=log)
    assert approx_equal(trg.f_calc_gradients, g_fin)
    for pn,f,a in zip(
          ["aa", "bb", "ab"], c_fin.parts(), trg.f_calc_hessians.parts()):
      print("c fin %s:" % pn, numstr(f), file=log)
      print("  ana %s:" % pn, numstr(a), file=log)
    assert approx_equal(trg.f_calc_hessians, c_fin)
  check_f_calc_abs_derivs()
  check_f_calc_derivs()
  #
  f_calc[0] = 0j
  f_calc_abs = flex.abs(f_calc)
  trg = r1.target(f_obs=f_obs, f_calc=f_calc)
  assert trg.gradients_work()[0] == 0j
  assert trg.hessians_work()[0] == (0,0,0)

def run(args):
  assert len(args) < 3
  arg_vals = [int(arg) for arg in args]
  arg_vals = arg_vals + [3, 2][len(arg_vals):]
  n_refl, n_trials = arg_vals
  assert n_refl > 0
  assert n_trials > 0
  if (len(args) == 0):
    from libtbx.utils import null_out
    log = null_out()
  else:
    import sys
    log = sys.stdout
  mt = flex.mersenne_twister(seed=0)
  for i_trial in range(n_trials):
    exercise(mt, n_refl, log)
  print("OK")

if (__name__ == "__main__"):
  import sys
  run(args=sys.argv[1:])


from scraper.scrape_functions import get_historicals_by_gw
from scraper.scraper_constants import seasons, team_tables, stored_path
import numpy as np
import os

import logging

logging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')

logging.info("Scraping Player Data")
gameweeklist = list(np.arange(1, 39))
ffs_tables = [f'{x}_' + str(season) for season in seasons for x in team_tables]
ffs_df_dict = {}
for season in seasons:
    for feature in team_tables:
        df = get_historicals_by_gw(str(season), gameweeklist, feature)
        ffs_df_dict[f"{feature}_{season}"] = df
        print(f"Scraped {feature, season}")

for table in ffs_tables:
    output_file_path = os.path.join(stored_path, f"{table}")
    ffs_df_dict[table].to_csv(output_file_path)


def _authenticate(self, params, headers):
        """
        Method that simply adjusts authentication credentials for the
        request.
        `params` is the querystring of the request.
        `headers` is the header of the request.

        If auth instance is not provided to this class, this method simply
        returns without doing anything.
        """
        if self.authentication:
            user = self.authentication.get_user()
            params.update({'auth': user.firebase_auth_token})
            headers.update(self.authentication.authenticator.HEADERS)


l = str(input('Enter list\n'))
l = list(map(int,l.split(" ")))

lPositive = []

for i in range(len(l)):
    if l[i] > 0:
        lPositive.append(l[i])

#Printing positive numbers
print('List with positive numbers:\n')
print(list(lPositive))


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

import random

def bubble(alist):
    for i in range(len(alist) - 1):
        exchange = False
        for j in range(len(alist) - 1 - i):
            if alist[j] > alist[j + 1]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
                exchange = True
        if not exchange:
            break

lst = [random.randint(1, 100) for i in range(10)]
print('Before sorting:')
print(lst)
bubble(lst)
print('After sorting:')
print(lst)


# Exercício Python 84:
'''Faça um programa que leia nome e peso de várias pessoas,
guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.'''

pessoas = []
dado = []
maior = menor = 0
while True:
    dado.append(str(input('Nome: ')))
    dado.append(float(input('Peso kg: ')))
    if len(pessoas) == 0:
        maior = menor = dado[1]
    else:
        if dado[1] > maior:
            maior = dado[1]
        if dado[1] < menor:
            menor = dado[1]
    pessoas.append(dado[:])
    dado.clear()
    resposta = str(input('Continuar? [S/N] '))
    if resposta in 'Nn':
        break
print(f'Foram cadastradas {len(pessoas)} pessoas.')
print(f'O maior peso foi de {maior}kg. Correspondente a ', end='')
for p in pessoas:
    if p[1] == maior:
        print(f'[{p[0]}] ', end='')
print()
print(f'O menor peso foi de {menor}kg. Correspondente a ', end='')
for p in pessoas:
    if p[1] == menor:
        print(f'[{p[0]}] ', end='')
print()


# Guess a number game

import random

def start_the_game():
    print("Game started")
    print("Please think of some number from 0 to 100 and I'll try to guess it")
    print(
        "Print one of the signs to help me guess a number: > (bigger than user's) < (smaller than user's) = (equals) ")
    help_messages = ["Help me please!\n",
                     "I beg you, give me the number\n",
                     "I'm nothing, I can't win\n",
                     "Who made me so emotional? Please help!\n"]
    default_min_number = 0
    default_max_number = 100
    current_min_number = default_min_number
    current_max_number = default_max_number
    comp_guess = random.randint(current_min_number, current_max_number)
    while True:
        try:
            previous_guess = comp_guess
            print(f"I guess it is {comp_guess}")
            user_input = input("Am I right?\n")
            if user_input == "=":
                print("At last...")
                break
            elif user_input == ">":
                current_max_number = comp_guess
            elif user_input == "<":
                current_min_number = comp_guess
            comp_guess = int((current_max_number + current_min_number) / 2)
            if comp_guess == previous_guess:
                print("You are cheating, I won't play with you...")
                break
            print(help_messages[random.randint(0, 3)])
        except Exception:
            print("You are cheating, I won't play with you...")
            break

def print_welcome():
    print("Hello my dear friend! Welcome to the Game!")
    print("Wanna play?")
    print("This time it's my turn to guess a number")
    ready_to_play = input("Are you ready to play?\n")
    ready_to_play = ready_to_play.lower()
    if ready_to_play.__contains__("yes") or ready_to_play.__contains__("да"):
        start_the_game()


__all__ = ['ProdSetting']

from pyasm.common import Container, TacticException
from pyasm.search import *
from pyasm.biz import Project

class ProdSetting(SObject):
    '''Defines all of the settings for a given production'''

    SEARCH_TYPE = "config/prod_setting"

    # FIXME: what is this for?
    def get_app_tabs(self):
        '''This controls what tabs are visible'''
        return ["3D Asset", "Checkin", "Sets", "Anim Loader", "Anim Checkin", "Layer Loader", "Layer Checkin", "Shot"]

    def _get_container_key(cls, key, search_type=None):
        if search_type:
            key = "ProdSetting:%s:%s" % (key, search_type)
        else:
            key = "ProdSetting:%s" % key
        return key

    _get_container_key = classmethod(_get_container_key)

    def get_value_by_key(cls, key, search_type=None):
        '''
        container_key = cls._get_container_key(key,search_type)
        value = Container.get(container_key)
        if value:
            return value
        '''
        if Project.get_project_name() in ['sthpw', 'admin']:
            return ''

        prod_setting = cls.get_by_key(key, search_type)
        value = ''
        if prod_setting:
            value = prod_setting.get_value("value")

        return value
    get_value_by_key = classmethod(get_value_by_key)

    def get_by_key(cls, key, search_type=None):
        from pyasm.security import Site
        site = Site.get_site()
        Site.set_site( Site.get_first_site() )

        try:

            project = Project.get_project_code()
            dict_key = '%s:%s' %(key, search_type)

            search = Search(cls.SEARCH_TYPE, project_code=project)
            search.add_filter("key", key)
            if search_type:
                search.add_filter("search_type", search_type)

            if Project.get_project_name() in ['admin', 'sthpw']:
                return None
            prod_setting = ProdSetting.get_by_search(search, dict_key)
        finally:
            Site.pop_site()

        return prod_setting

    get_by_key = classmethod(get_by_key)

    def get_seq_by_key(cls, key, search_type=None):
        seq = []
        value = cls.get_value_by_key(key, search_type)
        if value:
            seq = value.split("|")
        return seq
    get_seq_by_key = classmethod(get_seq_by_key)

    def add_value_by_key(cls, key, value, search_type=None):
        seq = cls.get_seq_by_key(key, search_type)
        if not seq:
            seq = []
        elif value in seq:
            return

        seq.append(value)

        setting = cls.get_by_key(key, search_type)
        if not setting:
            return

        setting.set_value( "value", "|".join(seq) )
        setting.commit()

        container_key = cls._get_container_key(key,search_type)
        value = Container.put(container_key, None)

    add_value_by_key = classmethod(add_value_by_key)

    def get_map_by_key(cls, key, search_type=None):
        ''' this is more like an ordered map'''
        seq = []
        map = []
        value = cls.get_value_by_key(key, search_type)
        if value:
            seq = value.split("|")
        for item in seq:
            try:
                key, value = item.split(':')
                map.append((key, value))
            except Exception as e:
                raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
        return map
    get_map_by_key = classmethod(get_map_by_key)

    def get_dict_by_key(cls, key, search_type=None):
        ''' this is to retrieve an unordered dict'''
        seq = []
        dict = {}
        value = cls.get_value_by_key(key, search_type)
        if value:
            seq = value.split("|")
        for item in seq:
            try:
                key, value = item.split(':')
                dict[key] = value
            except Exception as e:
                raise TacticException('ProdSettings should be formated like <key1>:<value1>|<key2>:<value2>|...')
        return dict
    get_dict_by_key = classmethod(get_dict_by_key)

    def create(key, value, type, description='', search_type=''):
        '''create a ProdSetting'''

        if Project.get_project_name() in ['admin', 'sthpw']:
            return None

        ProdSetting.clear_cache()
        setting = ProdSetting.get_by_key(key, search_type)
        if not setting:
            setting= SObjectFactory.create( ProdSetting.SEARCH_TYPE )
            setting.set_value("key", key)
            setting.set_value("value", value)

            setting.set_value("type", type)
            if description:
                setting.set_value("description", description)
            if search_type:
                setting.set_value("search_type", search_type)
        else:
            setting.set_value("value", value)

        setting.commit()
        return setting
    create = staticmethod(create)


# Python Object-Oriented Programming
# https://www.youtube.com/playlist?list=PL-osiE80TeTsqhIuOqKhwlXsIBIdSeYtc

class Employee():

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'

    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday() ==6:  # 使用weekday method, 如果是5或者6就是周末，就不是workday
            return False
        return True

class Developer(Employee):

    def __init__(self, first, last, pay, prog_lang):
        super(Developer, self).__init__(first, last, pay)
        self.prog_lang = prog_lang

class Manager(Employee):

    def __init__(self, first, last, pay, employees=None):
        super(Manager, self).__init__(first, last, pay)
        if employees is None:
            self.employees = []
        else:
            self.employees = employees

    def add_emp(self, emp):
        if emp not in self.employees:
            self.employees.append(emp)

    def remove_emp(self, emp):
        if emp in self.employees:
            self.employees.remove(emp)

    def print_emp(self):
        for emp in self.employees:
            print(emp.fullname())

dev_1 = Developer('Co', 'Sch', 80000, 'Python')
dev_2= Developer('C', 'S', 30000, 'Java')

# # print(dev_1.prog_lang)
# # print(dev_1.email)
#
# mrg_1 = Manager('Te', 'Us', 90000, [dev_1, dev_2])
# mrg_1.print_emp()

emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)

import datetime  # 导入Python中日期模块
my_data = datetime.date(2018, 2, 26)  # 传入一个日期，这个日期是星期一是workday

print(dev_1.is_workday(my_data))
# print(emp_2.fullname())
#
# print(emp_1)
# print(emp_2)
#
# print(emp_1.email)
# print(emp_2.email)

# 以上输出结果：
# <__main__.Employee object at 0x00000202B0497B00>
# <__main__.Employee object at 0x00000202B0497B38>
# Corey.Schafer@company.com
# Test.User@company.com


s1=input("Enter s1: ")
s2=input("Enter s2: ")
chars={}
for i in s1:
    if i in chars:
        chars[i]+=1
    else:
        chars[i]=1
res=1
for i in chars:
    cnt=0
    for j in s2:
        if j==i:
            cnt+=1
    if cnt<chars[i]:
        res=0
        break
if res==1:
    print("Strings are balanced!")
else:
    print("Strings are not balanced!")


import bottle
from LGSStatus import app, config, db, twitter, watch

@app.post("/append/<type>")
def insert(type):
	security_key = bottle.request.POST.key
	value = bottle.request.POST.value

	if security_key not in config["keys"]:
		bottle.abort(401, "Security token not given")

	if type not in config["types"]:
		bottle.abort(400, "Invalid type")

	if not value:
		bottle.abort(400, "Missing value parameter")

	db.set_value_of_type(type, value)

	if type == "door":
		twitter.tweet_about_door_state_if_changed()
		watch.set_status_to_working()

	return type + ":" + value


import sys
import numpy as np
import torch
from pprint import pprint
sys.path.append('../')
import affinity_approximation as losses

def numpy_naive(vs, ys):
    frobenius_np = np.mean(
        np.array([np.linalg.norm(vs[b].dot(vs[b].T) -
                                 ys[b].dot(ys[b].T))**2
                  for b in np.arange(vs.shape[0])]))
    return frobenius_np

if __name__ == "__main__":
    batch_size = 1
    num_tfs = 100
    embedding_depth = 10
    n_sources = 2
    vs_np = np.random.rand(batch_size, num_tfs, embedding_depth)
    ys_np = np.abs(np.random.rand(batch_size, num_tfs, n_sources))
    vs = torch.from_numpy(vs_np)
    ys = torch.from_numpy(ys_np)

    np_frobenius = numpy_naive(vs_np, ys_np)
    naive_torch_frobenius = losses.frobenius_naive(vs, ys).data.numpy()
    #
    print("Numpy Frobenius: {}".format(np_frobenius))
    print("Naive Torch Frobenius: {}".format(naive_torch_frobenius))

    assert np.abs(np_frobenius -
                  naive_torch_frobenius) < 10e-5, 'Naive ' \
                    'implementations of Frobenius norm should be equal'

    efficient_frobenius = losses.efficient_frobenius(vs, ys)
    print("Efficient Frobenius: {}".format(efficient_frobenius))

    # assert np.abs(np_frobenius -
    #               efficient_frobenius) < 10e-5, 'Efficient == Naive '

    paris_wtf = losses.naive(vs, ys)
    print("Paris wtf: {}".format(paris_wtf))


from tkinter import *
from chatbot import answer
root=Tk()
root.configure(background="black")
txt=Text(root)
txt.insert(END,"********************************************************************************\n")
txt.insert(END,"                    WELCOME TO AICTE CHATBOT DOJOBOT\n")
txt.insert(END,"********************************************************************************\n")
def send ():
    s=e.get()
    j=answer(s)

    txt.insert(END,"DOJOBOT-\n"+j)
    txt.insert(END,"\n")

txt.grid(row=0,column=0,columnspan=2)
e=Entry(root,width=100)
send=Button(root,text="SEND",command=send).grid(row=1,column=1)
e.grid(row=1,column=0)
root.title("chatbot")
root.mainloop()


import torch
import torch.nn as nn
from utils import model_info

class TorchGRUnet(nn.Module):
    """
    GRU network using PyTorch
    """
    def __init__(self, input_size, hidden_size, output_size,
                 num_layers=1, bidirection=False):
        super().__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.bidirection = bidirection
        if bidirection: # Add option for bidirectional
            self.gru = nn.GRU(
                input_size,
                hidden_size,
                num_layers,
                bidirectional=bidirection)
            self.fc = nn.Linear(hidden_size*2, output_size)
        else:
            self.gru = nn.GRU(input_size, hidden_size, num_layers)
            self.fc = nn.Linear(hidden_size, output_size)
        self.relu = nn.ReLU()
        self.logsoftmax = nn.LogSoftmax(dim=1)

    def forward(self, x, h):
        out, h = self.gru(x, h)
        out = self.fc(self.relu(out[:,-1]))
        out = self.logsoftmax(out)
        return out, h

    def init_hidden(self, batch_size=1):
        weight = next(self.parameters()).data
        # num_layers, batch_size, hidden_size
        factor = 2 if self.bidirection else 1
        hidden = weight.new(
            self.num_layers*factor,
            batch_size,
            self.hidden_size
        ).zero_()

        return hidden

class ThirawatGRUNet(nn.Module):
    '''
    My implimentation of GRU. Only support batch size = 1.
    '''
    def __init__(self, input_size, hidden_size, output_size, num_layers=1):
        super().__init__()

        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.output_size = output_size

        self.cells = nn.ModuleList()

        self.cells.append(self.GRUCell(
            self.input_size,
            self.hidden_size
        ))
        for _ in range(1, self.num_layers):
            self.cells.append(self.GRUCell(
                self.hidden_size,
                self.hidden_size
        ))
        self.fc = nn.Linear(self.hidden_size, self.output_size)
        self.relu = nn.ReLU()
        self.logsoftmax = nn.LogSoftmax(dim=1)

    def forward(self, x, h):
        hiddens = []
        for layer in range(self.num_layers):
            if layer == 0:
                hidden = self.cells[layer](x[:, 0, :], h[layer, :, :])
            else:
                hidden = self.cells[layer](h[layer-1, :, :], h[layer, :, :])
            hiddens.append(hidden)

        out = self.fc(self.relu(hidden))
        out = self.logsoftmax(out)

        return out, torch.stack(hiddens)

    def init_hidden(self, batch_size=1):
        weight = next(self.parameters()).data
        # num_layers, batch_size, hidden_size
        hidden = weight.new(
            self.num_layers,
            batch_size,
            self.hidden_size
        ).zero_()

        return hidden

    class GRUCell(nn.Module):
        def __init__(self, input_size, hidden_size) -> None:
            super().__init__()

            self.input_reset = nn.Linear(input_size, hidden_size)
            self.hidden_reset = nn.Linear(hidden_size, hidden_size)
            self.h1 = nn.Linear(hidden_size, hidden_size)
            self.x1 = nn.Linear(input_size, hidden_size)

            self.input_update = nn.Linear(input_size, hidden_size)
            self.hidden_update = nn.Linear(hidden_size, hidden_size)

        def forward(self, x, h):
            reset_gate = torch.sigmoid(
                self.input_reset(x)
                + self.hidden_reset(h)
            )
            r = nn.Tanh()((reset_gate * self.h1(h)) + self.x1(x))

            update_gate = torch.sigmoid(
                self.input_update(x)
                + self.hidden_update(h)
            )
            u = update_gate * h

            out = ((1-update_gate) * r) + u

            return out

if __name__ == '__main__':
    model = TorchGRUnet(300, 100, 2, 2, True)
    model_info(model)
    model = ThirawatGRUNet(300, 100, 2, 2)
    model_info(model)


import pygame as pg

vec = pg.math.Vector2

# define some colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BROWN = (106, 55, 5)
CYAN = (0, 255, 255)

# game settings
WIDTH = 1024  # 16 * 64 or 32 * 32 or 64 * 16(divisible by) a whole no squares up n down cross
HEIGHT = 768  # 16 * 48 or 32 * 24 or 64 * 12
FPS = 60
TITLE = "BOB's WORLD"
BGCOLOR = BROWN

TILESIZE = 16
GRIDWIDTH = WIDTH / TILESIZE
GRIDHEIGHT = HEIGHT / TILESIZE

WALL_IMG = 'tileGreen_39.png'

# player settings
PLAYER_HEALTH = 100
PLAYER_SPEED = 300.0
PLAYER_ROT_SPEED = 250.0  # everything is per second we are using delta time on the frames(easy way adjust how fast or sow we wan the player to be able to turn )
PLAYER_IMG = 'manBlue_gun.png'
PLAYER_HIT_RECT = pg.Rect(0, 0, 35, 35)
BARREL_OFFSET = vec(30,
                    10)  # vec representing how far from the center sprite the barrel of the gun is(20 pixels forward, 20 pixels downward)

# weapons settings
BULLET_IMG = 'bullet.png'
WEAPONS = {}
WEAPONS['pistol'] = {'bullet_speed': 500,
                     'bullet_lifetime': 1000,
                     'rate': 250,
                     'kickback': 200,
                     'spread': 5,
                     'damage': 10,
                     'bullet_size': 'lg',
                     'bullet_count': 1}
WEAPONS['shotgun'] = {'bullet_speed': 400,
                      'bullet_lifetime': 500,
                      'rate': 900,
                      'kickback': 300,
                      'spread': 20,
                      'damage': 5,
                      'bullet_size': 'sm',
                      'bullet_count': 12}

BULLET_SPEED = 500
BULLET_LIFETIME = 1000
BULLET_RATE = 150  # how fast we can shoot if we hold space bar down how fast did the bullets get produced
KICKBACK = 200
GUN_SPREAD = 5  # to give bullet inaccuracy every bullet come out in a perfectly straight line (5 represents how many degree to the left and right that the bullet will travel)
BULLET_DAMAGE = 10  # 10 points of damage and zombie will have 1000 health

# mob settings
MOB_IMG = 'zombie1_hold.png'
MOB_SPEEDS = [150, 100, 75, 125]
MOB_HIT_RECT = pg.Rect(0, 0, 30, 30)
MOB_HEALTH = 100
MOB_DAMAGE = 10
MOB_KNOCKBACK = 20
AVOID_RADIUS = 50
DETECT_RADIUS = 400  # how far can zombie see

# Effects
MUZZLE_FLASHES = ['whitePuff15.png', 'whitePuff16.png', 'whitePuff17.png', 'whitePuff18.png']
FLASH_DURATION = 50
SPLAT = 'splat green.png'
DAMAGE_ALPHA = [i for i in range(0, 255, 5)]
NIGHT_COLOR = (50, 50, 50)
LIGHT_RADIUS = (500, 500)
LIGHT_MASK = "light_350_med.png"

# Layers
WALL_LAYER = 1  # wall is at lowest layer as we set 1 (lowest number)
PLAYER_LAYER = 2
BULLET_LAYER = 3
MOB_LAYER = 2
EFFECTS_LAYER = 4
ITEMS_LAYER = 1

# Items
ITEM_IMAGES = {'health': 'health_pack.png',
               'shotgun': 'obj_shotgun.png'}
HEALTH_PACK_AMOUNT = 20
BOB_RANGE = 15  # how many pixels up and down we want our item
BOB_SPEED = 0.4

# Sounds
BG_MUSIC = 'espionage.ogg'
PLAYER_HIT_SOUNDS = ['pain/8.wav', 'pain/9.wav', 'pain/10.wav', 'pain/11.wav']
ZOMBIE_MOAN_SOUNDS = ['brains2.wav', 'brains3.wav', 'zombie-roar-1.wav', 'zombie-roar-2.wav',
                      'zombie-roar-3.wav', 'zombie-roar-5.wav', 'zombie-roar-6.wav', 'zombie-roar-7.wav']
ZOMBIE_HIT_SOUNDS = ['splat-15.wav']
WEAPON_SOUNDS = {'pistol': ['pistol.wav'],
                 'shotgun': ['shotgun.wav']}
EFFECTS_SOUNDS = {'level_start': 'level_start.wav',
                  'health_up': 'health_pack.wav',
                  'gun_pickup': 'gun_pickup.wav'}