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

# In[50]:

# From "data_read.py"
from netCDF4 import Dataset, num2date
import numpy as np
import numpy.ma as ma
from mpl_toolkits.basemap import Basemap, maskoceans
import matplotlib.pyplot as plt

def read_data_wind(filename): # note the change of function name (just for proper naming)
    f = Dataset(filename)  # open the first file to check the dimension of U and V
    lon = f.variables['lon'][:]
    lat = f.variables['lat'][:]
    time = f.variables['time']
    date = num2date(time[:], time.units)
    # u = f.variables['U'][:]
    # v = f.variables['V'][:]
    # speed = f.variables['speed'][:]
    sample_size = f.variables['MISR_sample_size'][:] # note the addition of this line to get the sample_size masked array
    cth_sample_size = f.variables['MISR_CTH_sample_size'][:] # note the addition of this line
    ar_shape = f.variables['AR_shape'][:]
    misr_u_at_cth = f.variables['MISR_U_at_CTH'][:]
    misr_v_at_cth = f.variables['MISR_V_at_CTH'][:]
    misr_cth = f.variables['MISR_CTH'][:]
    merra2_u = f.variables['MERRA2_U'][:]   # level: 3-5 km
    merra2_v = f.variables['MERRA2_V'][:]
    return lon, lat, date, sample_size, cth_sample_size, ar_shape, misr_u_at_cth, misr_v_at_cth, misr_cth, merra2_u, merra2_v

# Spatial Average
def calc_area_weighted_spatial_average(data, lon, lat, masking = 'mask_off', area_weight=True):
    '''Calculate area weighted average of the values in data
    :param data: two-dimensional masked array
    :type dataset: :class:`numpy.ma.core.MaskedArray`
    :returns: an area weighted mean value
    '''

    if lat.ndim == 1:
        lons, lats = np.meshgrid(lon, lat)
    else:
        lats = lat
    weights = np.cos(lats * np.pi / 180.)

    if masking == 'mask_ocean':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        data = masked_data
    if masking == 'mask_land':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        masked_data.mask = ~masked_data.mask # 'inverting' the mask to instead mask land
        data = masked_data

    if area_weight:
        spatial_average = ma.average(
            data[:], weights=weights)
    else:
        spatial_average = ma.average(data)

    return spatial_average

def calc_area_weighted_standard_deviation(data, lon, lat, masking='mask_off', area_weight=True):
    if lat.ndim == 1:
        lons, lats = np.meshgrid(lon, lat)
    else:
        lats = lat
    weights = np.cos(lats * np.pi / 180.)

    if masking == 'mask_ocean':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        data = masked_data
    if masking == 'mask_land':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        masked_data.mask = ~masked_data.mask # 'inverting' the mask to instead mask land
        data = masked_data

    squared_data = data[:]*data[:]
    if area_weight:
        spatial_average = ma.average(data[:], weights=weights)
        squared_data_spatial_average = ma.average(squared_data, weights=weights)
    else:
        spatial_average = ma.average(data)
        squared_data_spatial_average = ma.average(squared_data)
    standard_deviation = np.sqrt(squared_data_spatial_average-(spatial_average * spatial_average))

    return standard_deviation

# Significance Tests
## Pearson Correlation Coefficient
def pearson_correlation(data1, data2, lon, lat, masking='mask_off', area_weight=True):
    '''This function calculated the Pearson Correlation
    Coefficient between two datasets, data1 and data2. Masking
    and weights can be specified'''
    # Calculate data averages and standard deviations
    spatial_average1 = calc_area_weighted_spatial_average(data1, lon, lat, masking, area_weight)
    spatial_average2 = calc_area_weighted_spatial_average(data2, lon, lat, masking, area_weight)
    standard_deviation1 = calc_area_weighted_standard_deviation(data1, lon, lat, masking, area_weight)
    standard_deviation2 = calc_area_weighted_standard_deviation(data1, lon, lat, masking, area_weight)
    # Difference from Mean Datasets
    mean_diff_data1 = data1 - spatial_average1
    mean_diff_data2 = data2 - spatial_average2
    combined_data = mean_diff_data1 * mean_diff_data2
    average_mean_diff_product = calc_area_weighted_spatial_average(combined_data, lon, lat, masking, area_weight)
    # Calculate the Correlation
    pearson_correlation_coefficient = average_mean_diff_product / (standard_deviation1 * standard_deviation2)

    return pearson_correlation_coefficient

## Chi-squared Test Statistic
def chi_squared_statistic(data, modelData, lon, lat, masking='mask_off'):
    '''This function calculates the Chi-Squared Statistic
    for the goodness of fit between data and modelData. Each
    grid space is assumed to be a degree of freedom. This
    means the total number of degrees of freedom for the chi-
    squared distribution is (lon * lat)'''

    if masking == 'mask_ocean':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        masked_model_data = maskoceans(lons,lats,modelData)
        data = masked_data
        modelData = masked_model_data
    if masking == 'mask_land':
        masked_data = maskoceans(lons,lats,data) # masking oceans
        masked_data.mask = ~masked_data.mask # 'inverting' the mask to instead mask land
        masked_model_data = maskoceans(lons,lats,modelData)
        masked_model_data.mask = ~masked_model_data.mask
        data = masked_data
        modelData = masked_model_data
    scaled_squared_diff = ((data - modelData) * (data - modelData)) / modelData
    chi_squared = np.sum(scaled_squared_diff)
    #print('Number of degrees of freedom are',(lon * lat))

    return chi_squared

# Line Plotting
def line_plot(x,y,label_num):
    fig = plt.figure(figsize=(11,8))
    ax = fig.add_subplot(1,1,1)
    ax.plot(x,y,label=label_num)
    plt.savefig('correlation'+str(label_num)+'.png')

# In[8]:

lon, lat, date, sample_size, cth_sample_size, ar_shape, misr_u_at_cth, misr_v_at_cth, misr_cth, merra2_u, merra2_v = read_data_wind('West_Coast_AR_and_Wind_18UTC_daily_NOV-APR_2000-2017.nc')

# In[9]:

misr_cth_speed = np.sqrt((misr_u_at_cth * misr_u_at_cth)+(misr_v_at_cth * misr_v_at_cth))
merra2_speed = np.sqrt((merra2_u * merra2_u)+(merra2_v * merra2_v))

# In[25]:

chi_squared_statistic(misr_cth_speed[500,:,:],merra2_speed[500,0,:,:],lon,lat,masking='mask_off')

# In[48]:

np.shape(merra2_speed)
x = np.arange(20)
x

# In[52]:

pearson_correlation(sample_size[750,0,:,:],misr_cth_speed[750,:,:],lon,lat,area_weight=False)

# In[54]:

t_max = 30
correlations = []
time = np.arange(t_max)
for i in range(t_max):
    correlations.append(pearson_correlation(merra2_speed[i,0,:,:],misr_cth_speed[i,:,:],lon,lat,area_weight=False))
line_plot(time,correlations,1)

# In[ ]:


from string import ascii_lowercase as lowercase

def is_panagram(s):
    s = s.lower()
    d = dict()

    for c in s:
        if c not in d and c in lowercase:
            d[c] = 1

    if len(d) == 26:
        return True
    return False

x = input()

print(is_panagram(x))


# Starting with 1 and spiralling anticlockwise in the following way,
# a square spiral with side length 7 is formed.
# 37 36 35 34 33 32 31
# 38 17 16 15 14 13 30
# 39 18  5  4  3 12 29
# 40 19  6  1  2 11 28
# 41 20  7  8  9 10 27
# 42 21 22 23 24 25 26
# 43 44 45 46 47 48 49
# It is interesting to note that the odd squares lie along
# the bottom right diagonal,
# but what is more interesting is that 8 out of the 13 numbers
# lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

# If one complete new layer is wrapped around the spiral above,
# a square spiral with side length 9 will be formed.
# If this process is continued, what is the side length of the square
# spiral for which the ratio of primes along both diagonals
#     first falls below 10%?

import numpy as np
import utils
sidelengthsmin = 1
sidelengthsmax = 20000
primes = []
maxlast = 1
numdiagprimes = 0
numdiags = 1
sidelength = 2*sidelengthsmax+1
numnums = sum([4*i-4 for i in range(3, sidelength+1, 2)])+1
primes = utils.SieveOfEratosthenes(8000, primes)
for sidelength in range(sidelengthsmin, sidelengthsmax):
    sidelength = 2*sidelength+1
    numnewnums = np.arange(4*sidelength-4)+maxlast+1
    maxlast = numnewnums[-1]
    diags = [numnewnums[sidelength-2], numnewnums[2*sidelength-3],
             numnewnums[3*sidelength-4], numnewnums[-1]]
    numdiags += len(diags)
    if max(diags) > max(primes):
        numdiagprimes += len([d for d in diags if utils.isprime(d)])
    else:
        numdiagprimes += len([d for d in diags if d in primes])
    if (numdiagprimes/numdiags) < 0.1:
        print(3, sidelength)
        break


from __future__ import absolute_import, division, print_function

from ...core.card import Card, CardSlot
from ...core.domain import PowerDomain
from ...core.fabric import Fabric
from ...core.linecard import Linecard
from ...core.log import getLogger
from ...descs.led import LedColor
from ...libs.wait import waitFor

from ..eeprom import At24C512
from ..pca9541 import Pca9541
from ..plx import PlxPex8700

logging = getLogger(__name__)

