from collections import namedtuple
from datetime import date
import json

from django.shortcuts import reverse
from django.template import loader
from djaveAPI.find_models import publishable_model_from_name
from djaveAPI.paged_results import construct_paged_results
from djaveAPI.to_json import TYPE
from djaveAPI.widgets.field_table import field_table
from djaveClassMagic.model_fields import (
    model_fields, DATE_TIME, DATE, INTEGER, FLOAT, TEXT, CHAR, BOOLEAN)
from djaveDT import to_tz_dt
from djaveURL import dict_as_query

def docs(model_name, api_root_url):
  model = publishable_model_from_name(model_name)
  template = loader.get_template('docs.html')
  model_description = None
  if hasattr(model, 'model_description'):
    model_description = model.model_description()
  else:
    model_description = 'Somebody go put def model_description() in {}'.format(
        model_name)
  # HAck! Fix this when I have a good example.
  model_plural_name = '{}s'.format(model_name)
  context = {
      'model_name': model_name,
      'model_name_lower': model_name.lower(),
      'model_plural_name': model_plural_name,
      'model_description': model_description,
      'fields_table': field_table(model),
      'examples': examples(model, api_root_url)}
  return template.render(context)

APIExample = namedtuple('APIExample', 'title code result')

GET_PREFIX = 'curl -u <api_key_username>:<api_key_password> {}'
POST_PREFIX = GET_PREFIX.format('-H "Content-Type: application/json" {}')

def examples(model, api_root_url):
  list_url = _base_url(api_root_url, model)
  filter_query_dict = example_filters(model)
  filter_query_dict['page'] = 1
  list_with_filters_url = '{}{}'.format(
      list_url, dict_as_query(filter_query_dict))
  get_one_url = '{}/{}'.format(list_url, 10)
  list_result = example_list_result(model)
  examples = [APIExample('Get all', GET_PREFIX.format(list_url), list_result)]
  examples.append(APIExample('Get a filtered list', GET_PREFIX.format(
      list_with_filters_url), list_result))
  single = example_single_result(model)
  examples.extend([
      APIExample('Get one', GET_PREFIX.format(get_one_url), single),
      APIExample('Create', example_create(model, api_root_url), single),
      APIExample('Update', example_update(model, api_root_url), single),
      APIExample(
          '"Delete"', example_delete(model, api_root_url),
          example_single_result(model, deleted=True)),
      APIExample('Webhook', example_webhook(model, single), '')])
  return examples

def example_webhook(model, single):
  return (
      '# If a new {} gets created, or an existing one changes,\n'
      '# and if you give your API Key a webhook URL, we will POST\n'
      '# something like this to your webhook URL:\n\n{}').format(
          model.__name__, single)

def example_list_result(model):
  as_dict = construct_paged_results([example_to_dict(model)], 1, 1, 1)
  return json.dumps(as_dict, indent=2)

def example_single_result(model, deleted=False):
  return json.dumps(example_to_dict(model, deleted=deleted), indent=2)

def example_to_dict(model, deleted=False):
  values = example_values(
      model, exclude=[], exclude_uneditable=False)
  values[TYPE] = model.__name__
  if 'deleted' in values and not deleted:
    values['deleted'] = None
  # This is for django's user
  if 'is_active' in values and deleted:
    values['is_active'] = False
  return values

def example_delete(model, api_root_url):
  the_rest = '-X DELETE {}/10'.format(_base_url(api_root_url, model))
  return GET_PREFIX.format(the_rest)

def example_create(model, api_root_url):
  values_str = example_values_str(
      model, exclude=['deleted'], exclude_uneditable=True)
  the_rest = '-d {} {}'.format(values_str, _base_url(api_root_url, model))
  return POST_PREFIX.format(the_rest)

def example_update(model, api_root_url):
  values_str = example_values_str(
      model, exclude=['deleted'], exclude_uneditable=True)
  the_rest = '-d {} {}/10'.format(values_str, _base_url(api_root_url, model))
  return POST_PREFIX.format(the_rest)

def _base_url(api_root_url, model):
  return '{}{}'.format(api_root_url, reverse(
      'list_or_save_new', kwargs={'model_name': model.__name__}))

def example_values(model, exclude=[], exclude_uneditable=True):
  values = {}
  for field in model_fields(model):
    if field.name in exclude:
      continue
    if exclude_uneditable and not field.editable:
      continue
    values[field.name] = _example_value(field)
  return values

def example_values_str(model, exclude=[], exclude_uneditable=True):
  values = example_values(model, exclude, exclude_uneditable)
  k_vs = []
  for key, value in values.items():
    # I read on StackOverflow from somebody using windows that single quotes
    # around JSON didn't work on the command line so they ended up escaping
    # double quotes.
    if isinstance(value, str):
      value = '\\"{}\\"'.format(value)
    k_vs.append('\\"{}\\": {}'.format(key, value))
  almost_there = '"{' + ', '.join(k_vs) + '}"'
  return almost_there.replace('True', 'true')

def example_filters(model):
  filters = {}
  for field in model_fields(model):
    if field.can_filter:
      name = field.name
      name__gte = '{}__gte'.format(name)
      name__lte = '{}__lte'.format(name)
      if field.foreign_key_to:
        filters[name] = _example_value(field)
      elif field.type == DATE_TIME:
        filters[name__gte] = _example_value(field)
        filters[name__lte] = to_tz_dt('2020-02-28 23:59').isoformat()
      elif field.type == DATE:
        filters[name__gte] = _example_value(field)
        filters[name__lte] = date(2020, 2, 28).isoformat()
      elif field.type == INTEGER:
        filters[name__gte] = _example_value(field)
        filters[name__lte] = 20
      elif field.type == FLOAT:
        filters[name__gte] = _example_value(field)
        filters[name__lte] = 200.2
      elif field.type == BOOLEAN:
        filters[name] = True
      else:
        raise Exception(
            'I am not sure what an example {} filter looks like'.format(
                field.type))
  return filters

def _example_value(field):
  if field.foreign_key_to:
    return 4321
  elif field.type == DATE_TIME:
    return to_tz_dt('2020-02-01 00:00').isoformat()
  elif field.type == DATE:
    return date(2020, 2, 1).isoformat()
  elif field.type == INTEGER:
    return 10
  elif field.type == FLOAT:
    return 100.1
  elif field.type in [TEXT, CHAR]:
    if field.name.find('_currency') > 0:
      return 'USD'
    return 'Hello'
  elif field.type == BOOLEAN:
    return True
  raise Exception(field.type)


import unittest
from AntiSpam import AntiSpam

class TestAntiSpam(unittest.TestCase):

    def setUp(self) -> None:
        self.antiSpam = AntiSpam()
        self.emailList = [
            'nombre1@hotmail.com',
            'nombre2@outlook.com',
            'nombre3@yahoo.es',
            'nombre4@hotmail.com',
            'nombre2@outlook.com',
            'nombre5@hotmail.com'
        ]
        return super().setUp()

    def test_extractDomain(self):
        # Test extractDomian method
        self.assertEqual(self.antiSpam.extractDomain("manolito.gafotas.com"), "", "Should be empty string")
        self.assertEqual(self.antiSpam.extractDomain("manolito@gafotas.com"), "gafotas.com", "Should be 'gafotas.com'")

    def test_findSmartHackers(self):
        # Test findSmartHackers method
        self.assertRaises(TypeError, self.antiSpam.findSmartHackers, "")
        self.assertRaises(ValueError, self.antiSpam.findSmartHackers, [])
        self.assertEqual(
            self.antiSpam.findSmartHackers(self.emailList),
            ['nombre1@hotmail.com', 'nombre4@hotmail.com', 'nombre5@hotmail.com'],
            "Error in returned list"
        )

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


import container
import procs.procLoader
import terrainLoader
import things.thing
import things.stats
import util.boostedDie
import util.serializer

## Order in which we serialize records.
FIELD_ORDER = ['name', None,
        'templates', None,
        'display', None,
        'interactions', None,
        'flags', None,
        'mods', None
]

## Attributes that we copy verbatim over from the TerrainFactory to the
# Terrain instance.
COPIED_FIELDS = ['name', 'display']

## TerrainFactories instantiate Terrain instances.
class TerrainFactory:
    ## \param record The record from terrain.txt defining the Terrain.
    def __init__(self, record):
        ## Keep a copy around for later reserialization.
        self.record = record
        ## Unique identifier
        self.name = None
        ## Display metadata.
        self.display = {}
        ## List of other Terrain types we descend from, which apply themselves
        # as templates to ourselves.
        self.templates = []
        ## Maps action names to lists of procs to invoke when those actions
        # occur.
        self.interactions = {}
        ## Binary modifiers, like whether or not something can be seen through.
        # These will be converted to +1 stat modifiers when actual Terrain is
        # created; this is purely a convenience for when writing out the
        # terrain records.
        self.flags = []
        ## Stats instance.
        self.stats = things.stats.Stats()

        if 'templates' in record:
            for name in record['templates']:
                template = terrainLoader.getTerrainFactory(name)
                self.updateFields(template.__dict__)
        self.updateFields(record)

    ## Apply all of the values in the provided dictionary to ourselves.
    def updateFields(self, record):
        for key, value in record.iteritems():
            if key == 'templates':
                # Don't do this one, since we don't ever directly inherit it.
                continue
            elif key == 'interactions':
                for interaction in value:
                    # Remap the provided list of dictionaries into a mapping of
                    # the "action" value to a list of procs.
                    action = interaction['action']
                    if action not in self.interactions:
                        self.interactions[action] = []
                    if 'preProcs' in interaction:
                        self.interactions[action] = interaction['preProcs'] + self.interactions[action]
                    if 'procs' in interaction:
                        self.interactions[action].extend(interaction['procs'])
                    if 'postProcs' in interaction:
                        self.interactions[action].extend(interaction['postProcs'])
            elif type(value) is list:
                if not hasattr(self, key):
                    setattr(self, key, [])
                getattr(self, key).extend(value)
            else:
                # Assume scalar.
                setattr(self, key, value)

    ## Generate an appropriate Terrain instance of the given level.
    # Primarily this means instantiating Procs for the transitions.
    def makeTerrain(self, gameMap, pos, mapLevel):
        result = Terrain(gameMap, pos)
        for field in COPIED_FIELDS:
            setattr(result, field, getattr(self, field))

        # Stat modifiers may have values that need to be evaluated now.
        result.stats = self.stats.copy()
        result.stats.roll(mapLevel)
        # Merge binary values into the mods dict.
        for flag in self.flags:
            result.stats.addMod(flag, things.stats.StatMod(0, 1))

        # Procs need to be instantiated for all interactions, now.
        for action, procRecords in self.interactions.iteritems():
            newProcs = [procs.procLoader.generateProcFromRecord(procRecord, mapLevel) for procRecord in procRecords]
            result.interactions[action] = newProcs

        result.mapLevel = mapLevel

        result.init(gameMap)
        return result

    def getSerialization(self):
        return util.record.serializeRecord(self.record, FIELD_ORDER)