class DenaliCard(Card):

   ASICS = []
   PLX_PORTS = []
   PLX_REGS = None

   def __init__(self, *args, **kwargs):
      self.scd = None
      self.pca = None
      self.eeprom = None
      self.plx = None
      self.asics = []
      self.gpio1 = None
      self.gpio2 = None
      super(DenaliCard, self).__init__(*args, **kwargs)

   def detach(self):
      if self.plx:
         self.slot.pci.detach(self.getUpstreamPort())
      super().detach()

   def getEeprom(self):
      try:
         return self.eeprom.prefdl()
      except Exception: # pylint: disable=broad-except
         logging.debug("%s: failed to read eeprom", self)
         return {}

   def getUpstreamPort(self):
      slotId = self.slot.parent.getSlotId()
      name = 'sup%d' % slotId if slotId != 0 else 'lcpu'
      return self.plx.pci.portByName(name)

   def createGpio1(self):
      self.gpio1 = None

   def createPlx(self, parent=None):
      self.plx = self.pca.newComponent(
         PlxPex8700,
         addr=self.pca.i2cAddr(0x38),
         registerCls=self.PLX_REGS,
      )
      self.plx.addPciSwitch(
         parent,
         ports=self.PLX_PORTS,
      )
      if self.PLX_PORTS:
         self.slot.pci.attach(self.getUpstreamPort())

   def createAsics(self):
      self.asics = []

   def createScd(self):
      self.scd = None

   def controlPlaneOn(self):
      return False

   def dataPlaneOn(self):
      return False

   def createStandbyDpm(self):
      '''Override in child classes if a linecard has a standby DPM.'''
      pass

   def standbyCommon(self):
      '''Define Mux, Prefdl eeprom, Gpio1, Dpm, Pols, Temp sensors,
         and Fans...
      '''
      self.standby = self.newComponent(PowerDomain)

      self.pca = self.standby.newComponent(Pca9541, addr=self.slot.bus.i2cAddr(0x77),
                                           driverMode='user')
      self.eeprom = self.pca.newComponent(At24C512, addr=self.pca.i2cAddr(0x50),
                                          label='card_%d' % self.slot.slotId)
      self.createGpio1()
      if self.gpio1 is not None:
         self.gpio1.addRedGreenGpioLed('status', 'statusRed', 'statusGreen')

   def standbyDomain(self):
      pass

   def mainDomain(self):
      pass

   def controlDomain(self):
      assert self.control is None
      assert self.main is None
      self.control = self.newComponent(PowerDomain, enabled=self.controlPlaneOn)
      self.main = self.newComponent(PowerDomain, enabled=self.dataPlaneOn)
      self.createStandbyDpm()
      self.createPlx(parent=self.main)

   def loadStandbyDomain(self):
      self.standbyCommon()
      self.standbyDomain()
      if self.isDetected():
         self.controlDomain()

   def loadMainDomain(self):
      self.createScd()
      self.createAsics()
      self.mainDomain()

   def createCpu(self):
      logging.error("cpu not declared for this card")

   def loadCpuDomain(self):
      self.createCpu()
      if self.cpu:
         assert self.slot, 'cpu needs to create a slot object'
         self.loadMainDomain()

   def powerStandbyDomainIs(self, on):
      raise NotImplementedError

   def powerControlDomainIs(self, on):
      raise NotImplementedError

   def powerLcpuIs(self, on, lcpuCtx):
      raise NotImplementedError

   def powerPremainPowerDomainIs(self, on):
      '''Enable Microsemi downstream port and Plx.'''
      assert self.gpio1, "gpio1 is not created yet."
      if on:
         assert self.poweredOn(), "Card is not turned on."
         self.gpio1.pcieReset(False)
         waitFor(self.plx.smbusPing, "Can't take Plx out of reset.")
         self.setupPlx()
         self.enablePlxPcieUpstreamLink(True)
         self.getInventory().getLed('status').setColor(LedColor.AMBER)
      else:
         self.enablePlxPcieUpstreamLink(False)
         self.gpio1.pcieReset(True)
         self.getInventory().getLed('status').setColor(LedColor.OFF)

   def powerMainPowerDomainIs(self, on):
      if on:
         for asicId, asic in enumerate(self.asics):
            logging.debug('Taking asic %d on card %s out of reset', asicId, self)
            asic.resetIn()
            waitFor(asic.isInReset, "Can't have asic in reset")
            asic.resetOut()
            logging.debug('Asic %d on card %s is out of reset', asicId, self)
      else:
         for asicId, asic in enumerate(self.asics):
            logging.debug('Putting asic %d on card %s in reset', asicId, self)
            asic.resetIn()
            waitFor(asic.isInReset, "Can't have asic in reset")
            logging.debug('Asic %d on card %s is in reset', asicId, self)

      if on:
         self.slot.enablePciPort()
         # Verify asic presence
         for asicId, asic in enumerate(self.asics):
            # TODO: fixme pci addr does not exists
            self.asics[asicId].waitForIt()

   def powerOnIs(self, on, lcpuCtx=None):
      if on:
         # Make sure the port is disabled before we start. If it isn't we risk
         # triggering bogus PCI state that will result in kernel lockups later.
         self.slot.disablePciPort()
         self.powerStandbyDomainIs(True)
         self.powerControlDomainIs(True)
         self.powerPremainPowerDomainIs(True)
         if lcpuCtx:
            self.powerLcpuIs(True, lcpuCtx)
         else:
            self.powerMainPowerDomainIs(True)
         self.slot.enablePciPort()
      else:
         self.slot.disablePciPort()
         # NOTE: Wait for linux to be done processing pci hotplug events
         #       not waiting would lead to uncorrectable pci errors with a high
         #       risk of softlockups
         waitFor(lambda: not self.getUpstreamPort().reachable())
         if lcpuCtx:
            self.powerLcpuIs(False, lcpuCtx)
         else:
            self.powerMainPowerDomainIs(False)
         self.powerPremainPowerDomainIs(False)
         self.powerControlDomainIs(False)
         self.powerStandbyDomainIs(False)

   def poweredOn(self):
      if self.runningOnLcpu():
         return True
      if self.gpio1 is None:
         # Linecard is likely unsupported or not loaded
         return False
      try:
         return self.gpio1.powerGood()
      except Exception: # broad-except
         logging.debug('%s: failed to read power good', self)
         return False

   def enablePlxPcieUpstreamLink(self, bind):
      upstream = self.getUpstreamPort()
      upstream.disable()
      if bind:
         self.slot.pci.bind()
         upstream.enable()
      else:
         self.slot.pci.unbind()

   def setupPlx(self):
      self.plx.enableHotPlug()
      self.plx.setUpstreamPort(self.getUpstreamPort())
      self.plx.enableNt(False)

   def setupIdentification(self):
      self.pca.takeOwnership()
      self.pca.setup()
      self.eeprom.setup()

class DenaliCardSlot(CardSlot):

   CARD_CLS = None

   def __init__(self, parent, slotId, pci, bus, presenceGpio=None, card=None):
      super(DenaliCardSlot, self).__init__(parent, slotId)
      self.pci = pci
      self.bus = bus
      self.card = card
      self.presenceGpio = presenceGpio
      if not self.card:
         self.loadCard(self.CARD_CLS(self))

   def getPresence(self):
      if self.presenceGpio is None:
         return self.card.pca.ping()

      return self.presenceGpio.isActive()

   def getEeprom(self):
      if not self.getPresence():
         return None
      self.card.setupIdentification()
      return self.card.eeprom.prefdl()

class DenaliLinecardBase(DenaliCard, Linecard):
   pass

class DenaliFabricBase(DenaliCard, Fabric):
   pass

class DenaliLinecardSlot(DenaliCardSlot):
   CARD_CLS = DenaliLinecardBase

class DenaliFabricSlot(DenaliCardSlot):
   CARD_CLS = DenaliFabricBase


import os
import time
from collections import defaultdict

import numpy as np
import pandas as pd
import streamlit as st
import stravalib

import stravalib
from strava_overview.models import *
from strava_overview.auth import Tokens, InvalidToken, go_strava_auth

def auth(state, locations):
    ath = None
    if ath == None:
        client = stravalib.client.Client()
        url = go_strava_auth(client)
        auth = locations[0].markdown(
            f"Klink op deze [link]({url}) en geef toestemming om uw activateiten te zien."
        )
        token = locations[1].text_input("Wat is uw strava code?", value="")
        locations[2].subheader("Of login:")
        email = locations[3].text_input("Email")
        ww = locations[4].text_input("Wachtword", type="password")
        # if auth:

        if token != "":
            print("code:", token)
            try:
                id = Tokens.done(token)
                state.ath = Athlete.get_athlete(id)
                st.balloons()
                return state
            except InvalidToken:
                st.warning("De code in niet geldig.")

        if email and ww:
            state.trys += 1
            try:
                state.ath = Athlete.login(email, ww, state.trys)
                st.balloons()
                state.trys = -1
                return state
            except IncorrectPassword:
                st.warning("Het wachtwoord is incorrect.")

                if state.trys > 3:
                    sleep_time = state.trys * 10
                    st.warning(f"Te veel pogingen, wacht {sleep_time} seconden")
                    time.sleep(sleep_time)
                ww = "Wachtwoord"
            except LockedAccount:
                st.warning(
                    "Je account is geblokkeerd omdat er te veel fout wachtwoord poginingen zijn geweest."
                    + " Stuur een email naar motionnetai@gmail.com."
                )

if __name__ == "__main__":
    state = SessionState.get(trys=0)
    locations = [st.empty() for _ in range(10)]
    auth(state, locations)


#first example of exception handling mechanism
while 1==1:
    try:
        num1 = int(input("Enter 1st number"))
        num2 = int(input("Enter 2nd number"))
        result = num1/num2
        print(f"division = {result}")
        break
    except ValueError:
        print("invalid number ")
        print("only digits are allowed....")
    except ZeroDivisionError:
        print("2nd number must not be zero ")

print("Good bye...")


from random import randint

N = '0'
while not (N.isdigit() and int(N) > 0):
    N = input('Введите натуральное число: ')

N = int(N)

lst = [randint(-N, N) for i in range(N)]
indices = []

with open('file.txt', 'r') as file:
    for i in file:
        if -1 < int(i) < N:
            indices.append(int(i))

result = 1

# для проверки можно раскомментировать две строки ниже:
# print(lst)
# print(indices)

if indices:
    for i in indices:
        result *= lst[i]
    print(result)

else:
    print('Подходящих множителей нет')


from django.views import View
from django.db.models import (
    Count, OuterRef, Subquery, Case, When, F, Prefetch,
    CharField, Value, Q)
from django.http import Http404
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist

# PROJECT UTILS
from utils.generals import get_model, check_uuid

# LOCAL UTILS
from apps.beacon.utils.constant import (
    DRAFT, PUBLISHED, STATUS_CHOICES)

Chapter = get_model('beacon', 'Chapter')
ChapterRevision = get_model('beacon', 'ChapterRevision')
Explain = get_model('beacon', 'Explain')
ExplainRevision = get_model('beacon', 'ExplainRevision')
EnrollmentChapter = get_model('beacon', 'EnrollmentChapter')
EnrollmentGuide = get_model('beacon', 'EnrollmentGuide')

class ChapterDetailView(View):
    template_name = 'templates/chapter/detail.html'
    context = dict()

    def get(self, request, chapter_uuid=None):
        person = request.person
        person_pk = getattr(person, 'pk', None)
        status_choices = [item for item in STATUS_CHOICES if item[0] in [DRAFT, PUBLISHED]]

        chapter_uuid = check_uuid(uid=chapter_uuid)
        if not chapter_uuid:
            raise Http404(_("UUID invalid."))

        # ...
        # ChapterRevision objects in Subquery
        # ...
        revision_objs = ChapterRevision.objects.filter(chapter_id=OuterRef('id'))
        revision_fields = ('id', 'uuid', 'label', 'version', 'status',
                           'date_created', 'date_updated', 'description', 'changelog')

        # ...
        # Collection fro Annotate
        # ...
        draft_fields = dict()
        published_fields = dict()

        for item in revision_fields:
            draft_fields['draft_%s' % item] = Subquery(
                revision_objs.filter(status=DRAFT).order_by('-version').values(item)[:1])

            published_fields['published_%s' % item] = Subquery(
                revision_objs.filter(status=PUBLISHED).values(item)[:1])

        # ...
        # Enrollment Guide
        # ...
        enrollment_guide_obj = EnrollmentGuide.objects \
            .filter(guide_id=OuterRef('guide_id'), creator_id=person_pk)

        # ...
        # Enrollment Chapter
        # ...
        enrollment_chapter_obj = EnrollmentChapter.objects \
            .filter(chapter_id=OuterRef('id'), creator_id=person_pk)

        try:
            queryset = Chapter.objects \
                .prefetch_related(Prefetch('creator'), Prefetch('creator__user'), Prefetch('guide'),
                                  Prefetch('guide__category')) \
                .select_related('creator', 'creator__user', 'guide', 'guide__category') \
                .filter(uuid=chapter_uuid) \
                .annotate(
                    enrollment_guide_id=Subquery(enrollment_guide_obj.values('id')[:1]),
                    enrollment_chapter_id=Subquery(enrollment_chapter_obj.values('id')[:1]),
                    **draft_fields,
                    **published_fields) \
                .exclude(~Q(creator_id=person_pk), ~Q(published_status=PUBLISHED)) \
                .get()
        except ObjectDoesNotExist:
            raise Http404(_("Tidak ditemukan."))

        # Enroll!
        if queryset.enrollment_guide_id:
            # Enroll Chapter
            if not queryset.enrollment_chapter_id:
                queryset.enrollment_chapters \
                    .get_or_create(
                        creator_id=person_pk, enrollment_guide_id=queryset.enrollment_guide_id)

        # Create title
        title = queryset.draft_label
        if queryset.published_label:
            title = queryset.published_label

        # Explain List...
        revision_fields = ('id', 'uuid', 'label', 'version', 'status')
        revision_objs = ExplainRevision.objects.filter(explain_id=OuterRef('id'))

        # ...
        # Collection fro Annotate
        # ...
        draft_fields = dict()
        published_fields = dict()

        for item in revision_fields:
            draft_fields['draft_%s' % item] = Subquery(
                revision_objs.filter(status=DRAFT).order_by('-version').values(item)[:1])

            published_fields['published_%s' % item] = Subquery(
                revision_objs.filter(status=PUBLISHED).values(item)[:1])

        explain_objs = queryset.explains \
            .prefetch_related(Prefetch('creator'), Prefetch('chapter')) \
            .select_related('creator', 'chapter') \
            .annotate(
                sort_stage=Case(
                    When(stage__isnull=False, then=F('stage')),
                    default=99999),
                **draft_fields,
                **published_fields) \
            .exclude(~Q(creator_id=person_pk), ~Q(published_status=PUBLISHED)) \
            .order_by('sort_stage', '-date_created')

        self.context['person_pk'] = person_pk
        self.context['title'] = title
        self.context['chapter_uuid'] = chapter_uuid
        self.context['chapter_obj'] = queryset
        self.context['explain_objs'] = explain_objs
        self.context['guide_obj'] = queryset.guide
        self.context['status_choices'] = status_choices
        self.context['PUBLISHED'] = PUBLISHED
        self.context['DRAFT'] = DRAFT
        # self.context['res'] = ero
        return render(request, self.template_name, self.context)