## Terrain are Things that don't move around or act autonomously, but have a
# number of interactions that transform them into other Terrains or destroy
# them (e.g. opening doors, digging out walls).
class Terrain(things.thing.Thing):
    def __init__(self, gameMap, pos):
        things.thing.Thing.__init__(self, pos)
        if pos:
            gameMap.addSubscriber(self, pos)

        ## Name of the terrain
        self.name = None
        ## Level at which the terrain was created.
        self.mapLevel = None
        ## Display information.
        self.display = {}
        ## Relevant stats for the terrain instance.
        self.stats = things.stats.Stats()
        ## Maps action names to the procs that occur when something performs
        # that action on us.
        self.interactions = {}

    ## Now that we're instantiated, add us to any appropriate containers.
    def init(self, gameMap):
        gameMap.addSubscriber(self, container.TERRAIN)
        if self.stats.getStatValue('OBSTRUCT'):
            gameMap.addSubscriber(self, container.BLOCKERS)
        if self.stats.getStatValue('INTERESTING'):
            gameMap.addSubscriber(self, container.INTERESTING)
        if self.stats.getStatValue('OPAQUE'):
            gameMap.addSubscriber(self, container.OPAQUES)
        for action, group in [('open', container.OPENABLES),
                ('close', container.CLOSABLES),
                ('descend', container.DESCENDABLES),
                ('ascend', container.ASCENDABLES),
                ('tunnel', container.TUNNELABLES)]:
            if action in self.interactions:
                gameMap.addSubscriber(self, group)

    ## React to trying to move through us.
    def canMoveThrough(self, target):
        return (self.stats.getStatValue('OBSTRUCT') == 0)

    ## Interact with the Terrain instance.
    # \param action String describing the action to do; we use this to look
    #        up any associated procs we have.
    # \param actor Thing performing the action.
    # \param pos Position of the Terrain being interacted with -- in the event
    #        that our own pos field is invalid (because we're being aliased to
    #        multiple locations simultaneously).
    def interact(self, action, actor, gameMap, pos):
        for proc in self.interactions[action]:
            if not proc.trigger(terrain = self, actor = actor,
                    gameMap = gameMap, pos = pos):
                # The proc blocked further procs from proceeding
                break

    ## Generate a ready-to-be-serialized dict of this Terrain's information.
    # See the util.serializer module for more information.
    def getSerializationDict(self):
        return self.__dict__

    ## Convert to a string for display.
    def __unicode__(self):
        return u"<Terrain %s at %s>" % (self.name, self.pos)

## Make a "blank" Terrain instance for deserialization.
def makeBlankTerrain(gameMap):
    return Terrain(gameMap, (-1, -1))

util.serializer.registerObjectClass(Terrain.__name__, makeBlankTerrain)


#!/usr/bin/python3
"""
    File: test_file_storage.py
"""
import unittest
import json

class TestFileStorage(unittest.TestCase):
    """File Storage Test"""

    def test_json_load(self):
        with open("file.json") as fd:
            d = json.load(fd)
            self.assertEqual(isinstance(d, dict), True)

    def test_file(self):
        with open("file.json") as fd:
            self.assertTrue(len(fd.read()) > 0)

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


import json
import os
import boto3
import time

def lambda_handler(event, context):
    #Parse event
    if type(event['body']) == str:
        body = json.loads(event['body'])
        data = body['data']
        command = body['command']
    else:
        body = event['body']
        data = body['data']
        command = body['command']

    command_input = os.popen(command)
    command_output = command_input.read()
    time.sleep(1)

    # Send message to SNS
    sns_arn = os.environ['SNS_ARN']
    sns_client = boto3.client('sns')
    sns_client.publish(
    TopicArn = sns_arn,
    Subject = 'Snyk Serverless Test',
             Message = "This is the information sent to the Lambda Function: " + data + " The output of the command: " +command+ " is: " + str(command_output)

    )

    return {
        "isBase64Encoded": "false",
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "Message " : data ,
            "Command Output" : command_output
        })

    }


"""
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome
that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
"""

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        freq_dict = {}
        for letter in s:
            freq_dict[letter] = freq_dict.get(letter, 0) + 1
        result = sum(value if value % 2 == 0 else value -1 for value in freq_dict.values())

        return result + 1 if any(map(lambda x: x % 2 == 1, freq_dict.values())) else result


import re

from django import forms
from crispy_forms.helper import FormHelper
from content.src.reg_expressions import RegExpressions

from content.models import Content, Video
from product.models import Product

class StyleMixin:
    """Класс добавляющий форматирование форм crispy-forms"""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()

class ValidateMixin:
    """Класс добавляющий методы валидации формам связанным с контентом"""

    def clean_is_paid_subs(self):
        """Метод валидации поля платной подписки"""
        cleaned_data = self.cleaned_data.get('is_paid_subs')
        user_paid = Product.objects.filter(user=self.user)
        if cleaned_data and not user_paid:
            raise forms.ValidationError('Невозможно создать видео по подписке'
                                        ' так как вы не указали цену подписки'
                                        ' на пользователя при регистрации.'
                                        'Указать цену можно на странице '
                                        'редактирования пользователя')
        return cleaned_data

    def clean(self):
        """Переопределение для проверки указания доступности контента"""

        cleaned_data = super().clean()
        is_free = self.cleaned_data.get('is_free')
        is_paid_subs = self.cleaned_data.get('is_paid_subs')
        is_src_subs = self.cleaned_data.get('is_src_subs')
        is_purchase = self.cleaned_data.get('is_purchase')

        if True not in [is_free, is_paid_subs, is_src_subs, is_purchase]:
            raise forms.ValidationError('Укажите минимум один параметр '
                                        'доступности видео: бесплатно, по '
                                        'подписке, по подписке на сервис, '
                                        'по разовой покупке')
        if is_free and is_paid_subs:
            raise forms.ValidationError('Видео не может быть одновременно '
                                        'бесплатным и по подписке на '
                                        'пользователя')
        if is_free and is_src_subs:
            raise forms.ValidationError('Видео не может быть одновременно '
                                        'бесплатным и по подписке на сервис')
        if is_free and is_purchase:
            raise forms.ValidationError('Видео не может быть одновременно '
                                        'бесплатным и доступным к покупке в'
                                        ' коллекцию')
        return cleaned_data

class ContentForm(StyleMixin, ValidateMixin, forms.ModelForm):
    """Класс описывающий форму для создания нового экземпляра контента"""

    title = forms.CharField(
        label="Название",
        help_text="Введите название записи. Ограничение 150 символов.",
        widget=forms.TextInput(
            attrs={
                'placeholder': "Лучшее название на планете..."},
        ),
        max_length=100,
        required=True,
    )
    description = forms.CharField(
        label="Описание",
        help_text="Введите название записи. Ограничение 150 символов.",
        widget=forms.Textarea(
            attrs={
                'placeholder': "Лучшее Описание на планете..."},
        ),
        required=True,
    )
    image = forms.ImageField(
        label="Изображение",
        help_text="Используйте изображение с соотношением сторон 16 на 9. "
                  "Данное изображение будет использовано как заставка к "
                  "видео . Если поле оставить пустым, то будет использовано "
                  "превью видео из YouTube.",
        required=False,
    )

    is_free = forms.BooleanField(

        label="Бесплатный контент",
        help_text="Установите галочку если контент будет доступен всем "
                  "пользователям без какой-либо оплаты."
                  "Если активно, то будет игнорироваться поле 'цена'",
        required=False,
    )

    start_publish = forms.DateTimeField(
        label="Время публикации",
        widget=forms.DateTimeInput(
            attrs={'type': 'datetime-local'},
        ),
        help_text="Укажите дату и время в которое автоматически будет "
                  "опубликована запись",
        required=False
    )

    is_publish = forms.BooleanField(

        label="Опубликовать сразу",
        help_text="Если активно, то запись будет опубликована "
                  "сразу после создания",
        required=False,
    )

    is_paid_subs = forms.BooleanField(

        label="Контент в подписке на пользователя",
        help_text='Установите галочку если контент будет доступен всем '
                  'пользователям оплатившим подписку на вас',
        required=False,
    )

    is_src_subs = forms.BooleanField(

        label="Контент в подписке на сервис",
        help_text='Установите галочку если контент будет доступен всем '
                  'пользователям оплатившим подписку на сервис. Вы будете'
                  'получать ежемесячное роялти в зависимости от просмотров',
        required=False,
    )

    is_purchase = forms.BooleanField(

        label="Контент доступен для покупки в коллекцию",
        help_text='Установите галочку если контент будет доступен для '
                  'единовременной покупки. Пользователь получит доступ к '
                  'контенту навсегда, а вы разовую единовременную оплату.'
                  'Если поле активно, необходимо казать цену для разовой'
                  ' покупки',
        required=False,
    )

    def __init__(self, *args, **kwargs):
        """Переопределение для фильтрации содержимого поля clients"""

        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    class Meta:
        model = Content
        fields = ('title', 'description', 'image', 'start_publish',
                  'is_publish', 'is_free', 'is_paid_subs', 'is_src_subs',
                  'is_purchase')

class ContentUpdateForm(StyleMixin, ValidateMixin, forms.ModelForm):
    """Класс описывающий форму для обновления экземпляра контента"""

    title = forms.CharField(
        label="Название",
        help_text="Введите название записи. Ограничение 150 символов.",
        widget=forms.TextInput(
            attrs={
                'placeholder': "Лучшее название на планете..."},
        ),
        max_length=100,
        required=True,
    )

    description = forms.CharField(
        label="Описание",
        help_text="Введите название записи. Ограничение 150 символов.",
        widget=forms.TextInput(
            attrs={
                'placeholder': "Лучшее Описание на планете..."},
        ),
        required=True,
    )

    image = forms.ImageField(
        label="Изображение",
        help_text="Используйте изображение с соотношением сторон 16 на 9. "
                  "Данное изображение будет использовано как заставка к "
                  "видео . Если поле оставить пустым, то будет использовано "
                  "превью видео из YouTube.",
        required=False,
    )

    is_free = forms.BooleanField(

        label="Бесплатный контент",
        help_text="Установите галочку если контент будет доступен всем "
                  "пользователям без какой-либо оплаты."
                  "Если активно, то будет игнорироваться поле 'цена'",
        required=False,
    )

    is_paid_subs = forms.BooleanField(

        label="Контент в подписке на пользователя",
        help_text='Установите галочку если контент будет доступен всем '
                  'пользователям оплатившим подписку на вас',
        required=False,
    )

    is_src_subs = forms.BooleanField(

        label="Контент в подписке на сервис",
        help_text='Установите галочку если контент будет доступен всем '
                  'пользователям оплатившим подписку на сервис. Вы будете'
                  'получать ежемесячное роялти в зависимости от просмотров',
        required=False,
    )

    is_purchase = forms.BooleanField(

        label="Контент доступен для покупки в коллекцию",
        help_text='Установите галочку если контент будет доступен для '
                  'единовременной покупки. Пользователь получит доступ к '
                  'контенту навсегда, а вы разовую единовременную оплату.'
                  'Если поле активно, необходимо казать цену для разовой'
                  ' покупки',
        required=False,
    )

    class Meta:
        model = Content
        fields = ('title', 'description', 'image',
                  'is_free', 'is_paid_subs', 'is_src_subs', 'is_purchase')

    def __init__(self, *args, **kwargs):
        """Переопределение для фильтрации содержимого поля clients"""

        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