#!/usr/local/bin/python3

import requests
import os, sys, json, time

# snopes crawler
class snopesCrawler:

    # initialization
    def __init__(self, save_path, type, *args):
        self.index = 1
        self.type = type
        self.save_path = save_path
        self.base = "https://www.snopes.com/fact-check/page/"
        if args:
            self.url_list = args[0]

    # save current response and increment to next
    def save_and_increment(self):
        with open(os.path.join(self.save_path, self.type + "-{:05}".format(self.index)), "w") as f:
            f.write(self.res.content.decode("utf-8"))
        self.index += 1

    # get a response
    def get(self):
        if self.type == "lists":
            if self.index > 1182:
                exit()
            self.res = requests.get(self.base + str(self.index))
        else:
            if self.index > len(self.url_list):
                exit()
            self.res = requests.get(self.url_list[self.index - 1])
        print(self.index, self.res.status_code)
        self.save_and_increment()
        #time.sleep(1) # be gentle

if __name__ == "__main__":

    # get path
    sys_path = sys.path[0]
    sep = sys_path.find("src")
    file_path = sys_path[0:sep]
    save_path = os.path.join(file_path, "data", "snopes_raw")
    if not os.path.exists(save_path):
        os.mkdir(save_path)

    # list crawler initilization
    list_path = os.path.join(file_path, "data", "snopes_raw", "url_list")
    if not os.path.exists(list_path):
        snopes = snopesCrawler(save_path, "lists")
    else:
        with open(list_path, "r") as f:
            url_list = f.read().split("\n")[:-1]
        snopes = snopesCrawler(save_path, "articles", url_list)
    while True:
        snopes.get()


#!/usr/bin/python3
# encoding: utf-8

aNum = set()

for i in range(32):
    n = str(2 ** i)
    aNum.add(''.join(sorted(n)))

class Solution:
    def reorderedPowerOf2(self, N):
        m = ''.join(sorted(str(N)))
        return m in aNum

if __name__ == '__main__':
    s = Solution()
    print(s.reorderedPowerOf2(46))


import sys
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from subprocess import call

import sqlite3

class Alumnos:
    db_name = 'database_proyecto.db'

    def __init__(self, ventana_alumno):
        self.window = ventana_alumno
        self.window.title("APLICACION")
        self.window.geometry("800x670")
        self.window.resizable(0, 0)
        self.window.config(bd=10)

        "--------------- Titulo --------------------"
        titulo = Label(ventana_alumno, text="REGISTRO DE ALUMNOS", fg="black",
                       font=("Comic Sans", 17, "bold"), pady=10).pack()

        "--------------- Frame marco --------------------"
        marco = LabelFrame(ventana_alumno, text="Datos del alumno", font=("Comic Sans", 10, "bold"), pady=5)
        marco.config(bd=2)
        marco.pack()

        "--------------- Formulario --------------------"
        label_codigo = Label(marco, text="Matricula: ", font=("Comic Sans", 10, "bold")).grid(row=0, column=0,
                                                                                sticky='s',
                                                                                padx=5, pady=8)
        self.codigo = Entry(marco, width=25)
        self.codigo.focus()
        self.codigo.grid(row=0, column=1, padx=5, pady=8)

        label_nombre = Label(marco, text="Nombre completo del alumno: ", font=("Comic Sans", 10, "bold")).grid(row=1, column=0,
                                                                                sticky='s',
                                                                                padx=5, pady=8)
        self.nombre = Entry(marco, width=25)
        self.nombre.grid(row=1, column=1, padx=5, pady=8)

        label_categoria = Label(marco, text="Carrera: ", font=("Comic Sans", 10, "bold")).grid(row=2, column=0,
                                                                                sticky='s', padx=5,
                                                                                pady=9)
        self.combo_categoria = ttk.Combobox(marco,
                                            values=["Sistemas", "Electromecanica", "Administracion", "Renovables", "Animacion"],
                                            width=22, state="readonly")
        self.combo_categoria.current(0)
        self.combo_categoria.grid(row=2, column=1, padx=5, pady=0)

        label_cantidad = Label(marco, text="Edad: ", font=("Comic Sans", 10, "bold")).grid(row=0, column=2,
                                                                                sticky='s', padx=5,
                                                                                pady=8)
        self.cantidad = Entry(marco, width=25)
        self.cantidad.grid(row=0, column=3, padx=5, pady=8)

        label_precio = Label(marco, text="Promedio: ", font=("Comic Sans", 10, "bold")).grid(row=1, column=2,
                                                                                sticky='s', padx=5,
                                                                                pady=8)
        self.precio = Entry(marco, width=25)
        self.precio.grid(row=1, column=3, padx=5, pady=8)

        label_descripcion = Label(marco, text="Descripcion: ", font=("Comic Sans", 10, "bold")).grid(row=2, column=2,
                                                                                sticky='s',
                                                                                padx=10, pady=8)
        self.descripcion = Entry(marco, width=25)
        self.descripcion.grid(row=2, column=3, padx=10, pady=8)

        "--------------- Frame botones --------------------"
        frame_botones = Frame(ventana_alumno)
        frame_botones.pack()

        "--------------- Botones --------------------"
        boton_registrar = Button(frame_botones, text="REGISTRAR", command=self.Agregar_alumno, height=2, width=10,
                                 bg="green", fg="white", font=("Comic Sans", 10, "bold")).grid(row=0, column=1, padx=10,
                                                                                pady=15)
        boton_eliminar = Button(frame_botones, text="ELIMINAR", command=self.Eliminar_alumno, height=2, width=10,bg="red", fg="white", font=("Comic Sans", 10, "bold")).grid(row=0, column=2, padx=10,pady=15)
        boton_registrarmaestros = Button(frame_botones, text="REGISTRAR MAESTROS", command=self.llamar_maestro, height=5, width=15,
                                 bg="green", fg="white", font=("Comic Sans", 10, "bold")).grid(row=0, column=3, padx=10,
                                                                                pady=15)
        boton_salir = Button(frame_botones, text="SALIR", command=self.salir_registro, height=2, width=10,
                                bg="red", fg="white", font=("Comic Sans", 10, "bold")).grid(row=0, column=4, padx=10,
                                                                                pady=15)
        "--------------- Tabla --------------------"
        self.tree = ttk.Treeview(height=13, columns=("columna1", "columna2", "columna3", "columna4", "columna5"))
        self.tree.heading("#0", text='MATRICULA', anchor=CENTER)
        self.tree.column("#0", width=90, minwidth=75, stretch=NO)

        self.tree.heading("columna1", text='NOMBRE', anchor=CENTER)
        self.tree.column("columna1", width=150, minwidth=75, stretch=NO)

        self.tree.heading("columna2", text='CARRERA', anchor=CENTER)
        self.tree.column("columna2", width=150, minwidth=75, stretch=NO)

        self.tree.heading("columna3", text='EDAD', anchor=CENTER)
        self.tree.column("columna3", width=70, minwidth=60, stretch=NO)

        self.tree.heading("columna4", text='PROMEDIO', anchor=CENTER)
        self.tree.column("columna4", width=70, minwidth=60, stretch=NO)

        self.tree.heading("columna5", text='Descripcion', anchor=CENTER)

        self.tree.pack()

        self.Obtener_alumnos()

    "--------------- CRUD --------------------"

    def Obtener_alumnos(self):
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        query = 'SELECT * FROM Productos ORDER BY Nombre desc'
        db_rows = self.Ejecutar_consulta(query)
        for row in db_rows:
            self.tree.insert("", 0, text=row[1], values=(row[2], row[3], row[4], row[5], row[6]))

    def Agregar_alumno(self):
        if self.Validar_formulario_completo():
            query = 'INSERT INTO Productos VALUES(NULL, ?, ?, ?, ?, ?, ?)'
            parameters = (
            self.codigo.get(), self.nombre.get(), self.combo_categoria.get(), self.cantidad.get(), self.precio.get(),
            self.descripcion.get())
            self.Ejecutar_consulta(query, parameters)
            messagebox.showinfo("REGISTRO EXITOSO", f'Alumno registrado: {self.nombre.get()}')
            print('REGISTRADO')
        self.Limpiar_formulario()
        self.Obtener_alumnos()

    def Eliminar_alumno(self):
        try:
            self.tree.item(self.tree.selection())['values'][0]
        except IndexError as e:
            messagebox.showerror("ERROR", "Porfavor selecciona un elemento")
            return
        dato = self.tree.item(self.tree.selection())['text']
        nombre = self.tree.item(self.tree.selection())['values'][0]
        query = "DELETE FROM Productos WHERE Matricula = ?"
        respuesta = messagebox.askquestion("ADVERTENCIA", f"¿Seguro que desea eliminar al alumno: {nombre}?")
        if respuesta == 'yes':
            self.Ejecutar_consulta(query, (dato,))
            self.Obtener_alumnos()
            messagebox.showinfo('EXITO', f'Alumno eliminado: {nombre}')
        else:
            messagebox.showerror('ERROR', f'Error al eliminar al alumno: {nombre}')

    "--------------- OTRAS FUNCIONES --------------------"

    def Ejecutar_consulta(self, query, parameters=()):
        with sqlite3.connect(self.db_name) as conexion:
            cursor = conexion.cursor()
            result = cursor.execute(query, parameters)
            conexion.commit()
        return result

    def Validar_formulario_completo(self):
        if len(self.codigo.get()) != 0 and len(self.nombre.get()) != 0 and len(self.combo_categoria.get()) != 0 and len(
                self.cantidad.get()) != 0 and len(self.precio.get()) != 0 and len(self.descripcion.get()) != 0:
            return True
        else:
            messagebox.showerror("ERROR", "Complete todos los campos del formulario")

    def Limpiar_formulario(self):
        self.codigo.delete(0, END)
        self.nombre.delete(0, END)
        self.cantidad.delete(0, END)
        self.precio.delete(0, END)
        self.descripcion.delete(0, END)

    def llamar_maestro(self):
     ventana_alumno.destroy()
     call([sys.executable,'C:/pythonProject/TAREAS 2 SEMESTRE/UNIDAD 2/Practica 5/CRUD ALUMNOS.py'])#importante cambiar la dirreccion segun donde se corresponda su computadora

    def salir_registro(self):
     ventana_alumno.destroy()

if __name__ == '__main__':
    ventana_alumno = Tk()
    application = Alumnos(ventana_alumno)
    ventana_alumno.mainloop()

TAREAS 2 SEMESTRE/UNIDAD 2/Practica 5/CRUD PRINCIPAL.py


import streamlit as st
import threading
import pandas as pd
import telebot
import json
from Utils import *
import time

hide_streamlit_style = """

            """

try:
    with open('Final/Final_Sorted_Schedule.json') as json_file1:
        SCHEDULE = json.load(json_file1)
except:
    with open('Final_Sorted_Schedule.json') as json_file1:
        SCHEDULE = json.load(json_file1)

with open("CourseList.json", "r") as json_file2:
    courses_list = json.load(json_file2)

with open("total_data.json", "r") as json_file3:
    total_data = json.load(json_file3)

try:
    with open("Instructors.json", "r") as json_file4:
        InstructorDict = json.load(json_file4)
except:
    InstructorDict = {}

# Streamlit
st.set_page_config(page_title="UC Davis Classroom Search", layout="wide", page_icon="ShreyIconS2.png")
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

menu = st.sidebar.selectbox("Mode", ["Current Classes", "Weekly Schedule", "Course Info"])

current_time = time.strftime("%I:%M:%S %p", time.localtime())
session_id = get_session_id()

if 'message_sent' not in st.session_state:
    st.session_state.message_sent = False

if menu == "Current Classes":
    P, Q, R = st.columns((1, 4, 1))
    Q.title("UC Davis Classroom Search")

    colA, colB, colC = st.columns((1, 4, 1))
    days = ["Today"] + ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    selected_day = colB.selectbox("Select Day", days)

    colz, col1, col2, zolx = st.columns((1, 2, 2, 1))

    hour_options = ["Current Time"] + [f"{hour:02d}" for hour in range(0, 24)]
    selected_hour = col1.selectbox("Select Hour", hour_options)

    if selected_hour == "Current Time":
        selected_time = "Curr"
        minute_options = ["Current"]
    else:
        minute_options = [f"{minute:02d}" for minute in range(0, 60, 10)]
    selected_minute = col2.selectbox("Select Minute", minute_options)

    if selected_day == "Today":
        selected_day = "Curr"

    if selected_hour != "Current Time":
        selected_time = int(selected_hour + selected_minute + "00")

    colX, colY, colZ = st.columns((1, 4, 1))
    halls = list(SCHEDULE.keys())
    selected_hall = colY.selectbox("Select Hall", halls)

    vacant_rooms_data, ongoing_classes_data = get_info(selected_hall, selected_day, selected_time)

    if not (selected_hall == "Academic Surge Bldg" and selected_day == "Curr"):
        checkFirst(st)
    else:
        print(selected_hall,selected_day)
        print("Same Start")

    # Log Action:
    option_selected = f"Mode: {menu} | "
    option_selected += f"Hall: {selected_hall}"
    if selected_day != "Curr":
        option_selected += f" FOR Day: {selected_day}"
    if selected_hour != "Current Time":
        option_selected += f" and Time: {selected_hour}: {selected_minute}"
    log_action(option_selected, session_id)

    if vacant_rooms_data != "Weekend":
        colY.subheader("Vacant Classrooms")
        vacant_rooms_df = pd.DataFrame(vacant_rooms_data, columns=["Room", "Next Class", "Vacant Till"])
        colY.table(vacant_rooms_df)

        colY.subheader("Ongoing Classes")
        ongoing_classes_df = pd.DataFrame(ongoing_classes_data, columns=["Room", "Class", "In Use Till"])
        colY.table(ongoing_classes_df)
    else:
        colY.write("**Weekend...**")

elif menu == "Weekly Schedule":
    checkFirst(st)
    st.title("UC Davis Classroom Search")
    buildings = SCHEDULE.keys()
    col1, col2 = st.columns(2)
    selected_building = col1.selectbox("Select Building", buildings)

    rooms = SCHEDULE[selected_building].keys()
    rooms = sort_rooms(rooms)
    selected_room = col2.selectbox("Select Room", rooms)
    data = SCHEDULE[selected_building][selected_room]

    schedule_df = createDataFrame(data)
    st.subheader(f"Schedule for {selected_building}: {selected_room}")
    st.table(schedule_df.fillna(''))

    # Log action;
    option_selected = f"Mode: {menu} | "
    option_selected += f"Hall: {selected_building}, Room: {selected_room}"
    log_action(option_selected, session_id)