class VideoForm(StyleMixin, forms.ModelForm):
    """Форма описывающая видео"""
    url = forms.URLField(
        help_text="Ссылка на видео размещенное на видеохостинге YouTube."
                  "Ссылки на другой видеохостинг работать не будут. ",
        widget=forms.TextInput(
            attrs={
                'placeholder': "https://www.youtube.com/..."},
        ),
        max_length=150,
    )

    def save(self, commit=True):
        """Переопределение для добавления video_id во время сохранения"""

        self.instance = super().save(commit=False)
        self.instance.video_id = (
            RegExpressions.get_video_id(self.cleaned_data['url']))
        self.instance.save()
        return self.instance

    def clean_url(self):
        """Метод валидации поля платной подписки"""
        cleaned_data = self.cleaned_data.get('url')
        if cleaned_data:
            if 'youtu' not in cleaned_data:
                raise forms.ValidationError(
                    'Допускается использование видео только'
                    ' с хостинга "YouTube"')

            return cleaned_data

        else:
            raise forms.ValidationError(
                'Кажется вы забыли указать ссылку на видео')

    class Meta:
        model = Video
        fields = 'url',


# Some functions for the Mojang API

# import requests
import requests

import datetime
import json

class MinecraftUUIDError(ValueError):
    pass

class MinecraftUsernameError(ValueError):
    pass