elif menu == "Course Info":
    checkFirst(st)
    P, Q, R = st.columns((1, 4, 1))
    Q.title("Course Info")
    courses = ["Select"] + sorted(courses_list.keys(), reverse=True)
    courses = sorted(courses_list.keys(), reverse=True)
    selected_course = Q.selectbox("Select Course", courses)

    if selected_course != "Select":
        dataframes, lecture_infos, Name = getCourseInfo(selected_course)
        Q.subheader(" ")
        Q.subheader(f"{Name}")
        Q.write("---")  # Optional: Add a separator between groups
        Q.write("")

        sorted_lecture_infos = sorted(lecture_infos, key=lambda x: x[0])
        sorted_dataframes = [df for _, df in sorted(zip(lecture_infos, dataframes), key=lambda x: x[0][1], reverse=True)]

        for (info2print, lecInfo) in zip(sorted_dataframes, sorted_lecture_infos):

            # Q.write(f"Course information for {lecInfo[0]}:")
            Q.write(f'
Course information for {lecInfo[0]}:
', unsafe_allow_html=True)
            Q.write(f"**Lecture: {lecInfo[1]}**")
            Q.write("Discussion/lab sessions:")
            Q.table(info2print.fillna(''))
            Q.write(f"Maximum Class Size: {lecInfo[2]}")
            Q.write("---")  # Optional: Add a separator between groups

    # Log action;
    option_selected = f"Mode: {menu} | "
    option_selected += f"Course: {selected_course}"
    log_action(option_selected, session_id)

elif menu == "Instructor Schedule":
    checkFirst(st)
    st.title("Instructor Schedule")
    Instructors = sorted(list(InstructorDict.keys()))
    selected_instructor = st.selectbox("Select Instructor", Instructors)
    data = InstructorDict[selected_instructor]
    schedule_df = createDataFrame(data)
    st.subheader(f"Schedule for {selected_instructor}")
    st.table(schedule_df.fillna(''))


"""
Entradas
ChelinesA-->int-->CA
DracmasG-->int-->DG
Pe-->int-->P
Salidas
Pe-->int-->A
Fr-->int-->C
Do-->int-->D
Li-->int-->E
"""
CA=int(input("Digite los chelines austriaco: "))
DG=int(input("Digite los dracmas griegos: "))
P=int(input("Digite las pesetas: "))
#caja negra
A=(CA*956.871)/100
B=(DG*88.607)/1000
C=(B*1)/20.110
D=(P*1)/122.499
E=(P*100)/9.289
#Salidas
print("Chelines austriacos equivalen a: $","{:.0f}".format(A),"pesetas")
print("Dracmas griegos equivalen a: $","{:.0f}".format(C),"francos franceses")
print("Pesetas equivalen a: $","{:.0f}".format(D),"dolares EEUU")
print("Pesetas equivales a:  $","{:.0f}".format(E),"liras italianas")

Taller_Algoritmos/Taller estructuras de control/Punto10.py


class Atm:
    def __init__(self,cardnumber,pin):
        self.cardnumber=cardnumber
        self.pin = pin

    def check_balance(self):
        print("your balance is 50,000")

    def withdrawl(self,amount):
        newamount=50000-amount
        print("you have withdrown amount "+str(amount)+". Your remaing balance is "+str(newamount))

def main():
    card_number=input('enter your card number:')
    pin_number=input('wnter your pin:')
    new_user=Atm(card_number,pin_number)
    print("choose your activity")
    print("1.balance enquiry 2.Withdrawl")
    activity=int(input("enter activity number:"))

    if(activity==1):
        new_user.check_balance()

    elif(activity==2):
        amount=int(input("enter the amount:"))
        new_user.withdrawl(amount)

    else:
        print("enter a vaild number:")

main()


from django.db import models

class Tutor(models.Model):

    ﬁrst_name=models.CharField(max_length=20,
    help_text="Имя преподавателя", blank=False, verbose_name = "Имя")

    last_name=models.CharField(max_length=20,
    help_text="Фамилия преподавателя", blank = True, verbose_name = "Фамилия")

    biography=models.TextField(blank=True,
    help_text="Биографические сведенья", verbose_name = "Биография")

    image=models.ImageField(upload_to = 'tutor_image/',
    default='default/default_tutor_image.png', verbose_name="Портрет",
    help_text="Пристойное изображение")

    is_active=models.BooleanField(help_text="Активна ли запись",
    verbose_name = "Активность записи" )

    class Meta:
        verbose_name = "Преподаватель"
        verbose_name_plural = "Преподаватели"

    def __str__(self):
        return '{} {} with ID:{}'.format(self.last_name, self.first_name, self.pk)


from pypump.models import (PumpObject, Postable, Likeable, Shareable,
                           Commentable, Deleteable)

class Note(PumpObject, Postable, Likeable, Shareable, Commentable, Deleteable):
    """ This object represents a pump.io **note**,
    notes are used to post text (or html) messages to the pump.io network.

    :param content: (optional) Note content.
    :param display_name: (optional) Note title.

    Usage::

        >>> mynote = pump.Note(content='<b>Hello</b> world!')
        >>> mynote.send()

    """

    object_type = 'note'
    _ignore_attr = ["summary"]
    _mapping = {}

    def __init__(self,
                 content=None,
                 display_name=None,
                 **kwargs):

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

        self.content = content
        self.display_name = display_name

    def serialize(self):
        """ Converts the post to something compatible with `json.dumps` """
        data = super(Note, self).serialize()
        data.update({
            "verb": "post",
            "object": {
                "objectType": self.object_type,
                "content": self.content,
            }
        })
        if self.display_name:
            data["object"]["displayName"] = self.display_name

        return data

    def __repr__(self):
        return "<{type} by {webfinger}>".format(
            type=self.object_type.capitalize(),
            webfinger=getattr(self.author, 'webfinger', 'unknown')
        )

    def __unicode__(self):
        return u"{type} by {webfinger}".format(
            type=self.object_type,
            webfinger=getattr(self.author, 'webfinger', 'unknown')
        )


from json import JSONDecodeError
from dateutil.tz import tzlocal
from pytz import timezone, UnknownTimeZoneError
import json
from datetime import datetime
from tzlocal import get_localzone

def app(environ, start_response):
    # Request is POST
    if environ['REQUEST_METHOD'] == 'POST':
        received_data = environ['wsgi.input'].read().decode("utf-8")

        # check received_data on json format
        try:
            received_data = json.loads(received_data)
        except JSONDecodeError:
            start_response('200 OK', [('Content-Type', 'text/plain')])
            return [b'Incorrect data. Use json.dumps()']

        # data processing
        try:
            type_ = received_data['type']
        except KeyError:
            start_response('200 OK', [('Content-Type', 'text/plain')])
            return [b'Not found argument "type"']

        try:
            tz_start = received_data['tz_start']
        except KeyError:
            tz_start = None

        try:
            tz_end = received_data['tz_end']
        except KeyError:
            tz_end = None

        if tz_start:
            try:
                tz_start = timezone(tz_start)
            except UnknownTimeZoneError:
                start_response('200 OK', [('Content-Type', 'text/plain')])
                return [b'Unknown time zone tz_start']
        else:
            tz_start = get_localzone()

        if tz_end:
            try:
                tz_end = timezone(tz_end)
            except UnknownTimeZoneError:
                start_response('200 OK', [('Content-Type', 'text/plain')])
                return [b'Unknown time zone tz_end']
        else:
            tz_end = get_localzone()

        if type_ == 'date':
            answer = json.dumps({'date': datetime.now(tz=tz_start).date().isoformat(), 'tz': str(tz_start)})
        elif type_ == 'time':
            answer = json.dumps({'time': datetime.now(tz=tz_start).time().isoformat(), 'tz': str(tz_start)})
        elif type_ == 'datediff':
            d_start = datetime.now(tz=tz_start).tzinfo.localize(datetime.now())
            d_end = datetime.now(tz=tz_end).tzinfo.localize(datetime.now())

            result_diff = ''
            if d_end > d_start:
                result_diff += '-' + str(d_end - d_start)
            else:
                result_diff += str(d_start - d_end)
            answer = json.dumps({'diff': result_diff, 'tz_start': str(tz_start), 'tz_end': str(tz_end)})

        else:
            start_response('200 OK', [('Content-Type', 'text/plain')])
            return [b'Incorrect type (should: "time" or "date" or "datediff")']

        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [bytes(answer, encoding='utf-8')]

    # Request is GET
    else:
        input_timezone = environ['PATH_INFO'][1:]
        if input_timezone:
            try:
                input_timezone = timezone(input_timezone)
            except UnknownTimeZoneError:
                start_response('200 OK', [('Content-Type', 'text/plain')])
                return [b'Unknown time zone']
        else:
            input_timezone = None

        msg = 'Time '
        if input_timezone:
            msg += 'in %s:\n' % input_timezone
        else:
            msg += 'on server:\n'

        start_response('200 OK', [('Content-Type', 'text/plain')])
        return [bytes(msg + datetime.now(tz=input_timezone).time().isoformat() + '\nAdd needed timezone to the url\n'
                      , encoding='utf-8')]

if __name__ == '__main__':
    from paste import reloader
    from paste.httpserver import serve

    reloader.install()
    serve(app)


from Configuration import Config
from MaKaC.errors import MaKaCError
from MaKaC.common.logger import Logger

from MaKaC.common.logger import Logger
from MaKaC.common import timezoneUtils
from MaKaC.common.utils import OSSpecific

import os, shutil, pickle, datetime

class IndicoCache:
    """
    Used to cache some pages in Indico
    """
    _subDirName = ""

    def __init__( self, vars ):
        pass

    def getFileName( self ):
        return ""

    def lockCache( self, file, flag=True):
        global fp
        if flag:
            fp = open(file,"a")
            OSSpecific.lockFile(fp, 'LOCK_EX')
        else:
            if not fp:
                return
            OSSpecific.lockFile(fp, 'LOCK_UN')
            fp.close()
            fp = None

    def getCachePath( self ):
        path = os.path.join(Config.getInstance().getXMLCacheDir(),self._subDirName)
        if not os.path.exists(path):
            try:
                os.mkdir(path)
            except:
                pass
        return path

    def getFilePath( self ):
        return os.path.join(self.getCachePath(), self.getFileName())

    def cleanCache( self ):
        self.lockCache( self.getFilePath(), True )
        if os.path.exists( self.getFilePath() ):
            os.remove( self.getFilePath() )
        self.lockCache( self.getFilePath(), False )

    def cleanUpAllFiles( self ):
        """ removes an entire cache directory"""
        path = self.getCachePath()
        if os.path.exists(path):
            shutil.rmtree(path)

    def getCachePage( self ):
        if os.path.isfile(self.getFilePath()):
            fp = open(self.getFilePath(),"r")
            OSSpecific.lockFile(fp, 'LOCK_SH')
            page = fp.read()
            return page
        return ""

    def saveCachePage( self, page ):
        self.lockCache( self.getFilePath(), True )
        open(self.getFilePath(),"w").write( page )
        self.lockCache( self.getFilePath(), False )

class CategoryCache( IndicoCache ):
    _subDirName = "categories"

    def __init__( self, vars={} ):
        self._categId = vars.get("categId","")

    def getFileName( self ):
        return "cat-%s" % self._categId

class EventCache( IndicoCache ):
    _subDirName = "events"

    def __init__( self, vars={} ):
        self._eventId = vars.get("id","")
        self._type = vars.get("type", "")

    def getFileName( self ):
        return "eve-%s-%s" % (self._eventId, self._type)

class MultiLevelCacheEntry(object):
    """
    An entry(line) for a multilevel cache
    """

    def __init__(self):
        pass

    def getId(self):
        """
        Overloaded by subclasses
        """
        pass

    def pickle(self):
        return pickle.dumps(self)

    def setContent(self, content):
        self.content = content

    def getContent(self):
        return self.content

    @classmethod
    def unpickle(self, data):
        return pickle.loads(data)

class MultiLevelCache(object):
    """
    A multilevel cache
    """

    __entryFactory = None

    def __init__(self, cacheName):

        self.cacheName = cacheName
        cacheDir = self.getCacheDir()

        if not os.path.exists(cacheDir):
            os.makedirs(cacheDir)

    def _saveObject(self, fsPath, path, fileName, data):
        """
        Performs the actual save operation
        """

        if len(path) == 0:
            filePath = os.path.join(fsPath, fileName)
            f = open(filePath, 'wb')
            OSSpecific.lockFile(f, 'LOCK_EX')
            f.write(data)
            OSSpecific.lockFile(f, 'LOCK_UN')
            f.close()
        else:
            dirPath = os.path.join(fsPath, path[0])

            if not os.path.exists(dirPath):
                os.makedirs(dirPath)

            self._saveObject(dirPath, path[1:], fileName, data)

    def getCacheDir(self):
        """
        Returns the directory where the cache is located
        Can be overriden by subclasses
        """
        return os.path.join(Config().getInstance().getXMLCacheDir(), self.cacheName)

    def cacheObject(self, version, content, *args):
        """
        Actually puts an object into the cache
        """

        entry = self._entryFactory.create(content, *args)

        path = self._generatePath(entry)

        fileName = self._generateFileName(entry, version)

        self._saveObject(self.getCacheDir(), path, fileName, entry.pickle())

        Logger.get('cache/%s' % self.cacheName).debug(
            "Saved %s" % (os.path.join(*(path + [fileName]))))

    def loadObject(self, version, *args):
        """
        Loads an object from the cache, returning None if it doesn't exist
        or in case it is dirty (has expired)
        """

        dummyEntry = self._entryFactory.create(None, *args)

        filePath = os.path.join(*([self.getCacheDir()] +
                                  self._generatePath(dummyEntry) +
                                  [self._generateFileName(dummyEntry, version)]))

        Logger.get('cache/%s'%self.cacheName).debug("Checking %s...", filePath)
        if os.path.isfile(filePath):
            # (Possible) Cache hit!
            # check dirty state first

            f = open(filePath, 'rb')

            # Lock file
            OSSpecific.lockFile(f, 'LOCK_SH')
            data = f.read()
            OSSpecific.lockFile(f, 'LOCK_UN')
            f.close()

            obj = MultiLevelCacheEntry.unpickle(data)

            if self.isDirty(filePath, obj):
                Logger.get('cache/%s'%self.cacheName).debug("DIRTY")
                # if the file is older, report a miss
                # os.remove(filePath)
                return None
            else:
                Logger.get('cache/%s'%self.cacheName).debug("HIT")
                return obj

        else:
            Logger.get('cache/%s'%self.cacheName).debug("MISS")
            # Cache miss!
            return None

    def _generatePath(self, entry):
        """
        Generate the actual hierarchical location
        Can be overriden
        """

        return [entry.getId()[0]]

    def _generateFileName(self, entry, version):
        """
        Generate the file name
        Can be overriden
        """

        return '%s_%s' % (entry.getId(), version)

    def isDirty(self, path, object):
        """
        Overload it, in order to define whether
        the entry has expired or not
        """
        raise Exception("this method should be overloaded")


# CAT 10
# Target Report Descriptor (TRD) - (I010/020)
# Extended length.

from ClassLibrary.utils import *

class I010_020():
    def __init__(self, parent):
        self.parent = parent
        self.parent.ref_no = 'I010/020'
        self.parent.long = self.set_long()
        self.parent.length_type = 1 # 0: fixed, 1: extended, 2: repetitive, 3: compound
        self.parent.dataitem = self
        self.data = self.set_data()
        self.decoded_data = self.decode_data()

    def set_long(self):
        i = 0
        while i < len(self.parent.data_list):
            if self.parent.data_list[i] % 2 ==  0:
                break
            i += 1
        return i + 1

    def set_data(self):
        return self.parent.data_list[0:self.parent.long]

    def decode_data(self):

        bin_str = decimal_to_bin_str(self.data[0])
        TYP = bin_str[0:3]
        if TYP == '000':
            TYP = 'SSR multilateration'
        elif TYP == '001':
            TYP = 'Mode S Multilateration'
        elif TYP == '010':
            TYP = 'ADS-B'
        elif TYP == '011':
            TYP = 'PSR'
        elif TYP == '100':
            TYP = 'Magnetic Loop System'
        elif TYP == '101':
            TYP = 'HF Multilateration'
        elif TYP == '110':
            TYP = 'Not defined'
        elif TYP == '111':
            TYP = 'Other types'

        DCR = bin_str[3]
        if DCR == '0':
            DCR = 'No differential correction (ADS-B)'
        elif DCR == '1':
            DCR = 'Differential correction (ADS-B)'

        CHN = bin_str[4]
        if CHN == '0':
            CHN = 'Chain 1'
        elif CHN == '1':
            CHN = 'Chain 2'

        GBS = bin_str[5]
        if GBS == '0':
            GBS = 'Transponder Ground Bit not set'
        elif GBS == '1':
            GBS = 'Transponder Ground Bit set'

        CRT = bin_str[6]
        if CRT == '0':
            CRT = 'No Corrupted reply in multilateration'
        elif CRT == '1':
            CRT = 'Corrupted replies in multilateration'

        tuple = (TYP, DCR, CHN, GBS, CRT)
        if self.parent.long > 1:
            bin_str = decimal_to_bin_str(self.data[1])
            SIM = bin_str[0]
            if SIM == '0':
                SIM = 'Actual target report'
            elif SIM == '1':
                SIM = 'Simulated target report'

            TST = bin_str[1]
            if TST == '0':
                TST = 'Default'
            elif TST == '1':
                TST = 'Test target'

            RAB = bin_str[2]
            if RAB == '0':
                RAB = 'Report from target transponder'
            elif RAB == '1':
                RAB = 'Report from field monitor (fixed transponder)'

            LOP = bin_str[3:5]
            if LOP == '00':
                LOP = 'Undetermined'
            elif LOP == '01':
                LOP = 'Loop start'
            elif LOP == '10':
                LOP = 'Loop end'

            TOT = bin_str[5:7]
            if TOT == '00':
                TOT = 'Undetermined'
            elif TOT == '01':
                TOT = 'Aircraft'
            elif TOT == '10':
                TOT = 'Ground vehicle'
            elif TOT == '11':
                TOT = 'Helicopter'

            tuple =  (TYP, DCR, CHN, GBS, CRT, SIM, TST, RAB, LOP, TOT)
            if self.parent.long > 2:
                bin_str = decimal_to_bin_str(self.data[2])
                SPI = bin_str[0]
                if SPI == '0':
                    SPI = 'Absence of SPI'
                elif SPI == '1':
                    SPI = 'Special Position Identification'
                tuple =  (TYP, DCR, CHN, GBS, CRT, SIM, TST, RAB, LOP, TOT, SPI)
        return tuple


cod_p1, num_p1, val_p1 = input().split()
cod_p1 = int (cod_p1)
num_p1 = int (num_p1)
val_p1 = float (val_p1)

cod_p2, num_p2, val_p2 = input().split()
cod_p2 = int (cod_p2)
num_p2 = int (num_p2)
val_p2 = float (val_p2)

VALOR_TOTAL = (num_p1 * val_p1) + (num_p2 * val_p2)

print("VALOR A PAGAR: R$ %.2f" %VALOR_TOTAL)


from hype.graph import eval_reconstruction, load_adjacency_matrix
import argparse
import numpy as np
import torch
import os
from hype.lorentz import LorentzManifold
from hype.euclidean import EuclideanManifold, TranseManifold
from hype.poincare import PoincareManifold
import pickle

def get_model_info(fname):
    chkpnt = torch.load(fname)
    dset = chkpnt['conf']['dset']
    if not os.path.exists(dset):
        raise ValueError("Can't find dset!")
    data_format = 'hdf5' if dset.endswith('.h5') else 'csv'
    # dset = load_adjacency_matrix(dset, 'hdf5')
    dset = load_adjacency_matrix(dset, data_format)

    info_dict = {}
    # info_dict['dset'] = dset
    info_dict['idmap'] = dset['idmap']
    info_dict['embeddings'] = chkpnt['embeddings'].numpy()
    return info_dict

def get_vector(entity_id, info_dict):
    imap = info_dict['idmap']
    idx_obj = imap[entity_id]
    vec = info_dict['embeddings'][idx_obj, :]
    return vec

def distance(u, v, eps=1e-5):
    # Calculate the distance between two vectors in poincare space
    squnorm = np.clip(np.sum(u * u, axis=-1), 0, 1 - eps)
    sqvnorm = np.clip(np.sum(v * v, axis=-1), 0, 1 - eps)
    sqdist = np.sum(np.power(u - v, 2), axis=-1)
    x = 2 * sqdist / ((1 - squnorm) * (1 - sqvnorm)) + 1
    # arcosh calc
    tmp = np.sqrt(np.power(x, 2) - 1)
    return np.log(x + tmp)

# just an added function
def dist_norms(u, v):
    norm_u = np.linalg.norm(u, 2)
    norm_v = np.linalg.norm(v, 2)
    return (norm_u - norm_v)

def score_func_isa(u, v, alpha=1000):
    norm_u = np.linalg.norm(u, 2)
    norm_v = np.linalg.norm(v, 2)
    tmp = 1 + alpha * (norm_v - norm_u)
    return -1 * tmp * distance(u, v)

def score_func_rank(u, v, beta=0.1):
    norm_u = np.linalg.norm(u, 2)
    norm_v = np.linalg.norm(v, 2)
    tmp = 1 + beta * np.abs(norm_v - norm_u)
    return tmp * distance(u, v)

def compute_nn(ent_id, other_ids, info_dict, func='dist', alpha=1000, beta=0.1):
    vec = get_vector(ent_id, info_dict)
    dists = []
    for ent in other_ids:
        vec_ot = get_vector(ent, info_dict)
        if func == 'dist':
            tmp_score = distance(vec, vec_ot)
        elif func == 'isa':
            tmp_score = score_func_isa(vec, vec_ot, alpha)
        elif func == 'rank':
            tmp_score = score_func_rank(vec, vec_ot, beta)
        dists.append(tmp_score)

    dists = np.asarray(dists)
    sorted_ids = np.argsort(dists)
    return dists, sorted_ids

def sort_by_norm(info_dict):
    emb_mat = info_dict['embeddings']
    imap = info_dict['idmap']
    norms = np.linalg.norm(emb_mat, axis=1)
    sorted_ids = np.argsort(norms)
#    sorted_ids = list(sorted_ids)
    # smaller norms will be at the top of the heirarchy

    rev_imap = {}
    for key, val in imap.items():
        rev_imap[val] = key

    sorted_names = []
    for i in range(len(sorted_ids)):
        init_val = sorted_ids[i]
        new_val = rev_imap[init_val]
        # update with the entity_id
        sorted_names.append(new_val)

    return sorted_ids, sorted_names, norms

#def main():
#    np.random.seed(42)

#    parser = argparse.ArgumentParser(description='Process the model chkpnt path')
#    parser.add_argument('file', help='Path to checkpoint')
#    args = parser.parse_args()
#
#    model_file = args.file
#    info_dict = get_model_info(model_file)
#

#if __name__ == '__main__':
#    main()


import os
import sys
import platform

Build_flag  = ""

def getCurrentWorkspace():
    path = sys.path
    print(path[0])
    return path[0]

def createFolder(path):
    if os.path.exists(path):
        print("the folder exists")
    else:
        os.makedirs(path)

def doWorkOne(dirName):
    root_path = getCurrentWorkspace()
    p = platform.architecture()
    bits = p[0][0:2]
    print(bits)
    if "ryimll" == dirName:
        build_path = root_path + "/" + dirName + "/build_" + bits
    else:
        build_path = root_path + "/RyimAlg_samples/" + dirName + "/build_" + bits
    print(build_path)
    createFolder(build_path)
    os.chdir(build_path)
    buid_cmd = "cmake .. -DCMAKE_BUILD_TYPE=" + sys.argv[2] + " && make 2> makeinfo.txt "
    print(buid_cmd)
    os.system(buid_cmd)
    makeinfo_path = build_path + "/makeinfo.txt"
    if os.path.exists(makeinfo_path):
        with open(makeinfo_path, "r") as f:
            for line in f.readlines():
                if line.find("fatal error:"):
                    exit(1)

def doWorkAll():
    dirNames = os.listdir(getCurrentWorkspace() + "/RyimAlg_samples")
    print(dirNames)
    #dirNames = ["ryimll","utility", "rAlgorithms_sort_sample", "rArrayList_sample",
    #"rAlgorithms_substring_sample", "rHeap_sample", "rGraph_sample", "rTree_sample"]
    for name in dirNames:
        doWorkOne(name)

if __name__ == "__main__":
    print(sys.argv)
    if len(sys.argv) != 3:
        print("build.py [model name] [Debug/Release]")
        exit(1)
    if sys.argv[2] != "Debug" and sys.argv[2] != "Release":
        print("build.py [model name] [Debug/Release]")
        exit(1)

    if "all" == str(sys.argv[1]):
        doWorkAll()
    else:
        doWorkOne(sys.argv[1])


import sys

class Logger:
    #Logger
    msg = []
    prevmsgl = 0

    #Infos - flow
    mxFrameNumber = 0
    frameNumber = 0
    detectionTime = 0
    totalDetections = 0
    ReIDTimes = []
    totalTime = 0

    #Infos - end
    maxId = 0

    #Average times
    counter = 0
    detectionAvg = 0
    ReIDAvg = 0
    totalAvg = 0

    @classmethod
    def make_final_log(self):
        messages = ["", "Max ID", "Average Detection", "Average ReID", "Average FORT", "Average Total"]
        values = ["", Logger.maxId, Logger.detectionAvg / Logger.counter, Logger.ReIDAvg / Logger.counter, (Logger.totalAvg - Logger.detectionAvg) / Logger.counter, Logger.totalAvg / Logger.counter]
        units = ["", "", "ms", "ms", "ms", "ms"]

        mxLength = max([len(s) for s in messages])
        for i in range(len(messages)):
            Logger.add_to_log(messages[i], " " * (mxLength + 1 - len(messages[i])), values[i], " ", units[i])

    @classmethod
    def make_log(self):
        #Calculate message
        messages = ["Detections", "Detection", "", *["ReID" for i in range(len(Logger.ReIDTimes))], "", "FORT", "Total"]
        values = [Logger.totalDetections, int(Logger.detectionTime), "", *[int(v) for v in Logger.ReIDTimes], "", int(Logger.totalTime - Logger.detectionTime), int(Logger.totalTime)]
        units = ["", "ms", "", *["ms" for i in range(len(Logger.ReIDTimes))], "", "ms", "ms"]

        mxLength = max([len(s) for s in messages])
        hold = []
        for i in range(len(messages)):
            hold.append(Logger.to_String(messages[i], " " * (mxLength + 1 - len(messages[i])), values[i], " ", units[i]))

        #Log message
        mxLength = max([len(s) for s in hold]) - len(str(Logger.frameNumber)) - len(str(Logger.mxFrameNumber)) - 1
        Logger.add_to_log("")
        Logger.add_to_log("-" * (mxLength // 2), Logger.frameNumber, "/", Logger.mxFrameNumber, "-" * (mxLength - mxLength // 2))
        Logger.add_to_log("")

        for s in hold:
            Logger.add_to_log(s)

        #Update variables
        Logger.detectionAvg += Logger.detectionTime
        Logger.ReIDAvg += sum(Logger.ReIDTimes)
        Logger.totalAvg += Logger.totalTime

        Logger.ReIDTimes.clear()

        Logger.counter += 1

    @classmethod
    def to_String(self, *m):
        b = ''
        for i in m:
            b += str(i)
        return b

    @classmethod
    def add_to_log(self, *m):
        Logger.msg.append(Logger.to_String(*m))

    @classmethod
    def print_log(self):
        for _ in range(Logger.prevmsgl):
            sys.stdout.write("\x1b[1A\x1b[2K")

        str_msg = ""
        for m in Logger.msg:
            str_msg += m + "\n"

        sys.stdout.write(str_msg)
        sys.stdout.flush()

        # Logger.prevmsgl = len(Logger.msg)
        Logger.prevmsgl = len(str_msg.split("\n"))
        Logger.msg.clear()


from ..exceptions import ParserError
import re

class StringScanner(object):

    def __init__(self, string):
        self._input   = string
        self._offset  = 0
        self.results   = []

    @property
    def buffer(self):
        return buffer(self._input, self._offset)

    def eos(self):
        return self._offset >= len(self._input)

    def _search(self, pattern, flags = re.MULTILINE):
        pattern = re.compile(pattern, flags)
        match   = pattern.search(self.buffer)
        return match

    def _search_from_start(self, pattern, flags = re.MULTILINE):
        return self._search("\A" + pattern, flags)

    def match(self, pattern, flags = re.MULTILINE):
        match = self._search_from_start(pattern, flags)
        if match is not None:
            return len(match.group())

    def skip(self, pattern, flags = re.MULTILINE):
        match = self._search_from_start(pattern, flags)
        if match is not None:
            old_offset    = self._offset
            self._offset += match.end()
            return self._offset - old_offset

    def scan(self, pattern, flags = re.MULTILINE):
        match = self._search_from_start(pattern, flags)

        if match is not None:
            self._offset += match.end()
            self.results  = (match.group(),) + match.groups()

            return True

        self.results = []
        return False

    def skip_until(self, pattern, flags = re.MULTILINE):
        match = self._search(pattern, flags)
        if match is not None:
            self._offset += match.end()
            return match.end()

        return None

    def check_until(self, pattern, flags = re.MULTILINE):
        match = self._search(pattern, flags)

        if match is not None:
            self.results = [self._input[self._offset:self._offset + match.end()]]
            return True

        self.results = []
        return False

    def scan_until(self, pattern, flags = re.MULTILINE):
        if self.check_until(pattern, flags):
            self._offset += len(self.results[0])
            return self.results

        return None

    def remaining(self):
        return self._input[self._offset:]

    def terminate(self):
        self._offset = len(self._input)
        self.results  = []

    @property
    def pos(self):
        return self._offset

class ScannerBase(object):

    def __init__(self, settings = None):
        self._settings  = settings or {}
        self._tokenizer = []

    def parse(self, content):
        self._tmp = {}
        self._ast = {}

        self._input  = StringScanner(content)
        self._offset = 0

        while not self._input.eos():
            self.tokenize()

        return self._ast

    def skip_empty_line(self):
        return self._input.skip("^\n")

    def skip_blank_line(self):
        return self._input.skip("^[\s]*\n")

    def skip_new_line(self):
        return self._input.skip("\n")

    def scan_keyvalue(self):
        if self._input.scan("(.+?):(.*?)(\n|\Z)"):
            key, value = self._input.results[1].strip(), self._input.results[2].strip()
            if self._tmp.get("_section"):
                target = self._ast[self._tmp.get("_section")] or {}
            else:
                target = self._ast

            if value:
                if not target.has_key(key):
                    target[key] = value
                elif isinstance(target[key], list):
                    target[key].append(value)
                else:
                    target[key] = [target[key], value]

            return True

    def _scan_lines_to_array(self, pattern):
        results = []
        while self._input.scan(pattern):
            results.append(self._input.results[1].strip())
        return results

    def _scan_lines_to_hash(self, pattern):
        results = []
        while self._input.scan(pattern):
            key, value = self._input.results[1], self._input.results[2]
            results[key.strip()] = value.strip()
        return results

    def _scan_keyvalues(self, pattern):
        results = []
        if self._input.scan("(.+?):(.*?)(\n|\z)"):
            key, value = self._input.results[1], self._input.results[2]
            if not results.has_key(key):
                results[key] = value
            elif isinstance(results[key], list):
                results[key].results(value)
            else:
                results[key] = [results[key], value]
        return results

    def tokenize(self):
        for tokenizer in self._tokenizer:
            if hasattr(self, tokenizer):
                r = getattr(self, tokenizer)()
                if r:
                    return

        self.error("Unexpected token")

    def error(self, message):
        raise ParserError("%s: %s" % (message, self._input.remaining()))


import importlib.util
import logging
import os

from printStatus import printStatus

def prepareTemplates_Module(
    config, lmin, lmax, velscale, LSF_Data, LSF_Templates, module_used, sortInGrid=False
):
    """
    This function calls the prepareTemplates routine specified by the user.
    """
    # Import the chosen prepareTemplates routine
    try:
        spec = importlib.util.spec_from_file_location(
            "",
            os.path.dirname(os.path.realpath(__file__))
            + "/"
            + config[module_used]["TEMPLATE_SET"]
            + ".py",
        )
        logging.info(
            "Using the routine for '" + config[module_used]["TEMPLATE_SET"] + ".py'"
        )
        prepTemplatesModule = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(prepTemplatesModule)
    except Exception as e:
        logging.critical(e, exc_info=True)
        message = (
            "Failed to import the routine '"
            + config[module_used]["TEMPLATE_SET"]
            + ".py'"
        )
        printStatus.failed(message)
        logging.critical(message)
        return "SKIP"

    # Execute the chosen prepareTemplates routine
    try:
        (
            templates,
            lamRange_spmod,
            logLam2,
            ntemplates,
            logAge_grid,
            metal_grid,
            alpha_grid,
            ncomb,
            nAges,
            nMetal,
            nAlpha,
        ) = prepTemplatesModule.prepareSpectralTemplateLibrary(
            config,
            lmin,
            lmax,
            velscale,
            LSF_Data,
            LSF_Templates,
            module_used,
            sortInGrid,
        )
    except Exception as e:
        logging.critical(e, exc_info=True)
        message = "Routine '" + config[module_used]["TEMPLATE_SET"] + ".py' failed."
        printStatus.failed(message)
        logging.critical(message)
        return "SKIP"

    # Return
    return (
        templates,
        lamRange_spmod,
        logLam2,
        ntemplates,
        logAge_grid,
        metal_grid,
        alpha_grid,
        ncomb,
        nAges,
        nMetal,
        nAlpha,
    )


"""
Manages the box behaviour.

--

Author : DrLarck

Last update : 04/01/2020 (DrLarck)
"""

# dependancies
import asyncio

# check
from utility.command.checker.box import Box_checker

# util
from utility.database.database_manager import Database
from utility.cog.character.getter import Character_getter
from utility.graphic.embed import Custom_embed

# box manager
class Box:
    """
    Manages the player's box.

    - Parameter :

    `ctx` : Represents the `commands.Context`.

    `client` : Represents a `discord.Client`. The client must handle a database connection pool (i.e Database().init())

    `player` : Represents a `Player` (Player instance or discord.Member)

    - Method :

    :coro:`manager(character_id : None)` : Manages the box display, the page switching etc.

    :coro:`wait_for_reaction(displayer, player, possible_reactions)` : Get the player's reaction for the box.

    :coro:`add_button(displayer, current_page, total_pages)` : Add the buttons according to the box logic.

    :coro:`display_box(page : 1, data : None, character_id : None)` : Display the box. If a character_id is passed, display the unique characters.

    :coro:`display_box(page, data)` : Display the player's box.

    :coro:`get_data(id)` : Get the data used for the unique display.
    """

    # attribute
    def __init__(self, ctx, client, player):
        # basics
        self.client = client
        self.ctx = ctx
        self.player = player
        self.db = Database(self.client.db)

    # method
    async def manager(self, character_id = None):
        """
        `coroutine`

        Manages the box by changing the page, closing, etc.

        - Parameter :

        `character_id` : int - Represents the character id to display

        --

        Return : None
        """

        # init
        displayer, total_pages, current_page, data = None, 0, 1, None
        Box_checker.opened_box.append(self.player.id)

        while current_page > 0:  # set the current_page to 0 to stop
            await asyncio.sleep(0)

            # display the box
            displayer, total_pages, current_page, data = await self.display_box(current_page, data, character_id = character_id)

            # add buttons
            added_reaction = await self.add_button(displayer, current_page, total_pages)

            # wait for a reaction
            reaction = await self.wait_for_reaction(displayer, self.player, added_reaction)

            await displayer.delete()

            if(reaction == None):  # in this case, the player didn't react in time
                await self.ctx.send(f"<@{self.player.id}> Closing the box.", delete_after = 20)
                current_page = 0
                break

            if(reaction == "❌"):
                current_page = 0

            if(reaction == "⏮"):
                current_page = 1

            if(reaction == "⏭"):
                current_page = total_pages

            if(reaction == "▶"):
                current_page += 1

            if(reaction == "◀"):
                current_page -= 1

        # remove the player from the checker
        Box_checker.opened_box.remove(self.player.id)

        return(data)

    async def wait_for_reaction(self, displayer, player, possible_reactions):
        """
        `coroutine`

        Wait for a reaction to be added onto the box message.

        --

        Return : the added reaction as str(`discord.Emoji`).
        """

        # init
        added_reaction = None
        def box_predicate(reaction, user):
            check = False
            if(reaction.message.id == displayer.id):
                if(user.id == player.id):
                    if str(reaction.emoji) in possible_reactions:
                        check = True

            return(check)

        # get the reaction
        try:
            reaction, user = await self.client.wait_for(
                "reaction_add",
                timeout = 120,
                check = box_predicate
            )

        except asyncio.TimeoutError:
            return(added_reaction)

        else:
            return(str(reaction.emoji))

        return

    async def add_button(self, box, current_page, total_pages):
        """
        `coroutine`

        Add the button to switch the pages onto the box message.

        - Parameter :

        `box` : discord.Message - Represents the discord.Message to add the reactions to.

        `current_page` : int - Represents the page that is currently displayed.

        `total_pages` : int - Represents the max number of pages.

        --

        Return : list of added reactions
        """

        # int
        added_reaction = []
        reactions = {
            "close" : "❌",
            "beginning" : "⏮",
            "end" : "⏭",
            "next" : "▶",
            "previous" : "◀"
        }

        # add reactions
        await box.add_reaction(reactions["close"])
        added_reaction.append(reactions["close"])

        if(current_page == 1):
            if(total_pages > current_page):
                await box.add_reaction(reactions["next"])
                added_reaction.append(reactions["next"])

                await box.add_reaction(reactions["end"])
                added_reaction.append(reactions["end"])

        elif(current_page > 1):
            await box.add_reaction(reactions["beginning"])
            added_reaction.append(reactions["beginning"])

            await box.add_reaction(reactions["previous"])
            added_reaction.append(reactions["previous"])

            if(total_pages > current_page):
                await box.add_reaction(reactions["next"])
                added_reaction.append(reactions["next"])

                await box.add_reaction(reactions["end"])
                added_reaction.append(reactions["end"])

        return(added_reaction)

    async def display_box(self, page = 1, data = None, character_id = None):
        """
        `coroutine`

        Displays the player's box

        - Parameter :

        `page` : int default 1 - The page to display.

        `data` : list default None - The data to use.

        `character_id` : int default None - Represent the charcter id to display

        --

        Return : box message, number of pages, current_page, data
        """

        # init
        box_display = ""

            # params
        total_pages = 1
        max_display = 5  # number of characters to display
        start_at = 0     # index of the character to display first
        end_at = 5       # idex of the character to display last  (= max_display + 1)
        getter = Character_getter()

        if(data == None):  # if no data provided, get the player's character
            if(character_id == None):  # if the display is not unique
                data = await self.db.fetch(
                f"""
                SELECT DISTINCT character_global_id FROM character_unique
                WHERE character_owner_id = {self.player.id}
                ORDER BY character_global_id ASC;
                """
                )

            else:
                data = await self.db.fetch(
                    f"""
                    SELECT character_unique_id, character_type, character_rarity, character_level FROM character_unique
                    WHERE character_owner_id = {self.player.id} AND character_global_id = {character_id}
                    ORDER BY character_level DESC;
                    """
                )

        if(page > 1):
            start_at += (end_at) * (page - 1)  # display the character above the last one of the previous page
            end_at += max_display * (page - 1)

            # setup total pages
        total_pages = int(((len(data) - 1) / max_display) + 1)

        if(len(data) < end_at):  # if there is not enough character to display
            end_at = len(data)

        if(page > total_pages):
            await self.ctx.send(f"<@{self.player.id}> Sorry, this page doesn't exist.")
            Box_checker.opened_box.remove(self.player.id)
            return

        # start displaying
        waiting_message = await self.ctx.send(f"<@{self.player.id}> Displaying ...")

        for row in range(start_at, end_at):
            await asyncio.sleep(0)

            if(character_id == None):
                # retrieve the character
                character_id = data[row][0]
                character = await getter.get_character(character_id)
                await character.init()

                # get the character quantity
                character_quantity = len(await self.db.fetch(
                    f"""
                    SELECT character_global_id FROM character_unique
                    WHERE character_global_id = {character.info.id} AND character_owner_id = {self.player.id};
                    """
                ))

                # add line to the box
                box_display += f"#`{character.info.id}` - {character.image.icon}__{character.info.name}__ : *x{character_quantity}*\n"

                # reset
                character_id = None

            else:  # character unique
                # retrieve the character
                character = await getter.get_character(character_id)

                # setup the character
                unique_id = data[row][0]
                character.type.value = data[row][1]
                character.rarity.value = data[row][2]
                character.level = data[row][3]
                await character.init()

                # add line to the box
                box_display += f"{row + 1} - `{unique_id}` - {character.image.icon}__{character.info.name}__ {character.type.icon}{character.rarity.icon} - lv.{character.level}\n"

        # check if there is something to display
        if(box_display == ""):
            box_display = "DISPLAY ERROR"

        # setup the embed
        embed = await Custom_embed(self.client).setup_embed()
        embed.set_thumbnail(url = self.player.avatar)
        embed.add_field(
            name = f"{self.player.name}'s box | Page : {page:,} / {total_pages:,}",
            value = box_display,
            inline = False
        )

        # sending
        await waiting_message.delete()
        box = await self.ctx.send(embed = embed)

        return(box, total_pages, page, data)

    async def get_data(self, character_id):
        """
        `coroutine`

        Get the data used for the box.

        --

        Return : list
        """

        data = await self.db.fetch(
            f"""
            SELECT character_unique_id, character_type, character_rarity, character_level FROM character_unique
            WHERE character_owner_id = {self.player.id} AND character_global_id = {character_id}
            ORDER BY character_level DESC;
            """
        )

        return(data)

    async def get_characters_amount(self):
        """
        `coroutine`

        Get the amount of characters owned by the player.

        --

        Return : `int`
        """

        # init
        amount = 0
        characters = await self.db.fetch(
            f"""
            SELECT character_unique_id
            FROM character_unique
            WHERE character_owner_id = {self.player.id};
            """
        )

        if(characters != None):
            amount = len(characters)

        return(amount)


from flask import render_template, request
from app import app
import MySQLdb
from a_Model import ModelIt

import networkx as nx
import matplotlib.pylab as plt
from geopy.distance import great_circle
from geopy.geocoders import Nominatim
from setup_functions2 import *

@app.route('/')

@app.route('/index')
def index():
	return render_template("index.html",
		title = 'Home', user = { 'nickname': 'Missy' },
		)

@app.route('/db')
def bkmap_page():
	db = MySQLdb.connect(user="root", host="localhost", db="bk_map",  charset='utf8')
	with db:
		cur = db.cursor()
		cur.execute("SELECT * FROM bk_weights LIMIT 15;")
		query_results = cur.fetchall()
	edges = ""
	for result in query_results:
		edges += result[0]
		edges += "<br>"
		return edges

@app.route("/db_fancy")
def bkmap_page_fancy():
	db = MySQLdb.connect(user="root", host="localhost", db="bk_map",  charset='utf8')
	with db:
		cur = db.cursor()
		cur.execute("SELECT edgeid, node1, node2, weight FROM bk_weights LIMIT 15;")

		query_results = cur.fetchall()
	edges = []
	for result in query_results:
		edges.append(dict(edgeid=result[0], node1=result[1], node2=result[2], weight = result[3]))
	return render_template('cities.html', edges = edges)

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

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

@app.route('/output')
def crawl_output():
	start = request.args.get("START_LOC")
	bar1 = request.args.get("BAR1")
	bar2 = request.args.get("BAR2")
	bar3 = request.args.get("BAR3")
	end = request.args.get("END_LOC")
	bar_input_list = [bar1, bar2, bar3]
	bar_address = get_bar_address(bar1, bar2, bar3)

	start_tuple, end_tuple = get_start_end(start,end)
	bar_tuple_list = get_bar_location(bar1,bar2,bar3)

	node_sql = ReadNodefromSQL(cur)
	edge_sql = ReadEdgefromSQL(cur)

	node_dic = NodeSQLtoDic(node_sql)
	edge_dic = EdgeDQLtoDic(edge_sql)

	G = gen_network(node_dic, edge_dic)

	path, line_path = crawl_path(G, start_tuple, bar_tuple_list, end_tuple, node_dic, edge_dic)
	bar_address = reorder_beer_list(bar_address, path)
	bar_tuple_list = reorder_beer_list(bar_tuple_list, path)
	single_path = []
	for line in line_path:
		single_path.extend(line)
	bar_list = tuplebarlist_floatlist(bar_tuple_list)
	bar_add = tuplebarlist_stringlist(bar_address)
	bar_dic = make_bar_dic(bar_add, bar_list)
	return render_template('output.html',  start = [start, start_tuple[0],start_tuple[1]],  bar_add =bar_add, bar_dic = bar_dic, end = [end,end_tuple[0],end_tuple[1]], path = path, path_list = single_path)


from __future__ import print_function
from tensorflow import keras
from tensorflow.python.keras import regularizers, layers, models, datasets, callbacks, preprocessing, optimizers
from datetime import datetime

batch_size = 128
num_classes = 10
epochs = 60
l2_weights = 1e-4
img_x, img_y = 32, 32

##############################
# Load data
##############################
(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
x_train = x_train.reshape(x_train.shape[0], img_x, img_y, 3)
x_test = x_test.reshape(x_test.shape[0], img_x, img_y, 3)
input_shape = (img_x, img_y, 3)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

##############################
# Create model
##############################
model = models.Sequential()
for cnn_depth in range(1, 3):
    model.add(layers.Conv2D(32*cnn_depth, kernel_size=(3, 3), strides=(1, 1), activation='relu', input_shape=input_shape, kernel_regularizer=regularizers.l2(l2_weights)))
    model.add(layers.Activation("relu"))
    model.add(layers.BatchNormalization())
    model.add(layers.Conv2D(32*cnn_depth, kernel_size=(3, 3), strides=(1, 1), activation='relu', input_shape=input_shape, kernel_regularizer=regularizers.l2(l2_weights)))
    model.add(layers.Activation("relu"))
    model.add(layers.BatchNormalization())
    model.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
    model.add(layers.Dropout(rate=0.1 + 0.025*cnn_depth))

model.add(layers.Flatten())
# model.add(layers.Dense(256, activation='relu'))
# model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(num_classes, activation='softmax'))

opt_rms = optimizers.RMSprop(lr=0.0005,decay=1e-6)
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=opt_rms,
              metrics=['accuracy'])

# Tensorboard
tensorboard = callbacks.TensorBoard(
    log_dir="./K_CIFAR_model/{}".format(datetime.today().strftime('%m-%d__%H-%M-%S')),
    histogram_freq=0,
    write_graph=True)
tensorboard.set_model(model)

##############################
# Train model
##############################
datagen = preprocessing.image.ImageDataGenerator(
    featurewise_center=False,
    samplewise_center=False,
    featurewise_std_normalization=False,
    samplewise_std_normalization=False,
    zca_whitening=False,
    rotation_range=15,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
    vertical_flip=False
    )
datagen.fit(x_train)
model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size), epochs=epochs, validation_data=(x_test,y_test), callbacks=[tensorboard], steps_per_epoch=x_train.shape[0] // batch_size)
#
# model.fit(x_train, y_train,
#           batch_size=batch_size,
#           epochs=epochs,
#           verbose=1,
#           validation_data=(x_test, y_test),
#           callbacks=[tensorboard])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])


from typing import Dict, Set
from collections import defaultdict

from pyacc.common import epsilon
from .grammar import Grammar
from .lalr_nfa import LALRNFA, LALRNFAState
from .items import LookAheadItem

class FirstSet:
    def __init__(self, g: Grammar):
        self.g = g
        self._fs_table = defaultdict(set)
        self.calculate()

    def calculate(self):
        changed = True
        while changed:
            changed = False
            for rule in self.g.rules:
                previous_count = len(self._fs_table[rule.left_hand])
                for symbol in rule.right_hand:
                    if symbol in self.g.terminals:
                        self._fs_table[rule.left_hand].add(symbol)
                        break
                    else:
                        self._fs_table[rule.left_hand].update(self._fs_table[symbol])
                        if epsilon not in self._fs_table[symbol]:
                            break
                if len(self._fs_table[rule.left_hand]) != previous_count:
                    changed = True

    def __getitem__(self, symbol):
        if symbol in self.g.non_terminals:
            return self._fs_table[symbol]
        elif symbol in self.g.terminals:
            return {symbol, }
        else:
            raise Exception()

class Channelling:
    def __init__(self):
        self.first_set = None
        self.nfa = None
        self.grammar = None
        self.channel = None                                                   # type: Dict[LALRNFAState, Set[LALRNFAState]]

    def pre_configure(self, nfa: LALRNFA, g: Grammar):
        self.nfa = nfa
        self.grammar = g
        self.first_set = FirstSet(g)
        self.channel = defaultdict(set)
        for state in nfa.states:
            state.items.look_ahead = LookAheadItem(set())

    def init_channel(self):
        active_states = set()
        for edge in self.nfa.edges:
            src = edge.src_state
            dest = edge.dest_state
            symbol = edge.symbol
            if symbol is not epsilon:
                self.channel[src].add(dest)
            else:
                look_ahead_set = set()

                rule_item = src.items.rule
                unrecognized_symbols = rule_item.rule.right_hand[rule_item.dot_pos+1: ]
                for unrecognized_symbol in unrecognized_symbols:
                    first_set = self.first_set[unrecognized_symbol]
                    look_ahead_set.update(first_set)
                    if epsilon not in first_set:
                        break
                else:
                    self.channel[src].add(dest)
                if epsilon in look_ahead_set:
                    look_ahead_set.remove(epsilon)

                dest.items.look_ahead.symbols.update(look_ahead_set)
                active_states.add(dest)
        return active_states

    def flow(self, up_stream_state: LALRNFAState):
        upstream_symbols = up_stream_state.items.look_ahead.symbols

        for downstream_state in self.channel[up_stream_state]:
            downstream_symbols = downstream_state.items.look_ahead.symbols
            if not upstream_symbols.issubset(downstream_symbols):
                downstream_symbols.update(upstream_symbols)
                self.flow(downstream_state)

    def reset(self):
        self.first_set = None
        self.nfa = None
        self.grammar = None
        self.channel = None

    def channelling(self, nfa: LALRNFA, g: Grammar):
        self.pre_configure(nfa, g)
        active_states = self.init_channel()
        for state in active_states:
            self.flow(state)

        self.reset()


# coding:utf-8
from __future__ import print_function
from selenium import webdriver
from selenium.common.exceptions import ElementNotVisibleException
from ast import literal_eval
from time import sleep
from bs4 import BeautifulSoup
import sys
import urllib.request
from http.client import BadStatusLine
from http.client import IncompleteRead
import codecs
import datetime

args = sys.argv
word = args[1]

driver = webdriver.Chrome()

driver.get("https://ask.fm/" + word)

while True:
    scroll_h = driver.execute_script("var h = window.pageYOffset; return h")
    judge = driver.execute_script("var m = window.pageYOffset; return m")
    previous_h = driver.execute_script("var h = window.pageYOffset; return h")
    #スクロール
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    sleep(3)
    after_h = driver.execute_script("var h = window.pageYOffset; return h")
    if previous_h == after_h:
        break
print('load complete')

page_source = driver.page_source

questions = driver.find_elements_by_class_name("streamItemContent-question")
answers = driver.find_elements_by_class_name("answerWrapper")

qas = [(q.find_element_by_tag_name('h2').text, a.find_element_by_tag_name('p').text) for q, a in zip(questions, answers)]

print('find complete')

with codecs.open('data/askfm_data_' + word + '.txt', 'w', 'utf-8') as f:
    for q, a in qas:
        if q == '' or a == '' or 'http' in q or 'http' in a:
            continue
        q = q.replace('\n', '')
        a = a.replace('\n', '')
        f.write(q)
        f.write('\n')
        f.write(a)
        f.write('\n')
        f.write('\n')

driver.quit()


import random
import sys

def guess(user_number):
    computer_number=random.randint(1, 10)

    attempt = 'yes'

    while attempt == 'yes' :

        if int(computer_number) == int(user_number):
            print("you got the right number!")
        elif int(computer_number) != int(user_number):
            print("the number you introduced does not match with the computer number")

        print(f"computer number: {computer_number}")

        attempt = input(f"would you like to play again? (yes or no): ")

        while attempt != 'yes' and attempt !='no':
            attempt = input(f"please, enter a 'yes' or 'no': ")

        if attempt == "yes":
            user_number = int(input("try to guess the number from 1 to 10: "))
            computer_number = random.randint(1, 10)
        elif attempt == "no":
            print("have a great day!")

user_number = int(input("try to guess the number from 1 to 10: "))

guess(user_number)