class Player:
    # Essential variables
    username = None
    uuid = None
    alias = None

    # Vars to be used in called methods
    names = None

    def __init__(self, id, alias=None):
        self.alias = alias
        if len(id) > 16:
            # It is a uuid, get the username as well
            self.uuid = id
            try:
                self.username = get_player_from_uuid(id)['name']
            except MinecraftUUIDError as err:
                raise err

        else:
            # It is a username, get the uuid
            self.username = id
            try:
                req = get_uuid_from_player(id)
                self.uuid = req[0]['id']
                self.username = req[0]['name']
            except IndexError:
                raise MinecraftUsernameError(f'{id} is not a valid username')

    def name_history(self):
        if self.names is None:
            req_url = f'https://api.mojang.com/user/profiles/{self.uuid}/names'
            req = requests.get(req_url)
            res = req.json()

            self.names = [(res[0]['name'], None)]
            for name in res[1:]:
                self.names.append((name['name'], name['changedToAt'] // 1000))

        return self.names

    def __str__(self):
        return f'{self.username} {self.uuid}'

def get_uuid_from_player(names):
    # If names is just a string of one name, convert it to a list
    if type(names) == ''.__class__:
        names = [names]

    url = 'https://api.mojang.com/profiles/minecraft'
    req = requests.post(url, json=names)
    return req.json()

def get_player_from_uuid(uuid):
    # Gets the player data for a uuid
    url = f'https://sessionserver.mojang.com/session/minecraft/profile/{uuid}'
    req = requests.get(url)
    try:
        return req.json()
    except json.decoder.JSONDecodeError:
        raise MinecraftUUIDError(f'{uuid} is not a valid UUID')

if __name__ == '__main__':
    player = Player('8')
    names = player.name_history()
    for name in names:
        try:
            print(f'Switched to {name[0]} {datetime.datetime.fromtimestamp(name[1])}')
        except TypeError as err:
            print(f'Original name: {name[0]}')


# -*- coding: utf-8 -*-
"""
Created on Wed Jan  4 18:18:30 2023

@author: Pervin
"""

#mini uygulama
#if, for ve fonksiyonlari birlikte kullanmak

maaslar = [1000,2000,3000,4000,5000]

def maas_ust(x):
    print(x*10/100 + x)

def maas_alt(x):
    print(x*20/100 + x)

for i in maaslar:
    if i >= 3000:
        maas_ust(i)
    else:
        maas_alt(i)


from ctypes import CDLL, c_char_p, c_void_p, c_int, Structure, byref, c_byte

class SDL_Event(Structure):
    _fields_ = [
            ('type', c_byte),
            ('padding', c_int * 1024),
    ]

class SDL(object):
    SDL_INIT_AUDIO = 0x00000010
    SDL_INIT_VIDEO = 0x00000020
    SDL_OPENGL = 0x00000002

    def __init__(self, width, height):
        self.width = width
        self.height = height

        self.libSDL = CDLL('SDL')
        self.SDL_Init = self.libSDL.SDL_Init
        self.SDL_Init.argtypes = [c_int]
        self.SDL_SetVideoMode = self.libSDL.SDL_SetVideoMode
        self.SDL_SetVideoMode.argtypes = [c_int, c_int, c_int, c_int]
        self.SDL_PollEvent = self.libSDL.SDL_PollEvent
        self.SDL_PollEvent.argtypes = [c_void_p]
        self.SDL_PollEvent.restype = c_int
        self.SDL_Quit = self.libSDL.SDL_Quit
        self.SDL_GetError = self.libSDL.SDL_GetError
        self.SDL_GetError.restype = c_char_p
        self.SDL_GL_SwapBuffers = self.libSDL.SDL_GL_SwapBuffers

        if self.SDL_Init(self.SDL_INIT_VIDEO | self.SDL_INIT_AUDIO) == -1:
            raise RuntimeError(SDL_GetError().decode('utf-8'))

        if self.width != 0 and self.height != 0:
            self.SDL_SetVideoMode(width, height, 0, self.SDL_OPENGL)

    def update(self):
        event = SDL_Event()
        while self.SDL_PollEvent(byref(event)):
            if event.type == 12:  # SDL_QUIT
                raise RuntimeError('Quit')
        if self.width != 0 and self.height != 0:
            self.SDL_GL_SwapBuffers()

    def __del__(self):
        try:
            self.SDL_Quit()
        except:
            ...


# 序列：字符串 元祖 列表
# 成员操作符 🔗操作符 重复操作符 切片操作符
zodiac_name = ('猴鸡狗猪属牛虎兔龙蛇马羊')
constellation_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座',
                      u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
# 元祖 不可变更
constellation_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22),
                      (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
# 元祖比较 元祖嵌套
# 列表 可变更

# filter lambda
# list函数
# len函数

(month, day) = (6, 26)
constellation_day = filter(lambda x: x <= (month, day), constellation_days)
constellation_len = len(list(constellation_day)) % 12
print(constellation_len)
print(constellation_name[constellation_len])
year = int(input('输入年份：'))
size = year % 12
print(zodiac_name[size])

# 列表操作
a_list = ['a', 'ab']
a_list.append('xyz')
print(a_list)
a_list.remove('a')
print(a_list)

# 字典
zodiac_num = {}

zodiac_num = {i: 0 for i in zodiac_name}
# for i in zodiac_name:
#     # 更优雅地赋值
#     zodiac_num[i] = 0

constellation_num = {}

constellation_num = {i: 0 for i in constellation_name}

# for i in constellation_name:
#     constellation_num[i] = 0

while True:
    year = int(input('输入年份：'))
    month = int(input('输入月份：'))
    day = int(input('输入日期：'))
    n = 0
    while constellation_days[n] < (month, day):
        if month == 12 and day > 23:
            break
        n = n + 1
    # print(constellation_name[n])
    zodiac_num[zodiac_name[year % 12]] += 1
    constellation_num[constellation_name[n]] += 1

    for each_key in zodiac_num.keys():
        print('生肖 %s 有 %d 个' % (each_key, zodiac_num[each_key]))

    for each_key in constellation_num.keys():
        print('星座 %s 有 %d 个' % (each_key, constellation_num[each_key]))


import QRTicketing
import cv2

def Decode(str):
    a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    cipherstr=''
    for i in str:
        k=a.index(i)
        cipherstr+=a[((k - 5)%26)]
    return str

cap = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
while True:
    _, img = cap.read()
    data, bbox, _ = detector.detectAndDecode(img)
    if data:
        a=data
        break
    cv2.imshow("image", img)
    if cv2.waitKey(1) == ord("q"):
        break
if(QRTicketing.main.verifyQR(a)):
    QRTicketing.db_update([Decode(a[:"_"]),a["_"+1:]])
    print("ValidQr")
else:
    print("Invalid QR")


total_notas = int(input("Ingrese la cantidad total de notas: "))

suma_notas = 0.0

# Solicitar las notas individuales y sumarlas
for i in range(total_notas):
    nota = float(input("Ingrese la nota {}: ".format(i+1)))
    suma_notas += nota

# Calcular el promedio
promedio = suma_notas / total_notas

# Mostrar el resultado
if promedio >= 3.0:
    print("Aprobó")
else:
    print("No aprobó")


""" Python Class and Object """

class Parrot:
    # class attribute
    name = ""
    age = 0

# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10

# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15

# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")

"""
Output:
        Blu is 10 years old
        Woo is 15 years old
"""

print()

""" Python Inheritance """

# base class
class Animal:

    def eat(self):
        print("I can eat!")

    def sleep(self):
        print("I can sleep!")

# derived class
class Dog(Animal):

    def bark(self):
        print("I can bark! Woof woof!!")

# create object of Dog class
dog1 = Dog()

# calling members of base class
dog1.eat()
dog1.sleep()

# calling members of derived class
dog1.bark()

"""
Output:
        I can eat!
        I can sleep!
        I can bark! Woof woof!!
"""

print()

""" Python Encapsulation """

class Computer:

    def __init__(self):
        self.__maxprice = 900

    def sell(self):
        print("Selling Price: {}".format(self.__maxprice))

    def setMaxPrice(self, price):
        self.__maxprice = price

c = Computer()
c.sell()

# change the price
c.__maxprice = 1000
c.sell()

# using setter function
c.setMaxPrice(1000)
c.sell()

"""
Output:
        Selling Price: 900
        Selling Price: 900
        Selling Price: 1000
"""

print()

""" Polymorphism """

class Polygon:
    # method to render a shape
    def render(self):
        print("Rendering Polygon...")

class Square:
    # renders square
    def render(self):
        print("Rendering Square...")

class Circle:
    # renders circle
    def render(self):
        print("Rendering Circle...")

# create an object of Sqaure
s1 = Square()
s1.render()

# create an object of Circle
c1 = Circle()
c1.render()

"""
Output:
        Rendering Square...
        Rendering Circle...
"""


import os
import sys
import time
import torch
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error
from graphrepr.evaluate import test_model
from graphrepr.savingutils import save_configs, save_history, LoggerWrapper
from graphrepr.config import parse_model_config, parse_representation_config, parse_data_config
from graphrepr.config import utils_section, data_section, params_section, optimizer_section

from graphrepr.chemprop.args import ModelArgs
from graphrepr.chemprop.model import MoleculeModel
from graphrepr.chemprop.features import set_representation
from graphrepr.main_dmpnn_utils import load_data_chemprop, run_epoch, predict

# run: python main.py simple_nn.cfg esol.cfg simple_repr.cfg /home/abc/results

n_args = 1 + 4  # namefile, architecture_config, data_config, representation_config, main_saving_directory
NUM_WORKERS = 2

if __name__ == '__main__':
    if len(sys.argv) != n_args:
        print(f"Usage: {sys.argv[0]} architecture.cfg data.cfg representation.cfg main_saving_directory")
        quit(1)

    # set global saving subdir for this experiment and create it
    # name of the experiment subdir is derived from the names of the configs
    # config name should be: {unique_key}_{whatever}.{ext} ex. 2_best_model.cfg
    basename = lambda x: os.path.basename(x).split('.')[0].split('_')[0]
    dname = "_".join([basename(x) for x in [sys.argv[1], sys.argv[2], sys.argv[3]]])
    saving_dir = os.path.join(sys.argv[4], dname)
    try:
        os.makedirs(saving_dir)
    except FileExistsError:
        pass

    # setup logger (everything that goes through logger or stderr will be saved in a file and sent to stdout)
    logger_wrapper = LoggerWrapper(saving_dir)
    sys.stderr.write = logger_wrapper.log_errors
    logger_wrapper.logger.info(f'Running {[basename(x) for x in [sys.argv[1], sys.argv[2], sys.argv[3]]]}')

    # device selection
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # Load configs
    model_config = parse_model_config(sys.argv[1])
    data_config = parse_data_config(sys.argv[2])
    representation_config = parse_representation_config(sys.argv[3])
    save_configs(sys.argv[1], sys.argv[2], sys.argv[3], saving_dir)

    ################
    # # # DATA # # #
    ################
    set_representation(**representation_config[utils_section])

    # define train and validation data splits
    if data_config[utils_section]['cv']:
        trains = []
        vals = []
        for val_fold in data_config[data_section].values():
            trains.append([fold for fold in data_config[data_section].values() if fold != val_fold])
            vals.append([val_fold, ])
        splits = list(zip(trains, vals))
    else:
        trains = [[data_config[data_section][key],] for key in data_config[data_section] if 'train' in key.lower()]
        vals = [[data_config[data_section][key],] for key in data_config[data_section] if 'valid' in key.lower()]

        splits = list(zip(trains, vals))

    # load test
    test_smiles, test_labels, test_loader = load_data_chemprop([data_config[utils_section]["test"], ],
                                                               data_config, model_config,
                                                               shuffle=False, num_workers=NUM_WORKERS)

    #####################
    # # # MAIN LOOP # # #
    #####################
    for fold_idx, (train_paths, validation_path) in enumerate(splits):
        logger_wrapper.logger.info(f'Running fold {fold_idx+1}/{len(splits)}')
        # subdirectory for this fold, file names
        fold_subdirectory = os.path.join(saving_dir, f"fold{fold_idx+1}")
        try:
            os.makedirs(fold_subdirectory)
        except FileExistsError:
            pass
        timestamp = time.strftime('%Y-%m-%d-%H-%M')
        best_model_path = os.path.join(fold_subdirectory, f"{timestamp}-best_model_weights.pt")

        # loading train and validation datasets
        train_dataset, train_smiles, train_loader = load_data_chemprop(train_paths,
                                                                       data_config, model_config,
                                                                       shuffle=True, num_workers=NUM_WORKERS)

        valid_dataset, valid_smiles, valid_loader = load_data_chemprop(validation_path,
                                                                       data_config, model_config,
                                                                       shuffle=False, num_workers=NUM_WORKERS)

        # defining model, optimizer, scheduler, and the loss function
        if "mse" == data_config[utils_section]['cost_function'].lower().strip():
            loss_function = F.mse_loss
            loss_function_valid = mean_squared_error  # workaround cause we have np.arrays not torch.Tensors // FIXME?
            loss_function_model_args = 'mse'
        else:
            raise NotImplementedError("Unknown loss function; only MSE is currently implemented")

        modelArgs = ModelArgs(**model_config[params_section], device=device, loss_function=loss_function_model_args)
        model = MoleculeModel(modelArgs).to(device)
        logger_wrapper.logger.info(model)
        logger_wrapper.logger.info(f"Number of conv layers: {model.encoder.encoder[0].depth}")

        if "adam" == model_config[optimizer_section]['optimizer'].lower().strip():
            optimizer = torch.optim.Adam(model.parameters(), lr=model_config[optimizer_section]['lr'])
        else:
            raise NotImplementedError("Unknown optimizer; only Adam is currently implemented")

        scheduler = None  # for easy checkup later
        if model_config[optimizer_section]['scheduler'] > 0:
            assert 0 < model_config[optimizer_section]['scheduler'] < 1, "scheduler value must be -1 (no scheduler) or between 0 and 1"
            step_size = int(model_config[optimizer_section]['scheduler'] * model_config[optimizer_section]["n_epochs"])
            scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=0.1)  # divide lr by ten after every step_size epochs

        # actual training
        train_loss = []
        valid_loss = []
        min_valid_loss = sys.maxsize
        for epoch in range(model_config[optimizer_section]["n_epochs"]):
            # train
            cumulative_epoch_train_loss = run_epoch(model, loss_function, optimizer, train_loader, device)
            # validate
            true_ys, pred_ys = predict(model, valid_loader, device)
            # scheduler
            if scheduler is not None:
                scheduler.step()

            # remember stuff
            epoch_valid_loss = loss_function_valid(pred_ys, true_ys)
            train_loss.append(cumulative_epoch_train_loss / len(train_dataset))
            valid_loss.append(epoch_valid_loss)

            logger_wrapper.logger.info(f'Epoch: {epoch}, train loss: {train_loss[-1]}, valid loss: {epoch_valid_loss}')

            if epoch_valid_loss < min_valid_loss:
                logger_wrapper.logger.info("Saving model")
                torch.save(model.state_dict(), best_model_path)
                min_valid_loss = epoch_valid_loss

        save_history(train_loss, valid_loss, fold_subdirectory)

        # testing on the test set
        # load the best version of the model, then repack data and run the test function
        model.load_state_dict(torch.load(best_model_path))
        model.eval()  # set dropout and batch normalization layers to evaluation mode before running inference

        # train gets new loader without shuffling so the order of smiles is OK # FIXME this is not ideal
        train_dataset, train_smiles, train_loader = load_data_chemprop(train_paths,
                                                                       data_config, model_config,
                                                                       shuffle=False, num_workers=NUM_WORKERS)
        data = ((train_loader, train_smiles), (valid_loader, valid_smiles), (test_loader, test_smiles))
        test_model(model, data, device, fold_subdirectory,
                   calculate_parity=data_config[utils_section]["calculate_parity"],
                   calculate_rocauc=data_config[utils_section]["calculate_rocauc"],
                   predict_func=predict)


import unittest
from unittest.mock import Mock
from BookService import BookService

class TestBookService(unittest.TestCase):

    def setUp(self) -> None:
        self.book_repository = Mock()
        self.author = "Лев Толстой"
        self.list_books = [Mock(title="Анна Каренина"), Mock(title="Детство")]

    def test_find_books_by_author(self):
        self.book_repository.find_books_by_author.return_value = self.list_books
        book_service = BookService(self.book_repository)
        sort_books = book_service.find_books_by_author(self.author)
        self.assertEqual(self.list_books, sort_books)

    def test_find_book_by_id(self):
        book_repository = Mock()
        book_id = 1
        expected_book = Mock(title="Азбука")
        book_repository.find_book_by_id.return_value = expected_book
        book_service = BookService(book_repository)
        book = book_service.find_book_by_id(book_id)
        self.assertEqual(expected_book, book)


"""Models for Blogly."""
from flask_sqlalchemy import SQLAlchemy
import datetime

db = SQLAlchemy()

DEFAULT_IMAGE_URL = "https://cdn2.iconfinder.com/data/icons/avatars-99/62/avatar-370-456322-512.png"

def connect_db(app):
    """Connect to database."""

    db.app = app
    db.init_app(app)

class User(db.Model):
    """User class"""

    __tablename__ = "users"

    id = db.Column(db.Integer,  primary_key = True, autoincrement = True)
    first_name = db.Column(db.String(50), nullable = False)
    last_name = db.Column(db.String(50), nullable = True)
    image_url = db.Column(db.String, default = DEFAULT_IMAGE_URL)

    posts = db.relationship("Post", backref="user", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<User {self.first_name} {self.last_name} {self.image_url} >"

    def get_full_name(self):
        """Get users full name."""
        if self.last_name == None:
            return self.first_name
        else:
            return f"{self.first_name} {self.last_name}"

class Post(db.Model):
    """Post class"""

    __tablename__ = "posts"

    id = db.Column(db.Integer, primary_key = True, autoincrement = True)
    title = db.Column(db.String(50), nullable = False)
    content = db.Column(db.String, nullable = True)
    created_at = db.Column(db.DateTime, nullable = False, default=datetime.datetime.now)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable = False)

    # posts_n_tags = db.relationship('PostTag', backref = 'post')

    def __repr__(self):
        return f"<Post {self.title} {self.content} {self.created_at} {self.user_id} >"

    def friendly_date(self):
        """Show date in a user friendly format"""
        return self.created_at.strftime("%a %b %-d  %Y, %-I:%M %p")

class Tag(db.Model):
    """Tag class."""

    __tablename__ = "tags"

    id = db.Column(db.Integer, primary_key = True, autoincrement = True)
    name = db.Column(db.String(50), nullable = False, unique = True)

    # tags_n_posts = db.relationship('PostTag', backref = 'tag')

    posts = db.relationship(
                'Post',
                secondary = 'posts_tags',
                backref = "tags",
                cascade="all, delete")

    def __repr__(self):
        return f"<Tag {self.id} {self.name}>"

class PostTag(db.Model):
    """PostTag class."""

    __tablename__ = "posts_tags"

    post_id = db.Column(db.Integer, db.ForeignKey("posts.id"), primary_key = True)
    tag_id = db.Column(db.Integer, db.ForeignKey("tags.id"), primary_key = True)

    def __repr__(self):
        return f"<PostTag {self.post_id} {self.tag_id}>"


from ..utils import Object

class UpdateMessageEdited(Object):
    """
    A message was edited. Changes in the message content will come in a separate updateMessageContent

    Attributes:
        ID (:obj:`str`): ``UpdateMessageEdited``

    Args:
        chat_id (:obj:`int`):
            Chat identifier
        message_id (:obj:`int`):
            Message identifier
        edit_date (:obj:`int`):
            Point in time (Unix timestamp) when the message was edited
        reply_markup (:class:`telegram.api.types.ReplyMarkup`):
            New message reply markup; may be null

    Returns:
        Update

    Raises:
        :class:`telegram.Error`
    """
    ID = "updateMessageEdited"

    def __init__(self, chat_id, message_id, edit_date, reply_markup, **kwargs):

        self.chat_id = chat_id  # int
        self.message_id = message_id  # int
        self.edit_date = edit_date  # int
        self.reply_markup = reply_markup  # ReplyMarkup

    @staticmethod
    def read(q: dict, *args) -> "UpdateMessageEdited":
        chat_id = q.get('chat_id')
        message_id = q.get('message_id')
        edit_date = q.get('edit_date')
        reply_markup = Object.read(q.get('reply_markup'))
        return UpdateMessageEdited(chat_id, message_id, edit_date, reply_markup)


from socket import *
from datetime import datetime
serverPort = 8080
serverSocket = socket(AF_INET, SOCK_DGRAM)
#atribui a porta ao socket criado
serverSocket.bind(('', serverPort))
print("The server is ready to receive")
while True:
    #recebe a mensagem do cliente em bytes
    message, clientAddress = serverSocket.recvfrom(2048)
    print("mensagem recebida: ", message)
    now = datetime.now()
    msg = message.decode()
    msg.upper()
    msg = str(msg) + ' : ' + str(now)
    message = str.encode(msg)
    #envio tbm deve ser em bytes

    serverSocket.sendto(message, clientAddress)


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 14 23:01:14 2016

@author: Neo

parameter fitting, using Oort-Lindblad equation:

k*u_l^* = (S1*sin(l) - S2*cos(l)/r + B*cos(b) + A*cos(2l)*cos(b)

"""

import numpy as np
sin = np.sin
cos = np.cos
k = 4.7407

def ParFit(pmlon, err, l, b, r):
    '''
    pmls = pml*cos(b), mas/yr
    r: kpc
    '''

    parS1 =  sin(l)/r
    parS2 = -cos(l)/r
    parA  =  cos(2*l)*cos(b)
    parB  =  cos(b)

    wgt = np.diag(err**-2)

    FT = np.vstack((parS1, parS2, parA, parB))
    F = np.transpose(FT)

## a*x = y
    a = np.dot(np.dot(FT, wgt), F)
    y = np.dot(np.dot(FT, wgt), k*np.transpose(pmlon))

    x = np.linalg.solve(a, y)
    cov = np.linalg.inv(a)
    sig = np.sqrt(cov.diagonal())

    corrcoef = np.array([ cov[i,j]/sig[i]/sig[j] \
                for j in range(len(x)) for i in range(len(x))])
    corrcoef.resize((len(x), len(x)))

    return x, sig, corrcoef

#def Elim(pmRAs,pmDEs, e_pmRA,e_pmDE, n):
#    a = np.abs(pmRAs) - n*e_pmRA
#    b = np.abs(pmDEs) - n*e_pmDE
#    indice1 = np.where(a<0)
#    indice2 = np.where(b<0)
#    indice  = np.intersect1d(indice1, indice2)
##    pmRA = np.take(pmRA, indice)
##    pmDE = np.take(pmDE, indice)
##    e_pmRA = np.take(e_pmRA, indice)
##    e_pmDE = np.take(e_pmDE, indice)
##    RA = np.take(RA, indice)
##    DE = np.take(DE, indice)
#
#    return indice
#
#def loop(pmRA,pmDE,e_pmRA,e_pmDE,RA,DE, flog):
#    w, sig, corrcoef = RotationFit(pmRA,pmDE,e_pmRA,e_pmDE,RA,DE)
#
#    print>>flog, 'the orientation/spin are(mas/mas*yr-1):\n ',w
#    print>>flog, '   sigma are(mas/mas*yr-1):\n', sig
#    print>>flog, '   correlation coefficients are:\n', corrcoef
###  Calculate the residuals
#    wx = w[0]
#    wy = w[1]
#    wz = w[2]
#
#    pmRAf = -sin(DE)*cos(RA)*wx-sin(DE)*sin(RA)*wy+cos(DE)*wz
#    pmDEf =  sin(RA)*wx-cos(RA)*wy
#
### residuals
#    pmRAs = pmRAf - pmRA
#    pmDEs = pmDEf - pmDE
#
### generate the new array after eliminating outliers
#    n = 2.6
#    indice = Elim(pmRAs,pmDEs, e_pmRA,e_pmDE, n)
#    npmRA = np.take(pmRA, indice)
#    npmDE = np.take(pmDE, indice)
#    ne_pmRA = np.take(e_pmRA, indice)
#    ne_pmDE = np.take(e_pmDE, indice)
#    nRA = np.take(RA, indice)
#    nDE = np.take(DE, indice)
#
#    print>>flog, 'Eliminating(%2.1f-sigma): %d Outliers.'%(n,len(pmRA)-len(npmRA))
#
#    w, sig, corrcoef = RotationFit(npmRA,npmDE,ne_pmRA,ne_pmDE,nRA,nDE)

###  Calculate the residuals again
#    wx = w[0]
#    wy = w[1]
#    wz = w[2]
#
#    npmRAf = -sin(nDE)*cos(nRA)*wx-sin(nDE)*sin(nRA)*wy+cos(nDE)*wz
#    npmDEf =  sin(nRA)*wx-cos(nRA)*wy
#
### residuals
#    npmRAs = npmRAf - npmRA
#    npmDEs = npmDEf - npmDE
#
##    res = np.hstack((npmRAs/ne_pmRA**2, npmDEs/ne_pmDE**2))
#    wrmsRA = np.sqrt(np.sum(npmRAs**2/ne_pmRA**2)/np.sum(ne_pmRA**-2))
#    wrmsDE = np.sqrt(np.sum(npmDEs**2/ne_pmDE**2)/np.sum(ne_pmDE**-2))
#
#    print>>flog, 'After eliminating outliers, the orientation/spin are(mas/mas*yr-1):\n ',w
#    print>>flog, '   sigma are(mas/mas*yr-1):\n', sig
#    print>>flog, '   correlation coefficients are:\n', corrcoef
#    print>>flog, '   w.r.m.s(mas/mas*yr-1) is:\n', wrmsRA, wrmsDE
#
#    return w, sig, corrcoef, wrmsRA, wrmsDE
#
#def SpinFit(pmRA,pmDE,e_pmRA,e_pmDE,RA,DE, flog):
####  First Loop, calculate the mean error without weights.
#    np.ones(len(pmRA))
#    print>>flog, 'First, no weight apply to the data. Calculate the w.r.m.s'
#    w, sig, corrcoef, wrmsRA, wrmsDE = loop(pmRA,pmDE,np.ones(len(pmRA)),np.ones(len(pmDE)),RA,DE, flog)
#    merrRA, merrDE = wrmsRA, wrmsDE
#
###  Next, apply the weigths of M_err**2/err_i**2
#    print>>flog, 'Next, apply the weigths of M_err**2/err_i**2'
#    w, sig, corrcoef, wrmsRA, wrmsDE = loop(pmRA,pmDE,e_pmRA/merrRA,e_pmDE/merrDE,RA,DE, flog)

###############################################################################
## Main function


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

# Loading the libraries
import requests
from bs4 import BeautifulSoup
import time
import random
from tqdm.notebook import tqdm as tqdm

# Part a
page_url = "https://www.barnesandnoble.com/b/books/_/N-1fZ29Z8q8?Nrpp=40&page=1"

headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"}

search_page = requests.get(page_url, headers=headers)
page_info = BeautifulSoup(search_page.content, "html.parser")

# Part b
url_prefix = "https://www.barnesandnoble.com"
list_product_header = page_info.find_all("h3", class_ = "product-info-title")

list_product_urls = []
product_dict = dict()

for i, product in enumerate(list_product_header):

    product_url = url_prefix + product.find("a")['href']
    list_product_urls = list_product_urls + [product_url]

    product_name = product.find("a").text
    product_dict[i+1] = product_name

# Part c
base_fname = "top100_bn_"

for i, product_url in enumerate(list_product_urls):
    product_search = requests.get(product_url, headers=headers)

    fname = f"{base_fname}_{i+1}.html"
    with open(fname,"a+") as f:
        f.write(str(product_search.content))
    f.close()

    # Adding sleep time
    sleep_time = random.randint(5,10)
    time.sleep(sleep_time)

# Part d
prod_count = len(list_product_header)

for i in range(prod_count):
    fname = f"{base_fname}_{i+1}.html"

    with open(fname, "r") as f:
        page_content = BeautifulSoup(f, "html.parser")
    f.close()

    overview_box = page_content.find("div", class_ = "content overview-expandable-section")
    overview_content = overview_box.find("div", class_ = "overview-cntnt")
    print(f"Overview content for '{product_dict[i+1]}'")
    print(overview_content.text[:100])
    print("")


class MiddleoftheLinkedList(object):
    def middleNode(self, head):
        A = [head]
        while A[-1].next:
            A.append(A[-1].next)
        return A[len(A) // 2]

class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None
if __name__ == '__main__':
    a = MiddleoftheLinkedList()
    h1 = ListNode(1)
    h2 = ListNode(2)
    h3 = ListNode(3)
    h4 = ListNode(4)
    h5 = ListNode(5)
    h6 = ListNode(6)
    h1.next = h2
    h2.next = h3
    h3.next = h4
    h4.next = h5
    h5.next = h6
    print(a.middleNode(h1).val)
    print(a.middleNode(h2).val)
    print(a.middleNode(h3).val)
    print(a.middleNode(h4).val)


list = []
dataIn = None

def printLowHigh(list):
    high = list[0]
    low = list[0]
    for i in range(len(list)):
        if i < low:
            low = list[i]
        if i > high:
            high = list[i]
    print (low, high)

def Promedio(list):
    suma = 0
    for i in range(len(list)):
        suma = suma + list[i]
    promedio = suma / len(list)
    return promedio

while True:
    dataIn=int(input("ingrese el valor "))
    if dataIn == -1:
        break
    list.append(int(dataIn))

printLowHigh(list)
print (Promedio(list))


# This Python code reproduces the upper and low panel of Fig. 6 in Clay et. al. (2008).

#Save the voltage nd time series csv files as v1.csv for the standard HH model (top panel of fig.6 and v2.csv for the revised model (bottom panel for of fig. 6)

from neuron import h
import numpy as np
import matplotlib.pyplot as plt
import timeit
import subprocess
import math

def initialize():
	h.finitialize()
	h.fcurrent()
def integrate():
	#g.begin()

	h.finitialize()
	while h.t<tstop:
		h.fadvance()

cell=h.Section()

nseg=9
cell.nseg=nseg   # number of segments
cell.Ra=35.4 # ohm*cm  # cable resistance
cell.cm=1

l=1# length of the axon in mm
cell.L=l*1000  # length of the axon in um to be read into NEURON
cell.diam=500 # diameter of the axon in um

#insert the mechanism

#cell.insert('kext_clay') #in case the potassium accumulation is used.
cell.insert('hh') #inserting  Clay revised HH model
#cell.insert('hh') # Standard Hodgkin Huxley model
cell.ek = -72
cell.ena = 55

#Stimulation current
stim1=h.IClamp(0,sec=cell)
stim1.delay=100 #ms
stim1.dur=80 #ms
stim1.amp= 250 #nA

#print stim_density * 1000 * area

vec={}
for var in 'i','t','v':
	vec[var]=h.Vector()

vec['t'].record(h._ref_t)

vec['v'].record(cell(0.99)._ref_v)

vec['i'].record(stim1._ref_i)

tstop=200
h.dt=0.01

initialize()
integrate()

np.savetxt('v1.csv', vec['v'], delimiter= ',')
np.savetxt('time.csv', vec['t'], delimiter= ',') # saving the time series

cell2=h.Section()

nseg=9
cell2.nseg=nseg   # number of segments
cell2.Ra=35.4 # ohm*cm  # cable resistance
cell2.cm=1

l=1# length of the axon in mm
cell2.L=l*1000  # length of the axon in um to be read into NEURON
cell2.diam=500 # diameter of the axon in um

#insert the mechanism

cell2.insert('hhrx_clay_2') #inserting  Clay revised HH model

cell2.ek = -72
cell2.ena = 55

vec['v2'] = h.Vector()
vec['v2'].record(cell2(0.99)._ref_v)

#Stimulation current
stim1=h.IClamp(0,sec=cell2)
stim1.delay=100 #ms
stim1.dur=80 #ms
stim1.amp= 250 #nA

tstop=200
h.dt=0.01

initialize()
integrate()

np.savetxt('v2.csv', vec['v2'], delimiter= ',')

## code for plotting the results

v1 = np.genfromtxt('v1.csv',delimiter=',')
v2 = np.genfromtxt('v2.csv',delimiter=',')
time = np.genfromtxt('time.csv', delimiter= ',')

fig = plt.figure()
ax = fig.add_subplot(2,1,1)
plt.plot(time,v1)
plt.xlabel( 'Time (ms)')
plt.ylabel(' Voltage (mV)')
plt.text(140,20, 'HH', fontsize = 12)
plt.xlim(80,200)
ax.set_xticklabels([])
ax.set_xticks([])
ax.set_yticklabels([])
ax.set_yticks([])
plt.ylim(-75,60)
plt.plot((100,180), (50,50), color = 'k', linewidth = 2)
plt.plot((185,185), (-50,0), color = 'k', linewidth = 2)
plt.text(187,-50, '-50', fontsize = 12)
plt.text(187,0, '0 mV', fontsize = 12)

ax = fig.add_subplot(2,1,2)
plt.plot(time,v2)
plt.xlim(80,200)
plt.xlabel( 'Time (ms)')
plt.ylabel(' Voltage (mV)')
plt.text(140,20, 'Clay, et. al. (2008)', fontsize = 12)
ax.set_xticklabels([])
ax.set_xticks([])
ax.set_yticklabels([])
ax.set_yticks([])
plt.ylim(-75,60)
plt.plot((185,185), (-50,0), color = 'k', linewidth = 2)
plt.plot((125,175), (0,0), color = 'k', linewidth = 2)
plt.text(187,-50, '-50', fontsize = 12)
plt.text(187,0, '0 mV', fontsize = 12)
plt.text(145,-15, '50 ms', fontsize = 12)

try:
  plt.savefig('clay_mohit.jpeg',dpi=600, format='jpeg', bbox_inches='tight')
except:
  plt.savefig('clay_mohit.jpeg',dpi=600, format='jpeg') # incase bbox_inches failes

plt.show()


import argparse

import modelsim_utils

import time

parser = argparse.ArgumentParser()
parser.add_argument('-d', '--do_file_name'               , default = 'run_cmd.do')
parser.add_argument('-r', '--run_to_pane_shift_sleep_sec', default = 4) # 7
parser.add_argument('-t','--true_or_false_flag_example', action='store_true') # true if add flag to cmd line, false if don't
args = parser.parse_args()

time.sleep(1)
modelsim_utils.auto_run(args.do_file_name, int(args.run_to_pane_shift_sleep_sec))


# @Author : tony
# @Date   : 2021/5/2
# @Title  : epjb2009 paper practice
# @Dec    : deal with the dataset

import networkx as nx

# deal with the INT dataset
def readINT(dataUrl):
    G = nx.read_gml(dataUrl)
    list = dict()
    edge_list = []
    for id, label in enumerate(G.nodes()):
        list[int(label)] = int(id)
    for (v0, v1) in G.edges:
        print(list[int(v0)], list[int(v1)])
        edge_list.append([list[int(v0)], list[int(v1)]])
    return edge_list

# deal with the INT dataset
def readPB(dataUrl):
    G = nx.read_gml(dataUrl)
    list = dict()
    edge_list = []
    for id, label in enumerate(G.nodes()):
        list[label] = int(id)
        print(id, label)
    for (v0, v1) in G.edges:
        print(v0, v1)
        print(list[v0], list[v1])
        edge_list.append([list[v0], list[v1]])
    return edge_list

# deal with the Grid dataset
def readGrid(dataUrl):
    G = nx.read_gml(dataUrl, label='id')
    list = dict()
    edge_list = []
    for id, label in enumerate(G.nodes()):
        list[int(label)] = int(id)
        print(id, label)
    for (v0, v1) in G.edges:
        print(v0, v1)
        print(list[v0], list[v1])
        edge_list.append([list[v0], list[v1]])
    return edge_list

# save the txt
def save(edgeIdList, fileName):
    f = open(fileName, 'w')
    temp = ''
    for item in edgeIdList:
        temp += str(item[0]) + ' ' + str(item[1])
        temp += '\n'
    f.write(temp)
    f.close()

if __name__ == '__main__':
    # print('------------- SRART Internet-------------')
    # edge_list = readINT('./data gml/INT.gml')
    # save(edge_list, './data gml/Internet.txt')
    # print('------------- Internet　END -------------')

    # print('------------- SRART Political blogs-------------')
    # edge_list = readPB('./data gml/PB.gml')
    # print(edge_list)
    # save(edge_list, './data gml/Political blogs.txt')
    # print('------------- Political blogs　END -------------')

    print('------------- SRART Power grid-------------')
    edge_list = readGrid('./data gml/Grid.gml')
    print(edge_list)
    save(edge_list, 'data gml/Power grid.txt')
    print('------------- Power grid　END -------------')


import unittest
import pytest

from cupy_backends.cuda import stream as stream_module
import cupy
from cupy import _core
from cupy import testing

# TODO(leofang): test PTDS in this file

class DummyObjectWithCudaArrayInterface(object):

    def __init__(self, a, ver=3):
        self.a = a
        self.ver = ver

    @property
    def __cuda_array_interface__(self):
        desc = {
            'shape': self.a.shape,
            'strides': self.a.strides,
            'typestr': self.a.dtype.str,
            'descr': self.a.dtype.descr,
            'data': (self.a.data.ptr, False),
            'version': self.ver,
        }
        if self.ver == 3:
            stream = cupy.cuda.get_current_stream()
            desc['stream'] = 1 if stream.ptr == 0 else stream.ptr
        return desc

@testing.parameterize(*testing.product({
    'stream': ('null', 'new'),
    'ver': (2, 3),
}))
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestArrayUfunc(unittest.TestCase):

    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()

    @testing.for_all_dtypes_combination(names=['x_type', 'y_type'])
    @testing.numpy_cupy_allclose(rtol=1e-6, accept_error=TypeError,
                                 contiguous_check=False)
    def check_array_scalar_op(self, op, xp, x_type, y_type, trans=False):
        a = xp.array([[1, 2, 3], [4, 5, 6]], x_type)
        if trans:
            a = a.T

        if xp is cupy:
            with self.stream:
                a = DummyObjectWithCudaArrayInterface(a, self.ver)
                return getattr(xp, op)(a, y_type(3))
        else:
            return getattr(xp, op)(a, y_type(3))

    def test_add_scalar(self):
        self.check_array_scalar_op('add')

    def test_add_scalar_with_strides(self):
        self.check_array_scalar_op('add', trans=True)

@testing.parameterize(*testing.product({
    'stream': ('null', 'new'),
    'ver': (2, 3),
}))
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestElementwiseKernel(unittest.TestCase):

    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()

    @testing.for_all_dtypes_combination()
    @testing.numpy_cupy_allclose(rtol=1e-6, accept_error=TypeError,
                                 contiguous_check=False)
    def check_array_scalar_op(self, op, xp, dtyes, trans=False):
        a = xp.array([[1, 2, 3], [4, 5, 6]], dtyes)
        if trans:
            a = a.T

        if xp is cupy:
            with self.stream:
                a = DummyObjectWithCudaArrayInterface(a, self.ver)
                f = cupy.ElementwiseKernel('T x, T y', 'T z', 'z = x + y')
                return f(a, dtyes(3))
        else:
            return a + dtyes(3)

    def test_add_scalar(self):
        self.check_array_scalar_op('add')

    def test_add_scalar_with_strides(self):
        self.check_array_scalar_op('add', trans=True)

@testing.parameterize(*testing.product({
    'stream': ('null', 'new'),
    'ver': (2, 3),
}))
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestSimpleReductionFunction(unittest.TestCase):

    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()

        self.my_int8_sum = _core.create_reduction_func(
            'my_sum', ('b->b',), ('in0', 'a + b', 'out0 = a', None))

    @testing.numpy_cupy_allclose()
    def check_int8_sum(self, shape, xp, axis=None, keepdims=False,
                       trans=False):
        a = testing.shaped_random(shape, xp, 'b')
        if trans:
            a = a.T

        if xp == cupy:
            with self.stream:
                a = DummyObjectWithCudaArrayInterface(a, self.ver)
                return self.my_int8_sum(
                    a, axis=axis, keepdims=keepdims)
        else:
            return a.sum(axis=axis, keepdims=keepdims, dtype='b')

    def test_shape(self):
        self.check_int8_sum((2 ** 10,))

    def test_shape_with_strides(self):
        self.check_int8_sum((2 ** 10, 16), trans=True)

@testing.parameterize(*testing.product({
    'stream': ('null', 'new'),
    'ver': (2, 3),
}))
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestReductionKernel(unittest.TestCase):

    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()

        self.my_sum = _core.ReductionKernel(
            'T x', 'T out', 'x', 'a + b', 'out = a', '0', 'my_sum')

    @testing.numpy_cupy_allclose()
    def check_int8_sum(self, shape, xp, axis=None, keepdims=False,
                       trans=False):
        a = testing.shaped_random(shape, xp, 'b')
        if trans:
            a = a.T

        if xp == cupy:
            with self.stream:
                a = DummyObjectWithCudaArrayInterface(a, self.ver)
                return self.my_sum(
                    a, axis=axis, keepdims=keepdims)
        else:
            return a.sum(axis=axis, keepdims=keepdims, dtype='b')

    def test_shape(self):
        self.check_int8_sum((2 ** 10,))

    def test_shape_with_strides(self):
        self.check_int8_sum((2 ** 10, 16), trans=True)

@testing.parameterize(
    {'shape': (10,), 'slices': (slice(0, None),)},
    {'shape': (10,), 'slices': (slice(2, None),)},
    {'shape': (10, 10), 'slices': (slice(0, None), slice(0, None))},
    {'shape': (10, 10), 'slices': (slice(0, None), slice(2, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(0, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(2, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(4, None))},
)
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestSlicingMemoryPointer(unittest.TestCase):

    @testing.for_all_dtypes_combination(names=['dtype'])
    @testing.for_orders('CF')
    def test_shape_with_strides(self, dtype, order):
        x = cupy.zeros(self.shape, dtype=dtype, order=order)

        start = [s.start for s in self.slices]
        itemsize = cupy.dtype(dtype).itemsize
        dimsize = [s * itemsize for s in start]
        if len(self.shape) == 1:
            offset = start[0] * itemsize
        else:
            if order == 'C':
                offset = self.shape[0] * dimsize[0] + dimsize[1]
            else:
                offset = self.shape[0] * dimsize[1] + dimsize[0]

        cai_ptr, _ = x.__cuda_array_interface__['data']
        slice_cai_ptr, _ = x[self.slices].__cuda_array_interface__['data']
        cupy_data_ptr = x.data.ptr
        sliced_cupy_data_ptr = x[self.slices].data.ptr

        assert cai_ptr == cupy_data_ptr
        assert slice_cai_ptr == sliced_cupy_data_ptr
        assert slice_cai_ptr == cai_ptr+offset

test_cases = [
    {'shape': (10,), 'slices': (slice(0, None),)},
    {'shape': (10,), 'slices': (slice(2, None),)},
    {'shape': (10, 10), 'slices': (slice(0, None), slice(0, None))},
    {'shape': (10, 10), 'slices': (slice(0, None), slice(2, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(0, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(2, None))},
    {'shape': (10, 10), 'slices': (slice(2, None), slice(4, None))},
]
test_streams = ('null', 'new')
test_cases_with_stream = [
    {'stream': s, **t} for t in test_cases for s in test_streams]

@testing.parameterize(*test_cases_with_stream)
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestCUDAArrayInterfaceCompliance(unittest.TestCase):

    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()

    @testing.for_all_dtypes_combination(names=['dtype'])
    @testing.for_orders('CF')
    def test_value_type(self, dtype, order):
        x = cupy.zeros(self.shape, dtype=dtype, order=order)
        y = x[self.slices]

        # mandatory entries
        with self.stream:
            CAI = y.__cuda_array_interface__
        shape = CAI['shape']
        typestr = CAI['typestr']
        ptr, readonly = CAI['data']
        version = CAI['version']
        strides = CAI['strides']

        # optional entries
        descr = CAI['descr'] if 'descr' in CAI else None
        stream = CAI['stream'] if 'stream' in CAI else None

        # Don't validate correctness of data here, just their types
        assert version == 3  # bump this when the protocol is updated!
        assert isinstance(CAI, dict)
        assert isinstance(shape, tuple)
        assert isinstance(typestr, str)
        assert isinstance(ptr, int)
        assert isinstance(readonly, bool)
        assert (strides is None) or isinstance(strides, tuple)
        assert (descr is None) or isinstance(descr, list)
        if isinstance(descr, list):
            for item in descr:
                assert isinstance(item, tuple)
        assert (stream is None) or isinstance(stream, int)

@testing.parameterize(*testing.product({
    'stream': ('null', 'new', 'ptds'),
}))
@pytest.mark.skipif(cupy.cuda.runtime.is_hip,
                    reason='HIP does not support this')
class TestCUDAArrayInterfaceStream(unittest.TestCase):
    def setUp(self):
        if self.stream == 'null':
            self.stream = cupy.cuda.Stream.null
        elif self.stream == 'new':
            self.stream = cupy.cuda.Stream()
        elif self.stream == 'ptds':
            self.stream = cupy.cuda.Stream.ptds

    def test_stream_export(self):
        a = cupy.empty(100)

        # the stream context should export the stream
        with self.stream:
            stream_ptr = a.__cuda_array_interface__['stream']

        if self.stream is cupy.cuda.Stream.null:
            assert stream_ptr == stream_module.get_default_stream_ptr()
        elif self.stream is cupy.cuda.Stream.ptds:
            assert stream_ptr == 2
        else:
            assert stream_ptr == self.stream.ptr

        # without a stream context, it's always the default stream
        stream_ptr = a.__cuda_array_interface__['stream']
        assert stream_ptr == stream_module.get_default_stream_ptr()


#Item 1 #############################################################################################################
import hashlib
from random import randint
def cadastrar(nome,senha):
    senhaReal = senha
    senhaHash = (hashlib.md5(senhaReal.encode('utf-8')).hexdigest())
    with open("UsuariosCadastrados.txt", "a") as stream:  # usa "w" para não armazenar mais de 1 palavra
        print(nome, senhaHash, file=stream)

def md5(senha):
    senhaNova = (hashlib.md5(senha.encode('utf-8')).hexdigest())
    return senhaNova

def autenticar(nome,senha):
    if nome in listaUsu:
        z = listaUsu.index(nome)
        if senha == listaUsu[z+1]:
            print("Autentificacao efetuada com sucesso. Bem vindo ", nome)
        else:
            print("Nome ou senha invalidos.")
    else:
        print("Nome ou senha invalidos.")
listaUsu = []
listaHash = []
a = 1
while a == 1:
    nomeCadast = input("Digite um nome (de 4 caracteres) para cadastro: ")
    senhaCadast = input("Digite uma senha (de 4 caracteres) para cadastro: ")
    ativa = 1
    if ativa ==1:
        if (len(nomeCadast) or len(senhaCadast)) >4:
            print("Nome ou Senha digitado esta fora dos limites.")
        else:
            listaUsu.append(nomeCadast)
            listaUsu.append(senhaCadast)
            senhaHash = md5(senhaCadast)
            listaHash.append(senhaHash)
            cadastrar(nomeCadast, senhaCadast)
    a = int(input("Digite (0) se quiser parar de fazer cadastros, ou (1) para continuar: "))

fazer = int(input("Digite (1) se deseja autentificar, ou (0) para sair: "))
if fazer == 1:
    nomeAutent = input("Digite seu nome para Login: ")
    senhaAutent = input("Digite sua senha para Login: ")
    autenticar(nomeAutent,senhaAutent)
print("\n")

##Item 2: quebra md5 ################################################################################################
#import hashlib
import string
import datetime
from datetime import timedelta
def quebraMd5(senha1,senha2,senha3,senha4):
    hashes = [senha1, senha2, senha3, senha4]
    startTime = datetime.datetime.now()
    tempo_comeco = datetime.datetime.now()
    x = 0
    # diminui = timedelta(seconds=1) --> SE QUISER DIMINUIR UM TEMPO DETERMINADO
    for a in string.printable:
        for b in string.printable:
            for c in string.printable:
                for d in string.printable:
                    word = a + b + c + d
                    hash = hashlib.md5(word.encode("utf-8")).hexdigest()
                    # print(str(hash))
                    if hash in hashes:
                        end_time = str(datetime.datetime.now() - startTime).split('.')[0]
                        print("Senha Hash quebrada com sucesso!!")
                        print("Senha original: ", word)
                        print("Codigo HASH: ", hash)
                        print("Tempo necessário: ", end_time)
                        print("\n")
                        startTime = datetime.datetime.now()
                        x = x + 1
                        if x >= len(hashes):
                            tempo_final = str(datetime.datetime.now() - tempo_comeco).split('.')[0]
                            print("Tempo total: ", tempo_final)
                            break

senha1 = listaHash[0]
senha2 = listaHash[1]
senha3 = listaHash[2]
senha4 = listaHash[3]
quebraMd5(senha1,senha2,senha3,senha4)

#Item 3 ##############################################################################################################
def crip(texto,chave): #pode usar numeros tbm
    aq = []
    for cont in range (len(texto)):
        if texto[cont] == (chr(32)) or (chr(97)<=texto[cont]<=chr(122)):
            if texto[cont] == " ":
                aq.append(" ")
            else:
                crip = ord(texto[cont])
                if chr(crip+chave) <= chr(122):
                    crip = chr(crip + chave)
                    aq.append(crip)
                elif chr(crip+chave) > chr(122):
                    numero = (crip + chave)
                    numero = numero - 122
                    crip = chr(96 + numero)
                    aq.append(crip)
        if chr(48)<=texto[cont]<=chr(57):
            crip = ord(texto[cont])
            if chr(crip+chave) <= chr(57):
                crip = chr(crip+chave)
                aq.append(crip)
            elif chr(crip+chave) > chr(57):
                numero = (crip+chave)
                numero = numero - 57
                crip = chr(47 + numero)
                aq.append(crip)
    aq = "".join(aq)
    return(aq)
chaveRandom1 = randint(1,9)
senhaProte1 = crip(senha1,chaveRandom1)
chaveRandom2 = randint(1,9)
senhaProte2 = crip(senha2,chaveRandom2)
chaveRandom3 = randint(1,9)
senhaProte3 = crip(senha3,chaveRandom3)
chaveRandom4 = randint(1,9)
senhaProte4 = crip(senha4,chaveRandom4)
with open("HASHSModificados.txt", "a") as stream:  # usa "w" para não armazenar mais de 1 palavra
    print(senhaProte1, senhaProte2, senhaProte3, senhaProte4, file=stream)
print("\n")
print(f"Novo Hash Protegido de {listaUsu[0]} - {senhaProte1}")
print(f"Novo Hash Protegido de {listaUsu[2]} - {senhaProte2}")
print(f"Novo Hash Protegido de {listaUsu[4]} - {senhaProte3}")
print(f"Novo Hash Protegido de {listaUsu[6]} - {senhaProte4}")


from flask_app.config.mysqlconnection import connectToMySQL

class User:
    def __init__(self, data):
        self.id = data['id']
        self.first_name = data['first_name']
        self.last_name = data['last_name']
        self.email = data['email']
        self.created_at = data['created_at']
        self.updated_at = data['updated_at']

    @classmethod
    def get_all_users(cls):
        query = "SELECT * FROM users;"
        users_from_db = connectToMySQL("users_schema").query_db(query)

        users_list = []
        for user in users_from_db:
            users_list.append(cls(user))

        return users

    @classmethod
    def get_one_user(cls, data):
        query = "SELECT * FROM users;"
        results = connectToMySQL("users_schema").query_db(query, data)

        users_obj = cls()

        return users_obj

    @classmethod
    def create(cls, data):
        query = "INSERT INTO users (first_name, last_name, email, created_at, updated_at) VALUES (%(fname)s, %(lname)s, %(email)s, NOW(), NOW());"

        users_id = connectToMySQL("users_schema").query_db(query, data)

        return users_id

    @classmethod
    def delete_user(cls, data):
        query = "DELETE FROM dogs WHERE id = %(id)s"
        connectToMySQL("users_schema").query_db(query, data)

    @classmethod
    def update_user(cls, data):
        query = "UPDATE users SET first_name = %(fname)s, last_name = %(lname)s, email = %(email)s, updated_at = NOW() WHERE id = %(id)s"
        results = connectToMySQL("users_schema").query_db(query, data)

        return results


import tensorflow as tf
from QingDaoCoRec.CoRec import input_data
import os
import csv
import time
import numpy as np

dir = 'MODEL'
mod_name = 'model'
mod_cnt = 0
mod_end = '.ckpt'
batch_size = 100

def wei_mat(shape):
    ini = tf.random.truncated_normal(shape, stddev=0.1)
    return tf.Variable(ini)

def bias_mat(shape):
    ini = tf.constant(0.1, dtype=tf.float32, shape=shape)
    return tf.Variable(ini)

def conv_1d(x_, W):
    return tf.nn.conv1d(x_, W, 1, padding='SAME')

def max_pool(x_):
    return tf.nn.max_pool2d(x_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def mean_pool(x_):
    return tf.nn.avg_pool2d(x_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def multi(x_, W):
    return tf.matmul(x_, W)

def save_model(sess, directory_name, model_name):
    # save arguments

    saver = tf.compat.v1.train.Saver()
    directory_path = os.getcwd()
    directory_path = os.path.join(directory_path, directory_name)
    if not os.path.exists(directory_name):
        os.mkdir(directory_path)
    saver.save(sess, os.path.join(directory_path, model_name))

def model():
    x = tf.compat.v1.placeholder(tf.float32, [None, 27551])
    label = tf.compat.v1.placeholder(tf.float32, [None, 2])
    fx = tf.reshape(x, [-1, 27551, 1])
    drop_rate = tf.compat.v1.placeholder(tf.float32)
    # x = tf.split(x, batch_size)

    # birnn
    # lstm_fw_cell = tf.contrib.rnn.BasicLSTMCell(36499, forget_bias=1.0)
    # lstm_bw_cell = tf.contrib.rnn.BasicLSTMCell(36499, forget_bias=1.0)
    # outputs, _, _ = tf.contrib.rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype=tf.float32)

    # rnn
    rnncell = tf.keras.layers.LSTMCell(32)
    rnnlayer = tf.keras.layers.RNN(rnncell)
    rnnop = rnnlayer(fx)

    rnnop_dropout = tf.nn.dropout(rnnop, rate=drop_rate)

    # full connect
    W_fc = wei_mat([32, 2048])
    B_fc = bias_mat([2048])
    Out_fc = tf.nn.relu(multi(rnnop_dropout, W_fc) + B_fc)

    # Full Connected Dropout
    Out_fc_dropout = tf.nn.dropout(Out_fc, rate=drop_rate)

    # Softmax->2 labels
    W_soft = wei_mat([2048, 2])
    B_soft = bias_mat([2])
    y = tf.nn.softmax(multi(Out_fc_dropout, W_soft) + B_soft)
    return x, label, y, drop_rate

def train_model(epoch=30):
    global mod_cnt, batch_size
    data = input_data.read_data_sets('train.csv')
    batch_num = int(data.size() / batch_size) + 1
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.compat.v1.InteractiveSession(config=config)
    # get model
    x, label, y, drop_rate = model()

    # cross entropy
    cross_entropy = -tf.reduce_sum(label * tf.math.log(y))
    train_step = tf.compat.v1.train.AdamOptimizer(1e-5).minimize(cross_entropy)

    # accuracy
    predict = tf.equal(tf.argmax(label, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(predict, dtype=tf.float32))

    saver = tf.compat.v1.train.Saver()
    ckpt = tf.train.get_checkpoint_state('MODEL/')
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print('Model: ' + str(ckpt.model_checkpoint_path) + ' has been restored at ' + str(time.strftime('%H:%M:%S')))
    else:
        tf.compat.v1.global_variables_initializer().run()
        print('No model to restore.')

    # training
    start = time.perf_counter()
    if os.path.exists(r'MODEL/ite.npy'):
        last = np.load(r'MODEL/ite.npy', allow_pickle=True)
    else:
        last = (0, 0)
    i, j = last[0], last[1]
    print('Last Training terminated at epoch %d , batch %d' % (i, j))
    print('Training now continue')
    while i < epoch + 1:
        while j < batch_num:
            batch = data.next_batch(batch_size)
            train_step.run(feed_dict={x: batch[0], label: batch[1], drop_rate: 0.5}, session=sess)
            # training_accuracy = accuracy.eval(feed_dict={x: batch[0], label: batch[1], drop_rate: 0}, session=sess)
            # print('epoch:%d/%d batch:%d/%d ---training accracy=%g' % (i, epoch, j, batch_num, training_accuracy))
            loss = cross_entropy.eval(feed_dict={x: batch[0], label: batch[1], drop_rate: 0}, session=sess)
            print('epoch:%d/%d batch:%d/%d ---loss=%g' % (i, epoch, j, batch_num, loss))
            if time.perf_counter() - start > 1800:
                save_model(sess, dir, mod_name + mod_end)
                start = time.perf_counter()
                print('Model saved at ' + str(time.strftime('%H:%M:%S')))
                np.save(r'MODEL/ite.npy', (i, j))
            j += 1
        j = 0
        i += 1
    save_model(sess, dir, mod_name + mod_end)
    sess.close()

def model_call(data):
    print(data.shape)
    sess = tf.compat.v1.InteractiveSession()

    # get model
    x, label, y, drop_rate = model()

    # recover checkpoint
    saver = tf.compat.v1.train.Saver()
    directory_path = os.getcwd()
    directory_path = os.path.join(directory_path, dir, mod_name + mod_end)
    saver.restore(sess, directory_path)

    # calling model

    prediction = y
    total_res = None
    for i in range(0, 9550, 50):
        print(i)
        predint = prediction.eval(feed_dict={x: data[i:i + 50], drop_rate: 0}, session=sess)
        res = predint.T
        if i == 0:
            total_res = res
        else:
            total_res = np.concatenate((total_res, res), axis=-1)
    predint = prediction.eval(feed_dict={x: data[9550:], drop_rate: 0}, session=sess)
    res = predint.T
    total_res = np.concatenate((total_res, res), axis=-1)
    np.save('res.npy', total_res)
    with open('r.csv', 'w', newline='') as file:
        w = csv.writer(file)
        for i in total_res[1]:
            w.writerow([i])

if __name__ == "__main__":
    with tf.device("/cpu:0"):
        train_model()
        # a = pd.read_csv('test.csv')
        # c = [r for r in a]
        # data = a[c[1:-2]].values
        # model_call(data)


""" клиентская часть """

import sys
import json
import time
import re
import logging
import logs.config_client_log
from lib.variables import ACTION, PRESENCE, TIME, USER, ACCOUNT_NAME, RESPONSE, AUTH, ALERT, MSG, ERR200, ERR400, \
    CLIENT_LISTEN, LISTEN, SENDER, MSG, MSG_TEXT, ERROR
from lib.utils import create_socket, server_settings, get_message, send_message
from lib.errors import ReqFieldMissingError, ServerError
from logs.decoration_log import log

CLIENT_LOGGER = logging.getLogger('client')

@log
def message_from_server(message):
    """Функция - обработчик сообщений других пользователей, поступающих с сервера"""
    if ACTION in message and message[ACTION] == MSG and \
            SENDER in message and MSG_TEXT in message:
        print(f'Получено сообщение от пользователя {message[SENDER]}:\n{message[MSG_TEXT]}')
        CLIENT_LOGGER.info(f'Получено сообщение от пользователя {message[SENDER]}:\n{message[MSG_TEXT]}')
    else:
        CLIENT_LOGGER.error(f'Получено некорректное сообщение с сервера: {message}')

@log
def create_message(sock, account_name='Guest'):
    """Функция запрашивает текст сообщения и возвращает его.
    Так же завершает работу при вводе подобной комманды
    """
    message = input('Введите сообщение для отправки или \'exit\' для завершения работы: ')
    if message.lower() == 'exit':
        sock.close()
        CLIENT_LOGGER.info('Завершение работы по команде пользователя.')
        sys.exit(0)
    message_dict = {ACTION: MSG,TIME: time.time(),ACCOUNT_NAME: account_name,MSG_TEXT: message}
    CLIENT_LOGGER.debug(f'Сформирован словарь сообщения: {message_dict}')
    return message_dict

@log
def create_presence(account_name='Guest'):
    '''
    Функция генерирует запрос о присутствии клиента
    :param account_name:
    :return:
    '''
    # {'action': 'presence', 'time': 1573760672.167031, 'user': {'account_name': 'Guest'}}
    out = {ACTION: PRESENCE, TIME: time.time(), USER: {ACCOUNT_NAME: account_name}}
    CLIENT_LOGGER.debug(f'Сформировано {PRESENCE} сообщение для пользователя {account_name}')
    return out

@log
def get_user():
    """
    функция возвращает имя пользователя
    :return:
    """
    while True:
        account = input("введите имя пользователя >>>")
        if not re.match(r"[A-Za-z]", account) or len(account) > 25 or len(account) < 3:
            CLIENT_LOGGER.error(f"недопустимое имя пользователя: {account}")
            print("Имя пользователя должно быть от 3 до 25 латинских символов")
        elif account.lower().strip() == 'guest':
            CLIENT_LOGGER.error(f"недопустимое имя пользователя: {account}")
            print("Недоспустимое имя пользователя")
        else:
            break
    return account

@log
def create_action(account_name, action, msg=None):
    '''
    Функция отдает словарь с текстом сообщения
    :param account_name:
    :return:
    '''
    # {'action': 'presence', 'time': 1573760672.167031, 'user': {'account_name': 'Guest'}}
    out = {ACTION: action, TIME: time.time(), USER: {ACCOUNT_NAME: account_name}, MSG: msg}
    CLIENT_LOGGER.debug(f'Сформировано {ACTION} сообщение для пользователя {account_name}')
    return out

@log
def process_handler(message):
    '''
    Функция разбирает ответ сервера
    :param message:
    :return:
    '''
    CLIENT_LOGGER.debug(f'Разбор приветственного сообщения от сервера: {message}')
    print(f'Разбор приветственного сообщения от сервера: {message}')
    if RESPONSE in message:
        if message[RESPONSE]==200: #message[RESPONSE]==200:
            CLIENT_LOGGER.debug(f"{message[RESPONSE]} содержит {ERR200}")
            return message[MSG] #ERR200
        elif message[RESPONSE]==ERR400: #message[RESPONSE]==400:
            CLIENT_LOGGER.debug(f"{message[RESPONSE]} содержит {ERR400}")
            raise ServerError(f"{ERR400}: {message[ERROR]}")
    raise ReqFieldMissingError(RESPONSE)

@log
def start_client():
    srv_settings = server_settings()
    server_address = srv_settings[0]
    server_port = srv_settings[1]
    client_listen = srv_settings[2]

    print(f"start client on: {server_address}:{server_port} | listen_mode={client_listen}")
    CLIENT_LOGGER.info(f"client started {server_address}:{server_port} | listen_mode={client_listen}")

    try:
        transport = create_socket()
        transport.connect((server_address, server_port))
        send_message(transport, create_presence())
        answer = process_handler(get_message(transport))
        CLIENT_LOGGER.info(f"соединение с сервером {server_address}:{server_port}. Ответ: {answer}")
        print(f"соединение с сервером {server_address}:{server_port}. Ответ: {answer}")

# авторизация
        account_name = get_user()
        CLIENT_LOGGER.info(f"Guest авторизовался как {account_name}")
        CLIENT_LOGGER.debug(f"отправка {AUTH} сообщения на сервер {server_address}:{server_port} от user={account_name}")
        message_to_server = create_action(account_name, action=AUTH, msg=None)
        send_message(transport, message_to_server)
        try:
            answer = process_handler(get_message(transport))
            print(answer)
        except (ValueError, json.JSONDecodeError):
            print(answer)
            CLIENT_LOGGER.error(f"{ERR400}. Не удалось декодировать сообшение от сервера")
            print(f"{ERR400}. Не удалось декодировать сообшение от сервера")

    except json.JSONDecodeError:
        CLIENT_LOGGER.error(f"не удалось декодировать JSON-строку")
        print(f"не удалось декодировать JSON-строку")
        sys.exit(1)
    except ServerError as error:
        CLIENT_LOGGER.error(f"ошибка при установке соединения: {error.text}")
        print(f"ошибка при установке соединения: {error.text}")
        sys.exit(1)
    except ReqFieldMissingError as missing_error:
        CLIENT_LOGGER.error(f"в ответе сервера нет обязательного поля {missing_error.missing_field}")
        sys.exit(1)
    except ConnectionRefusedError:
        CLIENT_LOGGER.critical(f"Не удалось подключиться к серверу {server_address}:{server_port}")
        sys.exit(1)
    else:
        print(f"клиент - в режиме client_listen={client_listen:}")
    while True:
        if not client_listen:
            try:
                send_message(transport, create_message(transport))
            except (ConnectionResetError, ConnectionError, ConnectionAbortedError):
                CLIENT_LOGGER.error(f"соединение с сервером {server_address}:{server_port} потеряно")
                print(f"соединение с сервером {server_address}:{server_port} потеряно")
                sys.exit(1)
        if client_listen:
            try:
                message_from_server(get_message(transport))
            except (ConnectionResetError, ConnectionError, ConnectionAbortedError):
                CLIENT_LOGGER.error(f"соединение с сервером {server_address}:{server_port} потеряно")
                print(f"соединение с сервером {server_address}:{server_port} потеряно")
                sys.exit(1)

if __name__ == '__main__':
    start_client()


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # add up the difference between all local valleys and peaks
        profit = 0
        for i in range(1, len(prices)):
            prev = prices[i-1]
            current = prices[i]

            if current > prev:
                profit += current - prev

        return profit