import Adafruit_BBIO.GPIO as GPIO
import time

rows=4; cols=4;

#Definiendo la matrix
MATRIX = [ ['1','2','3','A'],
           ['4','5','6','B'],
           ['7','8','9','C'],
           ['*','0','#','D'] ]

#definiendo los pines
#COL = ["GPIO_66", "GPIO_69","GPIO_45","GPIO_47"] # C1, C2, C3, C4
#ROW = ["GPIO_67","GPIO_68","GPIO_44","GPIO_26"] # R1, R2, R3, R4
COL = ["P8_46","P8_44","P8_42","P8_40"] # C1, C2, C3, C4
ROW = ["P8_45","P8_37","P8_35","P8_39"] # R1, R2, R3, R4

for h in range(4):
 GPIO.setup(COL[h],GPIO.OUT)
 GPIO.setup(ROW[h],GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def TurnOff(COL):
 for q in range(4): GPIO.output(COL[q],0)

#Intento
for w in range(4): print("Fila (In): ",GPIO.input(ROW[w]),"COl :",GPIO.input(COL[w]))
print(" ")
#for p in range(4): print(GPIO.input(ROW[p]),GPIO.input(COL[p]))
flat=0,0
for i in range(1000):
  for j in range(4): #j es la columna
   GPIO.output(COL[j],1)
   for k in range(4):
     if GPIO.input(ROW[k])==1: flat=j,k
   TurnOff(COL)
  for p in range(4): print(GPIO.input(ROW[p]),GPIO.input(COL[p]))
  print(" ")
  time.sleep(0.1)
  print(MATRIX[flat[1]][flat[0]])


# -*- coding: utf-8 -*-
"""
@author: Thomas
"""

class portmanteau:

 #Finds the number of letters each word contributes to a "regular" portmanteau.
 def __init__(self,c,a,b):

     i = 0
     while c[i] == a[i]:
         i = i+1
         if i == len(a):
             break

     self.c = len(c)
     self.a = len(a)
     self.b = len(b)
     self.name_1 = i
     self.name_2 = self.c - i

 # finds percent that each word contributes
 def percent_find(self):

     rtrn = []

     rtrn.append(100*(self.name_1/self.c))
     rtrn.append(100 - rtrn[0])

     return rtrn
 # finds what percent of each word is used

 def percent_word(self):

     rtrn = []
     rtrn.append(100*(self.name_1/self.a))
     rtrn.append(100*(self.name_2/self.b))

     return rtrn


#! /usr/bin/python

import pandas as pd
import numpy as np
from itertools import repeat
import matplotlib.pyplot as plt
import seaborn as sns
import itertools

# load guppy data
df = {}
barcode_list = ['01','02','03','04','05','06','08','09','10','11']
for barcode_number in barcode_list:
    df[barcode_number] = pd.DataFrame()
    f1 = open("barcode{}/guppy.5mC.cpg.bam".format(barcode_number),'r')
    chromosome_list = list()
    start_position_list = list()
    end_position_list = list()
    modified_base_percentage_list = list()
    unmodified_base_count_list = list()
    modified_base_count_list = list()

    lines = f1.readlines()
    # strand = ['+','-']

    for line in lines:

        #split the line into a list by whitespace
        splitLine = line.rstrip().split()

        # change the condition here for data in either positive or negative strand
        if splitLine[5] == '+':

            chromosome = float(splitLine[0])
            start_position = float(splitLine[1])
            end_position = float(splitLine[2])
            modified_base_percentage = float(splitLine[10])
            unmodified_base_count = float(splitLine[11])
            modified_base_count = float(splitLine[12])

            chromosome_list.append(chromosome)
            start_position_list.append(start_position)
            end_position_list.append(end_position)
            modified_base_percentage_list.append(modified_base_percentage)
            unmodified_base_count_list.append(unmodified_base_count)
            modified_base_count_list.append(modified_base_count)

    f1.close()

    df[barcode_number]['chromosome'] = chromosome_list
    df[barcode_number] = df[barcode_number].astype({'chromosome':'int'})
    df[barcode_number]['start'] = start_position_list
    df[barcode_number] = df[barcode_number].astype({'start':'int'})
    df[barcode_number]['end'] = end_position_list
    df[barcode_number]['modified_base_percentage'] = modified_base_percentage_list
    df[barcode_number]['unmodified_base_count'] = unmodified_base_count_list
    df[barcode_number]['modified_base_count'] = modified_base_count_list
    df[barcode_number]['coordinates'] = mgc1(df[barcode_number]['chromosome'],df[barcode_number]['start']).rename('new')
    df[barcode_number] = df[barcode_number].rename(columns={'modified_base_percentage':'barcode{}_methylated_frequency'.format(barcode_number)})

# scatter plot of region in chromosome 7
SMALL_SIZE = 20
MEDIUM_SIZE = 20
BIGGER_SIZE = 30

sns.set_style('darkgrid')
plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=40)     # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=50)  # fontsize of the figure title

plt.figure()
plt.figure(figsize=(35, 15), dpi=80)

barcode_list = ['08','09','10','11','01','02','03','04','05','06']
legend_list = ['30hpi_BR1','36hpi_BR1','30hpi_BR2','36hpi_BR2','30hpi_BR3','36hpi_BR3','30hpi_BR4','36hpi_BR4',
               '30hpi_BR5','36hpi_BR5']
for count, barcode_number in enumerate(barcode_list):
    data =  df[barcode_number][ ( df[barcode_number]['chromosome']==7) & ( df[barcode_number]['start']>=500000) & (df[barcode_number]['end']<=600000)]
    if barcode_number in ['01','03','05','08','10']:
        plt.plot(data['start'],data['modified_base_percentage'],'o',label='{}'.format(legend_list[count]),color='blue')

    if barcode_number in ['02','04','06','09','11']:
        plt.plot(data['start'],data['modified_base_percentage'],'o',label='{}'.format(legend_list[count]),color='green')

plt.xlabel("Chr7:500000-600000",labelpad=15,fontsize=40)
plt.ylabel("modified base percentage(%)",labelpad=15,fontsize=40)
plt.ylim(0,100)
plt.title("Positive Strand",fontsize=60)
plt.legend()
file_name = 'chr7:500000_600000_positive_strand.png'
plt.savefig(file_name,dpi=500, bbox_inches='tight')
plt.show()


from lxml import etree

FILE_NAME = 'besiktas-speed-40/osm.net.xml'
SPEED_SCALE = 2

root = etree.parse(FILE_NAME)
for elt in root.iter():
    if "speed" in elt.attrib:
        current_speed = float(elt.attrib["speed"])
        elt.attrib["speed"] = str(current_speed * SPEED_SCALE)
    if "limitTurnSpeed" in elt.attrib:
        current_speed = float(elt.attrib["limitTurnSpeed"])
        elt.attrib["limitTurnSpeed"] = str(current_speed * SPEED_SCALE)
    print(elt)
# getting the parent tag of
# the xml document
b_xml = etree.tostring(root, pretty_print=True)

with open(FILE_NAME, "wb") as f:
    f.write(b_xml)


'''
utils.py

Utility functions used by multiple scripts.
'''

import os
import gzip
import json
import logging
import csv
import itertools
import numpy as np
import string
from operator import itemgetter

def gen_shares(filepath):
    with open(filepath, 'r') as f:
        shares = json.loads(f.read())
        for uid in shares:
            for tid in shares[uid]:
                yield uid, tid, shares[uid][tid]

def domain(url):
    """
    >>> domain('http://https://test.com')
    'https'
    >>> domain('http://test.com?site=https://other.com')
    'test.com'
    >>> domain('http://test.com/index?test=1')
    'test.com'
    >>> domain('http://indiana.facebook.com/dir1/page.html')
    'indiana.facebook.com'
    >>> domain('http://facebook.com')
    'facebook.com'
    >>> domain('http://www.facebook.com:80/')
    'facebook.com'
    """
    url = (''.join(filter(lambda c: c in string.printable, url))).lower()

    # remove protocol
    idx = url.find("://")
    if idx != -1:
        url = url[idx + 3:]

    # remove port
    idx = url.find(":")
    if idx != -1:
        url = url[:idx]

    # remove trailing / and everything that follows
    idx = url.find("/")
    if idx != -1:
        url = url[:idx]

    # remove ? and anything that follows if it wasn't in previous steps
    idx = url.find("?")
    if idx != -1:
        url = url[:idx]

    url_is_clean = False
    while not url_is_clean:
        if url.startswith('www.'):
            url = url[4:]
        elif url.startswith('www2.') or url.startswith('www3.'):
            url = url[5:]
        else:
            url_is_clean = True
    return url

def readcol(csv_filepath, col=0, delim='\t', skip_rows=0, apply_fn=None):
    if csv_filepath is None or not os.path.exists(csv_filepath):
        raise ValueError('Invalid filepath: {}.'.format(csv_filepath))

    items = []
    with open(csv_filepath, 'r') as f:
        reader = csv.reader(f, delimiter=delim)

        # skip header lines
        for _ in range(skip_rows):
            try:
                next(reader)
            except StopIteration:
                raise ValueError('Invalid skip_rows: {}, {}'.format(skip_rows, csv_filepath))

        for row in reader:
            if col >= len(row):
                raise ValueError('Invalid col: {}, {}'.format(col, csv_filepath))

            if apply_fn is not None:
                val = apply_fn(row[col])
            else:
                val = row[col]

            items.append(val)

    return items

def write_csv(filepath, items, headers=None, delimiter='\t'):
    with open(filepath, 'w') as f:
        w = csv.writer(f, delimiter=delimiter)
        if headers is not None:
            rows = [headers]
            rows.extend(items)
        else:
            rows = items
        w.writerows(rows)

if __name__ == "__main__":
    logging.info('Testing...')
    import doctest
    doctest.testmod()


import win32file
from AbstractFileReader import AbstractFileReader

class Win32FileReader(AbstractFileReader):
    __filename = None
    __handle = None

    def __init__(self, filename):
        self.__filename = filename
        try:
            fullname = '\\\\.\\%s' % filename
            self.__handle = win32file.CreateFile(fullname,
                win32file.GENERIC_READ,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                0, 0)
        except Exception as err:
            raise RuntimeError('Could not open the specified file.')

    def isValid(self):
        return self.__handle != None

    def readBytes(self, offset, length):
        if self.__handle == None:
            raise RuntimeError('Could not read from an invalid file handle.')
        win32file.SetFilePointer(self.__handle, offset, win32file.FILE_BEGIN)
        rc, bytes = win32file.ReadFile(self.__handle, length)
        return bytes

    def filename(self):
        return self.__filename

    def close(self):
        if self.__handle == None:
            raise RuntimeError('Could not close an invalid file handle.')
        win32file.CloseHandle(self.__handle)
        self.__handle = None


#!/usr/bin/env python3
"""
Unit tests
"""

import unittest
from stl import STL

class TestSTL(unittest.TestCase):
    """
    Unit tests
    """
    def test_load_stl(self):
        """
        loading test
        """
        stl = STL()
        stl.load("models/Tux_printable.stl")
        self.assertEqual(len(stl.triangles), 14842)
        stl.load("models/Pumpkin_whole.stl")
        self.assertEqual(len(stl.triangles), 138282)

if __name__ == "__main__":
    unittest.main(verbosity=2)


from types import SimpleNamespace
import torch
from torch import nn
from datasets import SentenceClassificationDataset
from multitask_classifier import MultitaskBERT, process_batch
from optimizer import AdamW
from tokenizer import BertTokenizer
from torch.utils.data import DataLoader
from tqdm import tqdm

import torch.nn.functional as F

class CrossEncoder(nn.Module):

    def __init__(
            self,
            option='finetune', device='cuda',
            hidden_dropout_prob=0.2,
            optimizer_params = {'lr': 2e-5},
            optimizer_class = torch.optim.AdamW,
                 ):

        super().__init__()
        # Init model
        config = {
            'hidden_dropout_prob': 0.001,
            'num_labels': {3: 0, 2: 1, 4: 2, 0: 3, 1: 4},
            'hidden_size': 768,
            'data_dir': '.',
            'option': 'pretrain',
            'local_files_only': False
            }

        config = SimpleNamespace(**config)

        self.device = device
        self.model = MultitaskBERT(config)
        self.model.to(self.device)
        self.optimizer = AdamW(self.model.parameters(), lr=1e-3, weight_decay=0.05, betas=[0.9, 0.999], eps=1e-06)

    def fit(self, train_dataloader: DataLoader):
            for sentence_pairs in tqdm(train_dataloader, desc="Iteration", smoothing=0.05):
                self.model.zero_grad()
                self.model.train()
                sst_ids, sst_mask, sst_labels = process_batch(sentence_pairs, self.device, "sst")
                sst_outputs = self.model.predict_sentiment(sst_ids, sst_mask)
                sst_loss = F.cross_entropy(sst_outputs, sst_labels.view(-1), reduction='mean')
                print(sst_loss)
                self.optimizer.zero_grad()
                sst_loss.backward()
                self.optimizer.step()

if __name__ == '__main__':
    sentence_pairs = [
        ["The sun is shining. [SEP] It's a beautiful day.", 0.85, 1],
        ["Cats are independent animals. [SEP] Dogs are loyal companions.", 0.65, 2],
        ["Learning a new language can be challenging. [SEP] Practice is key to language acquisition.", 0.75, 3],
        ["Books are a source of knowledge. [SEP] Reading enhances intellectual growth.", 0.90, 4]
    ]
    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', local_files_only=False)
    sentence_pairs = SentenceClassificationDataset(sentence_pairs, None, tokenizer)
    sentence_pairs_dataloader = DataLoader(sentence_pairs, shuffle=True, batch_size=4,
                                        collate_fn=sentence_pairs.collate_fn, num_workers=4)
    cross_encoder = CrossEncoder(device = 'cpu')
    cross_encoder.fit(train_dataloader=sentence_pairs_dataloader)


import sys
from collections import Counter
# +++your code here+++
# Define print_words(filename) and print_top(filename) functions.
# You could write a helper utility function that reads a file
# and builds and returns a word/count dict for it.
# Then print_words() and print_top() can just call the utility function.

def print_words(filename):
  words_list=[]
  f=open(filename,'rU')
  for line in f:
    line_words=line.split()
    line_words=[ x.lower() for x in line_words ]
    words_list+=line_words
  words_count_map=Counter(words_list)
  unique_word_list=list(words_count_map.keys())
  unique_word_list_sorted=sorted(unique_word_list)
  for word in unique_word_list_sorted:
    print(word,words_count_map[word])

if __name__ == '__main__':
  print_words('small.txt')


import tensorflow as tf
import numpy as np
from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer
from baselines.common.tf_util import get_session, save_variables, load_variables

from mpi4py import MPI
from baselines.common.tf_util import initialize
from baselines.common.mpi_util import sync_from_root

# Helper function to build convnets
def conv2d(inputs, filters, kernel_size, strides, padding):
        return tf.layers.conv2d(inputs = inputs,
                           filters = filters,
                            kernel_size = (kernel_size, kernel_size),
                            strides = strides,
                            padding = padding)

class ICM(object):
    def __init__(self, ob_space, ac_space, max_grad_norm, beta, icm_lr_scale):

        sess = get_session()

        #TODO find a better way
        input_shape = [ob_space.shape[0], ob_space.shape[1], ob_space.shape[2]]
        self.action_shape = 36

        # Placeholders
        self.state_ = phi_state = tf.placeholder(tf.float32, [None, *input_shape], name="icm_state")
        self.next_state_ = phi_next_state =  tf.placeholder(tf.float32, [None, *input_shape], name="icm_next_state")
        self.action_ = action = tf.placeholder(tf.float32, [None], name="icm_action")

        with tf.variable_scope('icm_model'):
            # Feature encoding
            # Aka pass state and next_state to create phi(state), phi(next_state)
            # state --> phi(state)
            phi_state = self.feature_encoding(self.state_)

            with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
                # next_state to phi(next_state)
                phi_next_state = self.feature_encoding(self.next_state_)

            # INVERSE MODEL
            pred_actions_logits, pred_actions_prob = self.inverse_model(phi_state, phi_next_state)

            # FORWARD MODEL
            pred_phi_next_state = self.forward_model(action, phi_state)

        # CALCULATE THE ICM LOSS
        # Inverse Loss LI
        # We calculate the cross entropy between our ât and at
        # Squeeze the labels (required)
        labels = tf.cast(action, tf.int32)

        self.inv_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred_actions_logits, labels=labels), name="inverse_loss")

        # Foward Loss
        # LF = 1/2 || pred_phi_next_state - phi_next_state ||
        # TODO 0.5 * ?
        self.forw_loss = tf.reduce_mean(tf.square(tf.subtract(pred_phi_next_state, phi_next_state)), name="forward_loss")

        # Todo predictor lr scale ?
        # ICM_LOSS = [(1 - beta) * LI + beta * LF ] * Predictor_Lr_scale
        self.icm_loss = ((1-beta) * self.inv_loss + beta * self.forw_loss) * icm_lr_scale

        # UPDATE THE PARAMETERS USING LOSS
        # 1. Get the model parameters
        icm_params = tf.trainable_variables('icm_model')
        # 2. Build our trainer
        icm_trainer = MpiAdamOptimizer(MPI.COMM_WORLD, learning_rate=1e-4, epsilon=1e-5)
        # 3. Calculate the gradients
        icm_grads_and_var = icm_trainer.compute_gradients(self.icm_loss, icm_params)
        icm_grads, icm_var = zip(*icm_grads_and_var)

        if max_grad_norm is not None:
            # Clip the gradients (normalize)
            icm_grads, icm__grad_norm = tf.clip_by_global_norm(icm_grads, max_grad_norm)
        icm_grads_and_var = list(zip(icm_grads, icm_var))
        # zip aggregate each gradient with parameters associated
        # For instance zip(ABCD, xyza) => Ax, By, Cz, Da

        _icm_train = icm_trainer.apply_gradients(icm_grads_and_var)

        if MPI.COMM_WORLD.Get_rank() == 0:
            print("Initialize")
            initialize()
        global_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="")
        print("GLOBAL VARIABLES", global_variables)
        sync_from_root(sess, global_variables) #pylint: disable=E1101

    # We use batch normalization to do feature normalization as explained in the paper
    def feature_encoding(self, x):
        x = tf.nn.elu(tf.layers.batch_normalization(conv2d(x, 8, 5, 4, "valid")))
        x = tf.nn.elu(tf.layers.batch_normalization(conv2d(x, 16, 3, 2, "valid")))
        x = tf.nn.elu(tf.layers.batch_normalization(conv2d(x, 32, 3, 2, "valid")))
        x = tf.nn.elu(tf.layers.batch_normalization(conv2d(x, 64, 3, 2, "valid")))
        x = tf.layers.flatten(x)
        x = tf.nn.elu(tf.contrib.layers.fully_connected(x, 256))

        return x

    # Inverse Model
    # Given phi(state) and phi(next_state) returns the predicted action ât
    """
    Parameters
    __________

    action:   The real action taken by our agent
    phi_state: The feature representation of our state generated by our feature_encoding function.
    phi_next_state: The feature representation of our next_state generated by our feature_encoding function.

    returns pred_actions_logits: the logits and pred_actions_prob: the probability distribution of our actions
    """
    def inverse_model(self, phi_state, phi_next_state):
        # Concatenate phi(st) and phi(st+1)
        icm_inv_concatenate = tf.concat([phi_state, phi_next_state], 1)
        icm_inv_fc1 = tf.nn.relu(tf.layers.dense(icm_inv_concatenate, 256))
        pred_actions_logits = tf.layers.dense(icm_inv_fc1, self.action_shape)
        pred_actions_prob = tf.nn.softmax(pred_actions_logits, dim=-1)

        return pred_actions_logits, pred_actions_prob

    # Foward Model
    # Given action and phi(st) must find pred_phi(st+1)
    """
    Parameters
    __________

    action:   The action taken by our agent
    phi_state: The feature representation of our state generated by our feature_encoding function.
    phi_next_state: The feature representation of our next_state generated by our feature_encoding function.

    returns pred_phi_next_state: The feature representation prediction of our next_state.
    """
    def forward_model(self, action, phi_state):
        # Concatenate phi_state and action
        action = tf.expand_dims(action, axis=1) # Expand dimension to be able to concatenate

        icm_forw_concatenate = tf.concat(axis=1, values=[phi_state, action])

        # FC
        icm_forw_fc1 = tf.layers.dense(icm_forw_concatenate, 256)

        # FC (size of phi_state [1] aka the width)
        icm_forw_pred_next_state = tf.layers.dense(icm_forw_fc1, phi_state.get_shape()[1].value)

        return icm_forw_pred_next_state

    # Calculate intrinsic reward
    """
    Parameters
    __________

    phi_next_state: The feature representation of our next_state generated by our feature_encoding function.
    pred_phi_next_state:   The feature representation prediction of our next_state.

    returns intrinsic_reward: The intrinsic reward
    """
    def calculate_intrinsic_reward(self, state, next_state, action):

        sess = tf.get_default_session()

        error = sess.run(self.forw_loss, {self.state_: state, self.next_state_: next_state, self.action_: action})

        error = error * 0.5

        # Return intrinsic reward
        return error

"""

   Need implement train function

"""


import sys
import re
import gzip
import os
import apache_log_parser
from contextlib import ExitStack

bitstreamRE = re.compile(r'/bitstream/(\d+)')

def create_access_table(db):
    "Initialize sqlite table for web access records."
    with db as c:
        c.execute('''create table if not exists
                access (bitstream_id, ip, ts, useragent)
                ''')

        c.execute('''create unique index if not exists access_unique_idx
                    on access(bitstream_id, ip, ts)''')

def add_access_info(db, filenames):
    """Add bitstream access information to sqlite table."""
    for access in read_and_parse(filenames):
        req = access['request_url_path']
        m = bitstreamRE.match(req)
        if not m:
            continue

        host = access['remote_ip']
        user_agent = access['request_header_user_agent']
        access_time = access['time_received_utc_isoformat']
        bitstream_id = m.group(1)
        db.execute("""insert or ignore into access(bitstream_id, ip, ts, useragent)
                    values(?, ?, ?, ?)""",
                    (bitstream_id, host, access_time, user_agent))
    db.commit()

def read_and_parse(filenames):
    """Read all apache log files (possibly gzipped) and
       yield each parsed bitsteam download event."""
    log_parser = create_log_parser()
    for filename in filenames:

        if os.path.splitext(filename)[1] == '.gz':
            fp = gzip.open(filename, 'rt')
        else:
            fp = open(filename)
        for line in fp:
            if not bitstreamRE.search(line):
                # if no bitstream ID, don't go any further
                continue
            try:
                p = log_parser(line)
            except apache_log_parser.LineDoesntMatchException:
                print("failed to parse '{0}'".format(line), file=sys.stderr)
                continue
            yield p

def create_log_parser():
    "Create parser for apache log entries (webfaction default)"
    # apache config:
    # %{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"
    format_string = r'%a %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"'
    log_parser = apache_log_parser.make_parser(format_string)
    return log_parser


from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

from .spiders import DocScraperSpider

def crawl(domains,
          start_urls=[],
          directory='./output',
          extensions=['.pdf', '.docx', '.doc', '.txt'],
          robotstxt_obey=True,
          download_delay=0,
          time_range=None):
    """ Run the crawler from a Python script.

    :param domains: the domains allowed to be crawled
    :type domains: list
    :param directory: the output directory for downloaded files
    :type directory: str
    :param extensions: the document extension types to download
    :type extensions: list
    :param robotstxt_obey: whether to obey robots.txt instructions
    :type robotstxt_obey: bool
    :param wayback_machine_time_range: dates for crawling the wayback machine
    :type wayback_machine_time_range: tuple

    """
    settings = get_project_settings()

    settings['ROBOTSTXT_OBEY'] = robotstxt_obey
    settings['DOWNLOAD_DELAY'] = download_delay

    # Set directory path for file downloads
    settings['FILES_STORE'] = directory

    settings['FEEDS'] = {
        '{}/file-listing.csv'.format(directory): {'format': 'csv'}
    }
    settings['FEED_EXPORT_FIELDS'] = ['domain', 'url', 'relative_path',
                                      'checksum', 'status', 'url_date',
                                      'filetype', 'filename']

    if time_range is not None:
        settings['DOWNLOADER_MIDDLEWARES'] = {
            'scrapy_wayback_machine.WaybackMachineMiddleware': 5
        }
        settings['WAYBACK_MACHINE_TIME_RANGE'] = time_range

    process = CrawlerProcess(settings)
    process.crawl(DocScraperSpider,
                  domains,
                  start_urls,
                  directory=directory,
                  extensions=extensions,
                  time_range=time_range
                  )

    process.start()

    return


import subprocess
import os
import re
import abc
import datetime

class BaseBackend(object):
    __metaclass__=abc.ABCMeta

    @abc.abstractmethod
    def create_tmp_file(self, version_dir):
        return

    @abc.abstractmethod
    def get_parsed_commit(self):
        return

class SVNBackend(BaseBackend):
    """
    svn log |grep [0-9] | trac
    """
    TEMP_FILENAME = 'svn_log_tmp.txt'
    DIR = '/tmp'

    def create_tmp_file(self, version_dir):
        os.chdir(version_dir)
        result = subprocess.\
            call("svn log | grep '^\\r[0-9]' | tac | awk '{print $3,$5}' > %s/%s"\
                % (self.DIR, self. TEMP_FILENAME), shell=True)

    def get_parsed_commit(self):
        """
        file format: 'dev  %Y-%m-%d'
        """
        f = open('%s/%s' % (self.DIR, self.TEMP_FILENAME), 'r')
        for line in f:
            info = line.split(' ')
            yield (info[0], datetime.datetime.strptime(re.sub(r'\n',
                                                      '', info[1]),
                                                      '%Y-%m-%d'))
        f.close()

class GitBackend(BaseBackend):
    """
    git log | egrep 'Author|Date' | sed '$!N;s/\n/ /
    """
    TEMP_FILENAME = 'git_log_tmp.txt'
    DIR = '/tmp'

    def create_tmp_file(self, version_dir):
        "git log | egrep 'Author|Date' | sed '$!N;s/\n/ /' | awk '{print $2,$6,$7,$9}'"
        os.chdir(version_dir)
        subprocess.\
            call("git log | egrep 'Author|Date'"
                    "| sed '$!N;s/\\n/ /' | "
                    "tac |"
                    "awk '{print $2,$6,$7,$9}' > %s/%s"
                    % (self.DIR, self.TEMP_FILENAME),
                    shell=True)

    def get_parsed_commit(self):
        f = open('%s/%s' % (self.DIR, self.TEMP_FILENAME), 'r')
        for line in f:
            info = line.split(' ')
            yield (info[0], datetime.datetime.strptime(
                re.sub('\n', '', ' '.join(info[1:])), '%b %d %Y'))
        f.close()


# coding: utf-8

# In[13]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_selection import SelectKBest, chi2, mutual_info_classif
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import GridSearchCV
import os
import csv

# In[2]:

def setProportion(features, labels, samples):
    pos_indexes = labels[labels==1].index
    neg_indexes = labels[labels==0].sample(n=samples, replace=False, random_state=0).index
    combine = np.concatenate((pos_indexes,neg_indexes))
    balanced_features = features.loc[combine]
    balanced_labels = labels.loc[combine]
    return balanced_features, balanced_labels

# In[3]:

#Normalization
def preprocess(data):
    scaler = MinMaxScaler()
    scaled_features = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)
    return scaled_features, scaler

# In[4]:

def selectKBest(features, labels, parameters):
    feat_selector = SelectKBest(parameters["score_func"], parameters["kbest"])
    feat_selector.fit_transform(features, labels)
    #Getting indexes of the most important features
    imp_columns =  feat_selector.get_support(indices=True)
    best_features = features.iloc[:, imp_columns]
    return best_features, feat_selector

# In[5]:

def reduceDimensions(data):
    pca = PCA(0.9)
    reduced_features = pca.fit_transform(data)
    reduced_features = pd.DataFrame(reduced_features)
    return reduced_features, pca

# In[6]:

train_data = pd.read_csv("aps_failure_training_set.csv", na_values='na')
test_data = pd.read_csv("aps_failure_test_set.csv", na_values='na')
print(train_data.head())
print(test_data.head())
    #Filling missing values with the median
train_data.fillna(train_data.median(), inplace=True)
test_data.fillna(train_data.median(), inplace=True)
    #Preprocessing datasets
train_labels = train_data['class']
test_labels = test_data['class']
train_features = train_data.drop(columns='class')
test_features = test_data.drop(columns='class')
    #Convert class labels to numeric value for the models to train and test on
train_labels.replace({'neg':0, 'pos':1}, inplace=True)
test_labels.replace({'neg':0, 'pos':1}, inplace=True)

# In[21]:

def main(model, parameters,train_data, test_data, train_labels, test_labels):
    if(model == 'RF'):
        best_train_features, feat_selector  = selectKBest(train_features, train_labels, parameters)
        balanced_features, balanced_labels = setProportion(best_train_features, train_labels, parameters["samples"])
        rfc = RandomForestClassifier(random_state=0)
#         print(balanced_features.shape)
        rfc.fit(balanced_features, balanced_labels)
        best_test_features = feat_selector.transform(test_features)
        #Executa grid search com cross validation
        prediction = rfc.predict(best_test_features)
        #report = classification_report(test_labels, prediction)
        #print(report)
        with open('RF.csv', 'w') as f:
            writer = csv.writer(f, delimiter=',')
            writer.writerows(zip(prediction,test_labels))

        cm = confusion_matrix(test_labels, prediction).ravel()
        print("Confusion matrix:")
        print(cm)
        score = cm[1]*10 + cm[2]*500
        print("Score:",score)

        return score
    elif(model == "SVM"):
        balanced_features, balanced_labels = setProportion(train_features, train_labels, parameters["samples"])
        scaled_train_features, scalar = preprocess(balanced_features)
        scaled_test_features = scalar.transform(test_features)
        reduced_train_features, pca = reduceDimensions(scaled_train_features)
        svc = svm.SVC()
        svc.fit(reduced_train_features, balanced_labels)
        reduced_test_features = pca.transform(scaled_test_features)
        prediction = svc.predict(reduced_test_features)
        cm = confusion_matrix(test_labels, prediction).ravel()
        print("Confusion matrix:")
        print(cm)
        score = cm[1]*10 + cm[2]*500
        print("Score:",score)

        return score
#         print(cm)

# In[8]:

# parameters = {'kbest':150, 'score_func':chi2, 'samples': 1000}
# main('RF', parameters,train_data, test_data, train_labels, test_labels)
# output = []
# for parameter_number in range(170,1,-1):
#     print("-----")
#     print("Number of parameters:",parameter_number)
#     parameters = {'kbest':parameter_number, 'score_func':chi2, 'samples': 1000}
#     score=main('RF', parameters,train_data, test_data, train_labels, test_labels)
#     output.append((parameter_number,score))
# print(output)

# In[9]:

# # parameters = {'kbest':84, 'score_func':chi2, 'samples': 1000}
# output = []
# for sample_size in range(5000,500,-100):
#     parameters = {'kbest':84, 'score_func':chi2, 'samples': sample_size}
#     score = main('SVM', parameters,train_data, test_data, train_labels, test_labels)
#     output.append((sample_size,score))
# print(output)

# In[23]:

parameters = {'kbest':110, 'score_func':chi2, 'samples': 1000}
main('RF', parameters,train_data, test_data, train_labels, test_labels)


import numpy as np  # to work with arrays
import matplotlib.pyplot as plt  # to plot
import streamlit as st  # to build UI
import tensorflow as tf
from PIL import Image  # to work with images

# let's load the model
model = tf.keras.models.load_model('cifar10_model.h5')

def main():
    st.title("Image Classifier")
    st.write("Using CIFAR_10 classes to classify your image!")

    file = st.file_uploader("upload an image", type=['jpg', 'png'])
    if file:
        # to recognize/read and load the file uploaded as an image into a variable image
        image = Image.open(file)
        # to actually display the image uploaded | second parameter is to correctly fit the image
        st.image(image, use_column_width=True)

        # now we have to resize the image so that the ML model can take it as an input
        # we specified the image input as 32x32 and 3 color channels in the model, therefore:
        resized_image = image.resize((32, 32))
        st.text('Your resized image passed as input to the model is shown below.')
        st.image(resized_image)  # to test display the resized image

        # refer info.txt for explanation
        # to normalise the resized image
        img_array = np.array(resized_image) / 255
        # now that we normalised and resized, we need the input to be in proper format, so,
        img_array = img_array.reshape((1, 32, 32, 3))  # 1 image 32x32 size 3 color channels

        # using the in-built predict function of tf and keras to make predictions using the model
        predictions = model.predict(img_array)
        cifar10_classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

        # to show users the actual percentage
        st.text("Percentage")
        st.write(predictions*100)

        st.text("Bar Graph Representation")
        # using matplotlib to plot bar graphs showing the confidence of prediction in each class
        # fig for figure, ax for axes
        fig, ax = plt.subplots()
        # create an array of integers based on length of cifar10_classes variable => 0-9
        y_pos = np.arange(len(cifar10_classes))
        # horizontal bar graph using bar h, y_pos represents position of each bar: here we have bars at 0, 1, 2 position
        # all the way to 9, predictions[i] contains predictions/confidence scores of each class also it is an
        # iterable therefore each bar will have its own prediction
        ax.barh(y_pos, predictions[0], align="center")
        # to label each bar
        ax.set_yticks(y_pos)
        ax.set_yticklabels(cifar10_classes)
        # labels read top-to-bottom
        ax.invert_yaxis()
        ax.set_xlabel('Probability')
        ax.set_title('Which CIFAR_10 class does your image belong to?')

        st.pyplot(fig)

        # trying to plot a pie chart
        fig1, ax1 = plt.subplots()
        ax1.pie(predictions[0], labels=cifar10_classes, autopct='%1.1f%%')

        st.pyplot(fig1)
    else:
        st.text("Please upload an image file.")

# to invoke or call the main function
if __name__ == '__main__':
    main()


from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static

from filebrowser.sites import site

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^$', 'pmsal.core.views.home', name='home'),
    # url(r'^institucional/', 'canaa.core.views.institutional',
    #     name='institutional'),

    url(r'^a-prefeitura/', 'pmsal.core.views.city', name='city'),
    url(r'^contato/', 'pmsal.core.views.contact', name='contact'),
    url(r'^transparencia/', 'pmsal.core.views.transparency',
        name='transparency'),

    url(r'^prefeitura/(?P<slug>[-\w]+)/$', 'pmsal.core.views.content',
        name='prefeitura'),
    url(r'^imprensa/(?P<slug>[-\w]+)/$', 'pmsal.core.views.content',
        name='imprensa'),
    url(r'^secretaria/(?P<slug>[-\w]+)/$', 'pmsal.core.views.content',
        name='secretaria'),

    url(r'^agenda/', include('pmsal.event.urls', namespace='event')),
    url(r'^noticias/', include('pmsal.blog.urls', namespace='blog')),
    url(r'^licitacoes/', include('pmsal.bid.urls', namespace='bid')),

    url(r'^admin/filebrowser/', include(site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^admin/', include(admin.site.urls)),

    # tinymce
    url(r'^tinymce/', include('tinymce.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# )


#! /usr/bin/env python3
# -*- coding: UTF-8 -*-

import StaticInfo

class TraceEvaluate:
    """ TraceEvaluate merges 'raw events' (aka events from the trace reader, with only ids)
        with the staticInfo (extracted from the goil generated file).
        It adjusts the current running task from events.
    """
    def __init__(self,staticInfo):
        self.staticInfo = staticInfo
        self.runningTask = -1 #unknown task (application may run before, so it's not necessary idle)

    def evaluate(self,rawEvent):
        '''evaluate one raw event, and return event with real names'''
        try:
            ts = rawEvent['ts']
            rawType = rawEvent['type']
            if rawType == 'proc':        #proc state udpdate
                i = int(rawEvent['proc_id'])
                st= int(rawEvent['target_state'])
                procName  = self.staticInfo.procNames[i]
                stateName = self.staticInfo.procStates[st]
                event = {'ts':ts,'type':rawType ,'id':i, 'state':st, 'procName':procName, 'stateName':stateName}
                if stateName=='RUNNING': #//change to running
                    self.runningTask = i
            elif rawType == 'resource': #resources
                i = int(rawEvent['resource_id'])
                st= int(rawEvent['target_state'])
                resourceName  = self.staticInfo.resourceNames[i]
                stateName = self.staticInfo.resourceStates[st]
                procId = self.runningTask
                if procId == -1: #unknown
                    procName  = '<unknown>'
                    #found = True #task unknown => cannot check anything
                else:
                    found = False
                    procName  = self.staticInfo.procNames[procId]
                    tasksAllowed = self.staticInfo.staticInfo['resource'][i]['TASKUSAGE']
                    for task in tasksAllowed:
                        if task['VALUE']==procName:
                            found = True
                    if not found:
                        print('ERROR configuration: the task {0} is not allowed to access resource {1}, at date {2}'.format(procName,resourceName,ts))
                event = {'ts':ts,'type':rawType, 'procName':procName, 'state':st, 'resourceName':resourceName, 'stateName':stateName}
            elif rawType == 'timeobj': #alarm expire
                i = int(rawEvent['timeobj_id'])
                to = self.staticInfo.timeObjNames[i]
                kind = rawEvent['kind']
                evType = rawType+'_'+kind
                if kind == 'expire':
                    event = {'ts':ts,'type':evType, 'id':i, 'toName':to}
                elif kind == 'update_state':
                    toState = int(rawEvent['target_state'])
                    toStateName = self.staticInfo.timeObjStates[toState]
                    event = {'ts':ts,'type':evType, 'id':i, 'toName':to, 'state':toState, 'toStateName':toStateName}
                else:
                    print('ERROR unhandled alarm kind: {0}'.format(rawEvent['kind']))
                    event = {'ts':ts,'type':'trace','info':evType}
            elif rawType == 'event': #events (send/reset)
                evtMask = int(rawEvent['event'])
                kind = rawEvent['kind']
                ok = True
                evType = rawType+'_'+kind
                if kind == 'set': #set event
                    target  = int(rawEvent['target_task_id'])
                    evtName = self.staticInfo.getEventName(target,evtMask)
                    procName  = self.staticInfo.procNames[target]
                    event = {'ts':ts, 'type':evType,'proc':target, 'evtMask':evtMask,
                            'procName':procName, 'evtName':evtName}
                elif kind == 'reset': #reset event
                    target  = self.runningTask
                    if target == -1: #unknown
                        procName = '<unknown>'
                        evtName = '<unknown>'
                    else:
                        evtName = self.staticInfo.getEventName(target,evtMask)
                        procName  = self.staticInfo.procNames[target]
                    event = {'ts':ts, 'type':evType,'proc':target, 'evtMask':evtMask,
                             'procName':procName, 'evtName':evtName}
                else:
                    print('ERROR unhandled event kind: {0}'.format(rawEvent['kind']))
                    event = {'ts':ts,'type':'trace','info':evType}
            elif rawType == 'message': #message
                i = int(rawEvent['msg_id'])
                kind = rawEvent['kind']
                ok = True
                evType = rawType
                if kind[:4] == 'send':
                    msgName = self.staticInfo.msgSendNames[i]
                    evType = rawType+'_'+kind[:4]
                    event = {'ts':ts, 'type':evType, 'id':i, 'msgName':msgName,'kind':kind}
                elif kind == 'receive': #receive message
                    msgName = self.staticInfo.msgRcvNames[i]
                    evType = rawType+'_'+kind
                    event = {'ts':ts, 'type':evType, 'id':i, 'msgName':msgName,'kind':kind}
                else:
                    print('ERROR unhandled message kind: {0}'.format(rawEvent['kind']))
                    event = {'ts':ts,'type':'trace','info':evType}
            elif rawType == 'ioc':
                i = int(rawEvent['ioc_id'])
                iocName = self.staticInfo.iocNames[i]
                evType = rawType+'_'+kind
                event = {'ts':ts, 'type':evType, 'id':i, 'iocName':iocName}
            elif rawType == 'overflow': #overflow
                event = {'ts':ts,'type':rawType}
            elif rawType == 'trace': #communication pb with trace (serial,…)
                event = {'ts':ts,'type':rawType,'info':'communication'}
            else:
                print('ERROR unhandled type: {0}'.format(rawType))
                event = {'ts':ts,'type':rawType}
            return event
        except IndexError:
            print('ERROR when decoding event: index out of range. Raw event is {0}'.format(rawEvent))


# Name: Syed Faysel Ahammad Rajo
# Date: November 22, 2021 @ 2:19 AM
# CodeForces: 460A - Vasya and Socks

n, m = [int(i) for i in input().split()]

days =n
es2 = days//m
es1 =0

while True:
    es1 = es2
    days =n+es1
    es2 = days//m

    if es2==es1:
        print(days)
        break
# Code executed on my terminal successfully

# Note to self: It was really hectic for me. It took near 4-5 hours to think... Finally used the idea of swaping variables.


juli = 7
money = 0
sum = 0
i = 1
while i<= 60:
	if juli <= 6:
		money = 3
	elif juli >6 and juli <=12:
		money = 4
	elif juli >12 and juli <=22:
		money = 5
	elif juli >22 and juli <=32:
		money = 6
	elif juli >32:
		if (juli - 32)%20 == 0:
			money = 6+(juli-32)/20
		else:
			money = 6+int(juli -32)/20+1

	if sum >= 100 and sum < 150:
		money = money*0.8
	elif sum>=150 and sum <400:
		money = money*0.5

	sum = sum + money

	i+=1
print("钱是%.02f"%sum)


from os import P_NOWAIT, name
from sys import argv, exit

import logging
from typing import TYPE_CHECKING

logging.basicConfig(
    level=logging.DEBUG,
    filename="log/log-parser.txt",
    filemode="w",
    format="%(filename)10s:%(lineno)4d:%(message)s"
)
log = logging.getLogger()

# Importando o YACC
import ply.yacc as yacc

# Importando minha lexica
from lexica import tokens

# Importando as coisas pra fazer a árvore
from mytree import MyNode
from anytree.exporter import DotExporter, UniqueDotExporter
from anytree import RenderTree, AsciiStyle, node

# Variável que guarda se teve algum erro

erro = False

# Sub-árvore.
#       (programa)
#           |
#   (lista_declaracoes)
#     /     |      \
#   ...    ...     ...
def p_programa(p):
    """programa : lista_declaracoes"""
    global root

    programa = MyNode(name='programa', type='PROGRAMA')

    root = programa
    p[0] = programa
    p[1].parent = programa

# Sub-árvore.
#    (lista_declaracoes)                          (lista_declaracoes)
#          /           \                                    |
# (lista_declaracoes)  (declaracao)                    (declaracao)
def p_lista_declaracoes(p):
    """lista_declaracoes : lista_declaracoes declaracao
                        | declaracao
    """
    pai = MyNode(name='lista_declaracoes', type='LISTA_DECLARACOES')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai

# Sub-árvore.
#      (declaracao)
#           |
#  (declaracao_variaveis ou
#   inicializacao_variaveis ou
#   declaracao_funcao)
def p_declaracao(p):
    """declaracao : declaracao_variaveis
                | inicializacao_variaveis
                | declaracao_funcao
    """
    pai = MyNode(name='declaracao', type='DECLARACAO')
    p[0] = pai
    p[1].parent = pai

# Sub-árvore.
#      (declaracao_variaveis)
#      /         |           \
# (tipo)    (DOIS_PONTOS)    (lista_variaveis)
#                |
#
def p_declaracao_variaveis(p):
    """declaracao_variaveis : tipo DOIS_PONTOS lista_variaveis"""
    pai = MyNode(name='declaracao_variaveis', type='DECLARACAO_VARIAVEIS')
    p[0] = pai
    p[1].parent = pai

    dois_pontos = MyNode(name='dois_pontos', type='DOIS_PONTOS', parent=pai)
    dois_pontos_simbolo = MyNode(name=p[2], type='SIMBOLO', parent=dois_pontos)
    p[2] = dois_pontos

    p[3].parent = pai

def p_declaracao_variaveis_error(p):
    """declaracao_variaveis : tipo DOIS_PONTOS error"""
    print('Erro na declaração de variável')
    error_line = p.lineno(2)
    father = MyNode(name='ERROR::{}'.format(error_line), type='ERROR')
    logging.error(
        "Syntax error parsing index rule at line {}".format(error_line))
    parser.errok()
    p[0] = father

# Sub-árvore.
#   (inicializacao_variaveis)
#              |
#         (atribuicao)
def p_inicializacao_variaveis(p):
    """inicializacao_variaveis : atribuicao"""
    pai = MyNode(name='inicializacao_variaveis', type='INICIALIZACAO_VARIAVEIS')

    p[0] = pai
    p[1].parent = pai

# Sub-árvore.
#                    (lista_variaveis)
#                             |
#                   /                   \
# (lista_variaveis) (',') (var)        (var)

def p_lista_variaveis(p):
    """lista_variaveis : lista_variaveis VIRGULA var
                        | var
    """

    pai = MyNode(name='lista_variaveis', type='LISTA_VARIAVEIS')
    p[0] = pai
    p[1].parent = pai
    if len(p) > 2:
        virgula = MyNode(name='virgula', type='VIRGULA', parent=pai)
        virgula_simbolo = MyNode(name=',', type='simbolo', parent=virgula)
        p[2] = virgula

        p[3].parent = pai

# Sub-árvore.
#        (var)
#          |
#   /              \
# (ID)         (ID)(indice)

def p_var(p):
    """var : ID
            | ID indice"""
    pai = MyNode(name='var', type='VAR')
    p[0] = pai

    node_id = MyNode(name='ID', type='ID', parent=pai)
    node_id_simbolo = MyNode(name=p[1], type='SIMBOLO', parent=node_id)
    p[1] = node_id

    if len(p) > 2:
        p[2].parent = pai

# Sub-árvore
#                        (indice)
#                            |
#              /                        \
# (indice)([)(expressao)(])      ([)(expressao)(])
#

def p_indice(p):
    """indice : indice ABRE_COLCHETE expressao FECHA_COLCHETE
                | ABRE_COLCHETE expressao FECHA_COLCHETE
    """
    pai = MyNode(name='indice', type='INDICE')
    p[0] = pai
    if len(p) == 5:
        p[1].parent = pai

        abre_colchete = MyNode(name='abre_colchete', type='ABRE_COLCHETE', parent=pai)
        abre_colchete_simbolo = MyNode(name='[', type='SIMBOLO', parent=abre_colchete)

        p[2] = abre_colchete

        p[3].parent = pai

        fecha_colchete = MyNode(name='fecha_colchete', type='FECHA_COLCHETE', parent=pai)
        fecha_colchete_simbolo = MyNode(name=']', type='SIMBOLO', parent=fecha_colchete)

        p[4] = fecha_colchete
    else:
        abre_colchete = MyNode(name='abre_colchete', type='ABRE_COLCHETE', parent=pai)
        abre_colchete_simbolo = MyNode(name='[', type='SIMBOLO', parent=abre_colchete)

        p[1] = abre_colchete

        p[2].parent = pai

        fecha_colchete = MyNode(name='fecha_colchete', type='FECHA_COLCHETE', parent=pai)
        fecha_colchete_simbolo = MyNode(name=']', type='SIMBOLO', parent=fecha_colchete)

        p[3] = fecha_colchete

def p_indice_error(p):
    """indice : ABRE_COLCHETE error FECHA_COLCHETE
                | indice ABRE_COLCHETE error FECHA_COLCHETE
    """

    print("Erro na definicao do indice. Expressao ou indice.")

    # print("Erro:p[0]:{p0}, p[1]:{p1}, p[2]:{p2}, p[3]:{p3}".format(
    #     p0=p[0], p1=p[1], p2=p[2], p3=p[3]))
    error_line = p.lineno(2)
    father = MyNode(name='ERROR::{}'.format(error_line), type='ERROR')
    logging.error(
        "Syntax error parsing index rule at line {}".format(error_line))
    parser.errok()
    p[0] = father

# Sub-árvore:
#    (tipo)
#      |
#  (FLUTUANTE)
def p_tipo(p):
    """tipo : INTEIRO
        | FLUTUANTE
    """

    pai = MyNode(name='tipo', type='TIPO')
    p[0] = pai

    if p[1] == 'inteiro':
        inteiro = MyNode(name='INTEIRO', type='INTEIRO', parent=pai)
        inteiro_simbolo = MyNode(name=p[1], type=p[1].upper(), parent=inteiro)
        p[1] = inteiro

    else:
        flutuante = MyNode(name='FLUTUANTE', type='FLUTUANTE', parent=pai)
        flutuante_simbolo = MyNode(name=p[1], type=p[1].upper(), parent=flutuante)
        p[1] = flutuante

# Sub-árvore:
#        (declaracao_funcao)
#                 |
#          /              \
# (tipo) (cabecalho)    (cabecalho)

def p_declaracao_funcao(p):
    """declaracao_funcao : tipo cabecalho
                        | cabecalho
    """
    pai = MyNode(name='declaracao_funcao', type='DECLARACAO_FUNCAO')
    p[0] = pai
    p[1].parent = pai

    if len(p) == 3:
        p[2].parent = pai

# Sub-árvore:
#                (cabecalho)
#                      |
# (ID) ('(') (lista_parametros)(')')(corpo)(FIM)

def p_cabecalho(p):
    """cabecalho : ID ABRE_PARENTESE lista_parametros FECHA_PARENTESE corpo FIM"""
    pai = MyNode(name='cabecalho', type='CABECALHO')
    p[0] = pai

    node_id = MyNode(name="ID", type='ID', parent=pai)
    node_id_simbolo = MyNode(name=p[1], type='ID', parent=node_id)
    p[1] = node_id

    abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
    abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
    p[2] = abre_parentese

    p[3].parent = pai

    fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
    fecha_parentese_simbolo = MyNode(name=")", type='SIMBOLO', parent=fecha_parentese)
    p[4] = fecha_parentese

    p[5].parent = pai

    fim = MyNode(name='FIM', type='FIM', parent=pai)
    fim_simbolo = MyNode(name='fim', type='FIM', parent=fim)
    p[6] = fim

# Sub-árvore:
#                                      (lista_parametros)
#                                              |
#                      /                       |          \
# (lista_parametros) (',') (parametro)    (parametro)   (vazio)
def p_lista_parametros(p):
    """lista_parametros : lista_parametros VIRGULA parametro
                    | parametro
                    | vazio
    """

    pai = MyNode(name='lista_parametros', type='LISTA_PARAMETROS')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        virgula = MyNode(name='virgula', type='VIRGULA', parent=pai)
        virgula_simbolo = MyNode(name=',', type='SIMBOLO', parent=virgula)
        p[2] = virgula

        p[3].parent = pai

#                (parametro)
#                     |
#          /                      \
# (tipo) (":") (ID)     (parametro) ("[")("]")
def p_parametro(p):
    """parametro : tipo DOIS_PONTOS ID
                | parametro ABRE_COLCHETE FECHA_COLCHETE
    """
    pai = MyNode(name='parametro', type='PARAMETRO')
    p[0] = pai
    p[1].parent = pai
    if p[2] == ':':
        dois_pontos = MyNode(name="dois_pontos", type='DOIS_PONTOS', parent=pai)
        dois_pontos_simbolo = MyNode(name=":", type='SIMBOLO', parent=dois_pontos)
        p[2] = dois_pontos

        node_id = MyNode(name='id', type='ID', parent=pai)
        filho_id = MyNode(name=p[3], type='ID', parent=node_id)
        p[3] = dois_pontos
    else:
        abre_colchete = MyNode(name='abre_colchete', type='ABRE_COLCHETE', parent=pai)
        abre_colchete_simbolo = MyNode(name='[', type='SIMBOLO', parent=abre_colchete)
        p[2] = abre_colchete

        fecha_colchete = MyNode(name='fecha_colchete', type='FECHA_COLCHETE', parent=pai)
        fecha_colchete_simbolo = MyNode(name=']', type='SIMBOLO', parent=fecha_colchete)
        p[2] = fecha_colchete

#             (corpo)
#                |
#        /              \
# (corpo) (acao)      (vazio)

def p_corpo(p):
    """corpo : corpo acao
            | vazio
    """
    pai = MyNode(name='corpo', type='CORPO')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai

def p_acao(p):
    """acao : expressao
        | declaracao_variaveis
        | se
        | repita
        | leia
        | escreva
        | retorna
    """
    pai = MyNode(name='acao', type='ACAO')
    p[0] = pai
    p[1].parent = pai

# Sub-árvore:
#       ________ (se) ________________________________
#      /    /          \      \         \      \      \
# (SE) (expressao)  (ENTAO)  (corpo) (SENAO) (corpo) (FIM)
#  |       |           |
# (se)   (...)      (então) ....
def p_se(p):
    """se : SE expressao ENTAO corpo FIM
          | SE expressao ENTAO corpo SENAO corpo FIM
    """
    pai = MyNode(name='se', type='SE')
    p[0] = pai

    se = MyNode(name='se', type='SE', parent=pai)
    se_simbolo = MyNode(name=p[1], type='SE', parent=se)
    p[1] = se

    p[2].parent = pai

    entao = MyNode(name='entao', type='ENTAO', parent=pai)
    entao_simbolo = MyNode(name=p[3], type='ENTAO', parent=entao)
    p[3] = entao

    p[4].parent = pai

    if len(p) == 8:
        senao = MyNode(name='senao', type='SENAO', parent=pai)
        senao_simbolo = MyNode(name=p[5], type='SENAO', parent=senao)
        p[5] = senao

        p[6].parent = pai

        fim = MyNode(name='FIM', type='FIM', parent=pai)
        fim_simbolo = MyNode(name=p[7], type='FIM', parent=fim)
        p[7] = fim
    else:
        fim = MyNode(name='FIM', type='FIM', parent=pai)
        fim_simbolo = MyNode(name=p[5], type='FIM', parent=fim)
        p[5] = fim

def p_se_error(p):
    """se : SE expressao ENTAO corpo SENAO corpo error
    """
    print("Erro na definicao do indice. Expressao ou indice.")

    # print("Erro:p[0]:{p0}, p[1]:{p1}, p[2]:{p2}, p[3]:{p3}".format(
    #     p0=p[0], p1=p[1], p2=p[2], p3=p[3]))
    error_line = p.lineno(2)
    father = MyNode(name='ERROR::{}'.format(error_line), type='ERROR')
    logging.error(
        "Syntax error parsing index rule at line {}".format(error_line))
    parser.errok()
    p[0] = father

def p_repita(p):
    """repita : REPITA corpo ATE expressao"""
    pai = MyNode(name='repita', type='REPITA')
    p[0] = pai

    repita = MyNode(name='REPITA', type='REPITA', parent=pai)
    repita_simbolo = MyNode(name=p[1], type='REPITA', parent=repita)
    p[1] = repita

    p[2].parent = pai

    ate = MyNode(name='ATE', type='ATE', parent=pai)
    ate_simbolo = MyNode(name=p[3], type='ATE', parent=ate)
    p[3] = repita

    p[4].parent = pai

def p_atribuicao(p):
    """atribuicao : var ATRIBUICAO expressao"""
    pai = MyNode(name='atribuicao', type='ATRIBUICAO')
    p[0] = pai

    p[1].parent = pai

    atribuicao = MyNode(name='ATRIBUICAO', type='ATRIBUICAO', parent=pai)
    atribuicao_simbolo = MyNode(name=':=', type='SIMBOLO', parent=atribuicao)
    p[2] = atribuicao

    p[3].parent = pai

def p_leia(p):
    """leia : LEIA ABRE_PARENTESE var FECHA_PARENTESE"""

    pai = MyNode(name='leia', type='LEIA')
    p[0] = pai

    leia = MyNode(name='LEIA', type='LEIA', parent=pai)
    leia_simbolo = MyNode(name=p[1], type='LEIA', parent=leia)
    p[1] = leia

    abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
    abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
    p[2] = abre_parentese

    p[3].parent = pai  # var

    fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
    fecha_parentese_simbolo = MyNode(name=')', type='SIMBOLO', parent=fecha_parentese)
    p[4] = fecha_parentese

def p_escreva(p):
    """escreva : ESCREVA ABRE_PARENTESE expressao FECHA_PARENTESE"""

    pai = MyNode(name='escreva', type='ESCREVA')
    p[0] = pai

    escreva = MyNode(name='ESCREVA', type='ESCREVA', parent=pai)
    escreva_simbolo = MyNode(name=p[1], type='ESCREVA', parent=escreva)
    p[1] = escreva

    abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
    abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
    p[2] = abre_parentese

    p[3].parent = pai

    fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
    fecha_parentese_simbolo = MyNode(name=')', type='SIMBOLO', parent=fecha_parentese)
    p[4] = fecha_parentese

def p_retorna(p):
    """retorna : RETORNA ABRE_PARENTESE expressao FECHA_PARENTESE"""

    pai = MyNode(name='retorna', type='RETORNA')
    p[0] = pai

    retorna = MyNode(name='RETORNA', type='RETORNA', parent=pai)
    retorna_simbolo = MyNode(name=p[1], type='RETORNA', parent=retorna)
    p[1] = retorna

    abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
    abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
    p[2] = abre_parentese

    p[3].parent = pai

    fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
    fecha_parentese_simbolo = MyNode(name=')', type='SIMBOLO', parent=fecha_parentese)
    p[4] = fecha_parentese

def p_expressao(p):
    """expressao : expressao_logica
                    | atribuicao
    """
    pai = MyNode(name='expressao', type='EXPRESSAO')
    p[0] = pai
    p[1].parent = pai

def p_expressao_logica(p):
    """expressao_logica : expressao_simples
                    | expressao_logica operador_logico expressao_simples
    """
    pai = MyNode(name='expressao_logica', type='EXPRESSAO_LOGICA')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai
        p[3].parent = pai

def p_expressao_simples(p):
    """expressao_simples : expressao_aditiva
                        | expressao_simples operador_relacional expressao_aditiva
    """

    pai = MyNode(name='expressao_simples', type='EXPRESSAO_SIMPLES')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai
        p[3].parent = pai

def p_expressao_aditiva(p):
    """expressao_aditiva : expressao_multiplicativa
                        | expressao_aditiva operador_soma expressao_multiplicativa
    """

    pai = MyNode(name='expressao_aditiva', type='EXPRESSAO_ADITIVA')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai
        p[3].parent = pai

def p_expressao_multiplicativa(p):
    """expressao_multiplicativa : expressao_unaria
                               | expressao_multiplicativa operador_multiplicacao expressao_unaria
        """

    pai = MyNode(name='expressao_multiplicativa',
                 type='EXPRESSAO_MULTIPLICATIVA')
    p[0] = pai
    p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai
        p[3].parent = pai

def p_expressao_unaria(p):
    """expressao_unaria : fator
                        | operador_soma fator
                        | operador_negacao fator
        """
    pai = MyNode(name='expressao_unaria', type='EXPRESSAO_UNARIA')
    p[0] = pai
    p[1].parent = pai

    if p[1] == '!':
        negacao = MyNode(name='operador_negacao', type='OPERADOR_NEGACAO', parent=pai)
        negacao_simbolo = MyNode(name=p[1], type='OPERADOR_NEGACAO', parent=negacao)
        p[1] = negacao
    else:
        p[1].parent = pai

    if len(p) > 2:
        p[2].parent = pai

def p_operador_relacional(p):
    """operador_relacional : MENOR
                            | MAIOR
                            | IGUAL
                            | DIFERENTE
                            | MENOR_IGUAL
                            | MAIOR_IGUAL
    """
    pai = MyNode(name='operador_relacional', type='OPERADOR_RELACIONAL')
    p[0] = pai

    if p[1] == "<":
        filho = MyNode(name='MENOR', type='MENOR', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    elif p[1] == ">":
        filho = MyNode(name='MAIOR', type='MAIOR', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    elif p[1] == "=":
        filho = MyNode(name='IGUAL', type='IGUAL', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    elif p[1] == "<>":
        filho = MyNode(name='DIFERENTE', type='DIFERENTE', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    elif p[1] == "<=":
        filho = MyNode(name='MENOR_IGUAL', type='MENOR_IGUAL', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    elif p[1] == ">=":
        filho = MyNode(name='MAIOR_IGUAL', type='MAIOR_IGUAL', parent=pai)
        filho_sym = MyNode(name=p[1], type='SIMBOLO', parent=filho)
    else:
        print('Erro operador relacional')

    p[1] = filho

def p_operador_soma(p):
    """operador_soma : MAIS
                    | MENOS
    """
    pai = MyNode(name='operador_soma', type='OPERADOR_SOMA')
    p[0] = pai

    if p[1] == "+":
        mais = MyNode(name='MAIS', type='MAIS', parent=pai)
        mais_simbolo = MyNode(name='+', type='SIMBOLO', parent=mais)
        p[1] = mais
    else:
        menos = MyNode(name='MENOS', type='MENOS', parent=pai)
        menos_simbolo = MyNode(name='-', type='SIMBOLO', parent=menos)
        p[1] = menos

def p_operador_logico(p):
    """operador_logico : E_LOGICO
                    | OU_LOGICO
    """
    pai = MyNode(name='operador_logico', type='OPERADOR_LOGICO')
    p[0] = pai

    if p[1] == "E":
        node = MyNode(name='E_LOGICO', type='E_LOGICO', parent=pai)
    else:
        node = MyNode(name="OU_LOGICO", type='OU_LOGICO', parent=pai)

    node_simbolo = MyNode(name=p[1], type='SIMBOLO', parent=node)
    p[1] = node

def p_operador_negacao(p):
    """operador_negacao : NEGACAO"""
    pai = MyNode(name='operador_negacao', type='OPERADOR_NEGACAO')
    nao = MyNode(name='NEGACAO', type='NEGACAO', parent=pai)
    nao_simbolo = MyNode(name=p[1], type='SIMBOLO', parent=nao)

    p[1] = nao

def p_operador_multiplicacao(p):
    """operador_multiplicacao : MULTIPLICACAO
                            | DIVISAO
    """
    pai = MyNode(name='operador_multiplicacao', type='OPERADOR_MULTIPLICACAO')
    p[0] = pai

    if (p[1] == '*'):
        node = MyNode(name='MULTIPLICACAO', type='MULTIPLICACAO', parent=pai)
    else:
        node = MyNode(name='DIVISAO', type='DIVISAO', parent=pai)
    node_simbolo = MyNode(name=p[1], type='SIMBOLO', parent=node)
    p[1] = node

def p_fator(p):
    """fator : ABRE_PARENTESE expressao FECHA_PARENTESE
            | var
            | chamada_funcao
            | numero
    """
    pai = MyNode(name='fator', type="FATOR")
    p[0] = pai
    if len(p) > 2:
        abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
        abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
        p[1] = abre_parentese

        p[2].parent = pai

        fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
        fecha_parentese_simbolo = MyNode(name=')', type='SIMBOLO', parent=fecha_parentese)
        p[3] = fecha_parentese
    else:
        p[1].parent = pai

def p_numero(p):
    """numero : NUM_INTEIRO
                | NUM_PONTO_FLUTUANTE
                | NUM_NOTACAO_CIENTIFICA
    """
    pai = MyNode(name='numero', type='NUMERO')
    p[0] = pai

    if str(p[1]).find('.') == -1:
        node = MyNode(name='NUM_INTEIRO', type='NUM_INTEIRO', parent=pai)
    elif str(p[1]).find('e') >= 0:
        node = MyNode(name='NUM_NOTACAO_CIENTIFICA', type='NUM_NOTACAO_CIENTIFICA', parent=pai)
    else:
        node = MyNode(name='NUM_PONTO_FLUTUANTE', type='NUM_PONTO_FLUTUANTE', parent=pai)
    node_simbolo = MyNode(name=p[1], type='VALOR', parent=node)
    p[1] = node

def p_chamada_funcao(p):
    """chamada_funcao : ID ABRE_PARENTESE lista_argumentos FECHA_PARENTESE"""
    pai = MyNode(name='chamada_funcao', type='CHAMADA_FUNCAO')
    p[0] = pai
    if len(p) > 2:
        node_id = MyNode(name='ID', type='ID', parent=pai)
        node_id_simbolo = MyNode(name=p[1], type='ID', parent=node_id)
        p[1] = node_id

        abre_parentese = MyNode(name='ABRE_PARENTESE', type='ABRE_PARENTESE', parent=pai)
        abre_parentese_simbolo = MyNode(name='(', type='SIMBOLO', parent=abre_parentese)
        p[2] = abre_parentese

        p[3].parent = pai

        fecha_parentese = MyNode(name='FECHA_PARENTESE', type='FECHA_PARENTESE', parent=pai)
        fecha_parentese_simbolo = MyNode(name=')', type='SIMBOLO', parent=fecha_parentese)
        p[4] = fecha_parentese
    else:
        p[1].parent = pai

def p_lista_argumentos(p):
    """lista_argumentos : lista_argumentos VIRGULA expressao
                    | expressao
                    | vazio
    """
    pai = MyNode(name='lista_argumentos', type='LISTA_ARGUMENTOS')
    p[0] = pai

    if len(p) > 2:
        p[1].parent = pai

        virgula = MyNode(name='VIRGULA', type='VIRGULA', parent=pai)
        virgula_simbolo = MyNode(name=p[2], type='SIMBOLO', parent=virgula)
        p[2] = virgula

        p[3].parent = pai
    else:
        p[1].parent = pai

def p_vazio(p):
    """vazio : """

    pai = MyNode(name='vazio', type='VAZIO')
    p[0] = pai

def p_error(p):
    if p:
        global erro
        erro = True
        token = p
        print("\nErro:[{line},{column}]: Erro próximo ao token '{token}'".format(
            line=token.lineno, column=token.lexpos, token=token.value))

def main():
    if (len(argv) < 2):
        print("Erro! Informe o nome do arquivo")
        data = open("semantica-testes/sema-003.tpp")
        # exit()
    else:
        data = open(argv[1])

    source_file = data.read()
    parser.parse(source_file)
    global erro

    try:
        if root and root.children != () and erro != False:
            print("Generating Syntax Tree Graph...")
            # DotExporter(root).to_picture(argv[1] + ".ast.png")
            UniqueDotExporter(root).to_picture(argv[1] + ".unique.ast.png")
            # DotExporter(root).to_dotfile(argv[1] + ".ast.dot")
            UniqueDotExporter(root).to_dotfile(argv[1] + ".unique.ast.dot")
            # print(RenderTree(root, style=AsciiStyle()).by_attr())
            print("Graph was generated.\nOutput file: " + argv[1] + ".ast.png")

            DotExporter(root, graph="graph",
                        nodenamefunc=MyNode.nodenamefunc,
                        nodeattrfunc=lambda node: 'label=%s' % (node.type),
                        edgeattrfunc=MyNode.edgeattrfunc,
                        edgetypefunc=MyNode.edgetypefunc).to_picture(argv[1] + ".ast2.png")

            # DotExporter(root, nodenamefunc=lambda node: node.label).to_picture(argv[1] + ".ast3.png")

        else:
            print('\n--------------------------------\n')
            print('Não foi possível gerar a árvore!')
    except NameError as error:
        print("Erro: " + str(error))
        print('Não foi possível gerar a árvore!')

# Build the parser.
# __file__ = "02-compiladores-analise-sintatica-tppparser.ipynb"
# parser = yacc.yacc(optimize=True, start='programa', debug=True, debuglog=log)
parser = yacc.yacc(method="LALR", optimize=True, start='programa', debug=True,
                   debuglog=log, write_tables=False, tabmodule='tpp_parser_tab')

def retorna_root(filename):
    if len(filename) == 0:
        print("Erro! Informe o nome do arquivo")
        exit()
    data = open(filename)

    source_file = data.read()
    parser.parse(source_file)

    UniqueDotExporter(root).to_picture(filename + ".png")
    return root

if __name__ == "__main__":
    main()


"""
计算器
编译者：PengPeng3g
v1.0 增加加法
v2.0 增加减，乘，除法
v3.0 可以多部计算，但需更改代码
v4.0 在v2.0的基础上更改，精简v2.0的代码
v5.0 精简代码
当前版本：v5.0
"""
#加法
diyigejiashu=input('加数')

diergejiashu=input('加数')

print('和', int(diyigejiashu)+int(diergejiashu))

#除法
beichushu=input('被除数')

chushu=input('除数')

print('商',int(beichushu)/int(chushu))

#乘法
diyigechengshu=input('因数')

diergechengshu=input('因数')

print('积',int(diyigechengshu)*int(diergechengshu))

#减法
beijianshu=input('被减数')

jianshu=input('减数')

print('差',int(beijianshu)-int(jianshu))


#!/usr/bin/python3

import sys

x = 0
y = 0
angle = 0

for line in sys.stdin:
    direction = line[0:line.index(' ')]
    magnitude = int(line[line.index(' ') + 1:])

    if direction == 'forward':
        x += magnitude
        y += magnitude * angle

        if y < 0:
            y = 0
    elif direction == 'up':
        angle -= magnitude
    elif direction == 'down':
        angle += magnitude
    else:
        raise Exception('unrecognized direction')

print(x * y)


from django.urls import path
from .views import *

app_name = 'expenses'

urlpatterns = [

	# Admin Site URLs

    # Client Site URLs

    # Api Urls
    path('expense/list/', ExpenseListAPIView.as_view(), name="expenses"),
    path('expense/<int:id>/', ExpenseDetailAPIView.as_view(), name="expense"),

]


#! /usr/bin/python
import os, shutil

os.mkdir("_endRuns")
files = os.listdir(".")
filesDendro = [i for i in files if "dendro" in i]

d = dict()
for file in filesDendro:
	thisFile = file.split("run")
	stem = thisFile[0]
	thisRun = int(thisFile[1].split("dendro")[0])
	if stem in d.keys():
		if thisRun > d[stem]:
			d[stem] = thisRun
	else:
		d[stem] = thisRun
	d[stem] = thisRun

for key in d.keys():
	file = key + "run" + str(d[key]) + "dendro-block1.jpg"
	shutil.copy2(file, "_endRuns")


from django.test import TestCase
from django.utils.translation import override

from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (
    build_localized_fieldname,
    get_instance_field_value,
    get_language,
    get_model_field,
    split_translated_fieldname,
)

from .app.models import Blog, Category

class UtilsTest(TestCase):
    def test_get_language(self):
        self.assertEqual(get_language(), "en")

        with override("nl"):
            self.assertEqual(get_language(), "nl")

        with override("id"):
            self.assertEqual(get_language(), "en")

    def test_split_translated_fieldname(self):
        self.assertEqual(split_translated_fieldname("title_nl"), ("title", "nl"))

        self.assertEqual(split_translated_fieldname("full_name_nl"), ("full_name", "nl"))

    def test_transform_translatable_fields(self):
        self.assertEqual(
            transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo"}),
            {"i18n": {"title_nl": "foo"}, "title": "bar"},
        )

    def test_transform_translatable_fields_without_translations(self):
        self.assertEqual(
            transform_translatable_fields(Blog, {"title": "bar", "title_nl": "foo", "i18n": None}),
            {"i18n": {"title_nl": "foo"}, "title": "bar"},
        )

    def test_transform_translatable_fields_keep_translations(self):
        self.assertEqual(
            transform_translatable_fields(
                Blog, {"title": "bar", "title_de": "das foo", "i18n": {"title_nl": "foo"}}
            ),
            {"i18n": {"title_nl": "foo", "title_de": "das foo"}, "title": "bar"},
        )

    def test_build_localized_fieldname(self):
        self.assertEqual(build_localized_fieldname("title", "nl"), "title_nl")
        self.assertEqual(build_localized_fieldname("category__name", "nl"), "category__name_nl")
        self.assertEqual(build_localized_fieldname("title", "id"), "title_ind")
        self.assertEqual(build_localized_fieldname("title", "en-US"), "title_en_US")

    def test_get_model_field(self):
        with self.assertRaises(ValueError):
            get_model_field(object(), "name")
        self.assertEqual(get_model_field(Category, "name"), Category._meta.get_field("name"))
        self.assertEqual(get_model_field(Category, "color"), None)
        self.assertEqual(get_model_field(Blog, "category__name"), Category._meta.get_field("name"))
        self.assertEqual(get_model_field(Blog, "category__color"), None)

    def test_get_instance_field_value(self):
        test = Category(name="test")
        blog = Blog(category=test, title="Python")

        self.assertEqual(get_instance_field_value(Category(), "content"), None)
        self.assertEqual(get_instance_field_value(test, "name"), "test")
        self.assertEqual(get_instance_field_value(blog, "category__name"), "test")
        self.assertEqual(get_instance_field_value(blog, "category__color"), None)


import dataclasses
from typing import Any, Dict, List

from acme import core
from acme import types

from acme.multiagent import types as ma_types

LearnerState = Any

@dataclasses.dataclass
class SynchronousDecentralizedLearnerSetState:
  """State of a SynchronousDecentralizedLearnerSet."""
  # States of the learners keyed by their names.
  learner_states: Dict[ma_types.AgentID, LearnerState]

class SynchronousDecentralizedLearnerSet(core.Learner):
  """Creates a composed learner which wraps a set of local agent learners."""

  def __init__(self,
               learners: Dict[ma_types.AgentID, core.Learner],
               separator: str = '-'):
    """Initializer.

    Args:
      learners: a dict specifying the learners for all sub-agents.
      separator: separator character used to disambiguate sub-learner variables.
    """
    self._learners = learners
    self._separator = separator

  def step(self):
    for learner in self._learners.values():
      learner.step()

  def get_variables(self, names: List[str]) -> List[types.NestedArray]:
    """Return the named variables as a collection of (nested) numpy arrays.

    The variable names should be prefixed with the name of the child learners
    using the separator specified in the constructor, e.g. learner1/var.

    Args:
      names: args where each name is a string identifying a predefined subset of
        the variables. The variables names should be prefixed with the name of
        the learners using the separator specified in the constructor, e.g.
        learner-var if the separator is -.

    Returns:
      A list of (nested) numpy arrays `variables` such that `variables[i]`
      corresponds to the collection named by `names[i]`.
    """
    variables = []
    for name in names:
      # Note: if separator is not found, learner_name=name, which is OK.
      learner_id, _, variable_name = name.partition(self._separator)
      learner = self._learners[learner_id]
      variables.extend(learner.get_variables([variable_name]))
    return variables

  def save(self) -> SynchronousDecentralizedLearnerSetState:
    return SynchronousDecentralizedLearnerSetState(learner_states={
        name: learner.save() for name, learner in self._learners.items()
    })

  def restore(self, state: SynchronousDecentralizedLearnerSetState):
    for name, learner in self._learners.items():
      learner.restore(state.learner_states[name])


from json_generator import *
from wordcloud_generator import *
import course_list_downloader
import os.path
import time

TEST = 0  # for use in test with a few courses
REAL = 1  # for use in constructing the website
OFFER_NOW = 3  # for use when only offer-now courses are analyzed

time_start = time.time()

def course_list_file_reader(mode) -> List[str]:
    """Generate list of course based on mode."""
    if mode == TEST:
        return ['VIC275']
        # return ['CSC265', 'ABP100', 'ECO200', 'MAT235', 'PSY100', 'ENV200']
    if mode == REAL:
        # course_list_file = open("Database/UofT_course_list.txt", "r")
        # course_list_file.close()
        # return course_list_file.read().split('\n')
        return course_list_downloader.UofT_course_generator_list_of_str()
    if mode == OFFER_NOW:
        return course_list_downloader.offer_now_courses()

def course_detail_content_generator() -> Dict[str, Tuple[str, str, str]]:
    """Read from file and generate a dictionary where the key is the course,
    the value is a list of two strings, where the first string is course name
    and the second is description."""
    file = open("Database/UofT_course_detail.txt", "r")
    content = file.read()
    each_courses = content.split('\n\n')
    result = dict()
    for i in each_courses:
        course = i.split('\n')
        if len(course) >= 2 and course[1].isalnum():
            result[course[0]] = ('', '', course[1])
        elif len(course) >= 3 and course[2].isalnum():
            result[course[0]] = (course[1], '', course[2])
        elif len(course) == 4 and course[3].isalnum():
            result[course[0]] = (course[1], course[2], course[3])
        else:
            result[course[0]] = ('', '', '')
        # except IndexError:
        #     try:
        #         result[course[0]] = (course[1], '', )
        #     except IndexError:
        #         result[course[0]] = ('', '')
    file.close()
    return result

# Check if the course calendar file exists.
if not os.path.exists("Database/UofT_course_list.txt"):
    if not os.path.exists("Database/UofT_courses.html"):
        raise FileNotFoundError
    course_list_downloader.UofT_course_generator_file()

# Load the course list.
course_list = course_list_file_reader(REAL)

# Load the course content file.
course_content = course_detail_content_generator()

# Authorization
reader = RedditReader('UofT', ['QCoNFSH3HMntdQ',
                               'Wp0hdaBna71vtZ6SDqEgFUGczzk', 'Test'])

# Open the destination json file
json_file = open("Database/database.json", "w")
json_file.write("{")

# Main loop
last_course = course_list[len(course_list) - 1]
for course_code in course_list:

    # Console status update
    print("Working on the " + course_code + "...\t\t", end='')

    # Start to time it
    start = time.time()

    # Generate the name and description of the course
    try:
        content = course_content[course_code]
    except KeyError:
        print()
        continue

    # Connect reddit and download the posts related to this course.
    course_complex = reader.read_course(course_code)

    # Generate the heat of this course.
    heat = course_complex.course_heat()

    # Generate the wordcloud.
    wordcloud = WordCloudGenerator()
    wordcloud.generate_wordcloud_dict(course_complex, width=1200, height=600)

    # Generate the json piece for this very course.
    course_dict = JSONGenerator().generate_python_dict_one_course(
        course_complex, top_comments_limit=20)
    top_reviews = '['
    reviews = course_dict['top_reviews']
    if reviews:
        top_reviews = "[\n\t\t\t\t[\"" + reviews[0][2].replace('\n',
                                                               '\\n').replace(
            '"', '\\"').replace('\\[', '[').replace('\\]', ']') + \
                      "\",\"" + reviews[0][0].replace('\n', '\\n').replace('"',
                                                                           '\\"').replace(
            '\\[', '[').replace('\\]', ']') + \
                      "\",\"" + reviews[0][1] + "\"]"
        reviews.pop(0)
    for i in reviews:
        s = ",\n\t\t\t\t[\"" + i[2].replace('\n', '\\n').replace('"',
                                                                 '\\"').replace(
            '\\[', '[').replace('\\]', ']') + \
            "\",\"" + i[0].replace('\n', '\\n').replace('"', '\\"').replace(
            '\\[', '[').replace('\\]', ']') + \
            "\",\"" + i[1] + "\"]"
        top_reviews = top_reviews + s
    top_reviews = top_reviews + ']'
    j = "\n\t\"" + course_code + "\":\n\t\t{\n\t\t\t\"cloud_path\":\"" + \
        course_dict['wordcloud_path'] + "\",\n" + "\t\t\t\"name\":\"" + \
        content[0] + "\",\n\t\t\t\"description\":\"" + content[1] + \
        "\",\n\t\t\t\"br_category\":\"" + content[2] + \
        "\",\n\t\t\t\"score\":\"" + str(course_dict['score']) + \
        "\",\n\t\t\t\"heat\":\"" + str(heat) + \
        "\",\n\t\t\t\"top_review\":" + top_reviews + "\n\t\t}"
    if last_course != course_code:
        j = j + ','

    # Write in the json piece to destination file
    json_file.write(j)

    end = time.time()
    print("Finished in " + "%5.2f" % (end - start) + "s.")

json_file.write("\n}")
json_file.close()

time_end = time.time()
print("Total time: " + str(round(time_end - time_start, 2)) + "s.")


import pandas as pd
import sys
import os
import mysql.connector

count = 0

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password=""
)

mycursor = mydb.cursor(dictionary=True)

# create tables if they do not exist
mycursor.execute("use btp")
mycursor.execute("create table if not exists dbpedia_relations(id int primary key AUTO_INCREMENT, lhs varchar(300),binaryRelation varchar(300), rhs varchar(300));")
mycursor.execute("create table if not exists dbpedia_types(id int primary key AUTO_INCREMENT, value varchar(300),typeList varchar(300));")
mycursor.execute("create table if not exists dbpedia_files(id int primary key AUTO_INCREMENT, filename varchar(1000));")

# encode_string is used to escape out strings so that they can be passed in a MySQL query
def encode_string(str):
	ans = ""
	for c in str:
		if c in ['`','"',"'",'\\',]:
			ans += '\\'
		ans += c
	return ans

# insertRelation inserts a triplet into dbpedia_relations table
def insertRelation(lhs, binaryRelation, rhs):
	if type(lhs) != str or type(binaryRelation) != str or type(rhs) != str:
		print(lhs,binaryRelation,rhs)
		return
	query = "insert ignore into dbpedia_relations(lhs,binaryRelation,rhs) values('" + encode_string(lhs) + "','" + encode_string(binaryRelation) + "','" + encode_string(rhs) +"')"
	if len(lhs) > 300 or len(binaryRelation)> 300 or len(rhs) > 300:
		print(query)
	else:
		mycursor.execute(query)

# insertTypes inserts the type list for an entity in the dbpedia_types table
def insertTypes(val, typeList):
	if type(val) != str or type(typeList) != str:
		print(val,typeList)
		return
	query = "insert ignore into dbpedia_types(value,typeList) values('" + encode_string(val) + "','" + encode_string(typeList) +"')"
	if len(val) > 300 or len(typeList)> 300:
		print(query)
	else:
		mycursor.execute(query)

filename = sys.argv[1]
print(filename)

# check if the relations from the file have already been extracted
mycursor.execute("select * from dbpedia_files where filename = "+"'"+ encode_string(filename) +"'")
records = mycursor.fetchall()
isempty = not records

# only iterate if the records are not stored
if isempty:
	# insert the filename into the table so that it is not rerun
	mycursor.execute("insert into dbpedia_files (filename) values ("+"'"+ encode_string(filename) +"')")

	# read the file
	data = pd.read_csv(filename,compression='gzip',dtype=object)
	cols = data.columns

	useColIndexes = []
	useColNames = []
	typeIndex = 0

	idx = 2
	# remove columns that do not correspond to relations
	while idx < len(cols):
		if cols[idx] == '22-rdf-syntax-ns#type_label':
			typeIndex = idx
			break
		if cols[idx].endswith('_label'):
			useColNames.append(cols[idx+1])
			useColIndexes.append(idx)
			idx = idx+2
		else:
			useColNames.append(cols[idx])
			useColIndexes.append(idx)
			idx = idx+1

	# print(useColIndexes,useColNames)
	# print(typeIndex)

	# store all the relations from all the rows
	for index, row in data.iterrows():
		if row['URI'] =='URI' or row['URI'] == 'http://www.w3.org/2002/07/owl#Thing' or pd.isnull(row[1]):
			continue
		elemVal = row[1]
		for x in range(len(useColIndexes)):
			idx = useColIndexes[x]
			name = useColNames[x]
			if pd.isnull(row[idx]):
				continue
			val = row[idx]
			if val[0] == '{':
				for v in (val[1:-1].split('|')):
					insertRelation(elemVal,name,v)
			else:
				insertRelation(elemVal,name,val)

		# insert the type value for the entity
		val = row[typeIndex]
		insertTypes(elemVal,val)
	mydb.commit()
else:
	print(records)


import pygame
import random
import time
import WindowControl

#VARIABLES =======================================
# Enemy Values
enemy_WIDTH = 65
enemy_HEIGHT = 65
enemy_IMAGES = ['Assets/enemy_mouse_brown.png', 'Assets/enemy_mouse_grey.png', 'Assets/enemy_mouse_white.png']
enemy_minSpeed = 0.5
enemy_maxSpeed = 1.2
enemy_maxSpawned = 10
enemy_SPAWNRATE = 1500

#Used to reset enemy stats
enemy_maxSpeed_START = 1.2
enemy_SPAWNRATE_START = 1500

#CLASS CONSTRUCTOR ==============================
# Defines enemy as a Sprite
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load(random.choice(enemy_IMAGES)) #Uses list to make random enemy
        self.rect = self.image.get_rect()
        self.x = WindowControl.window_WIDTH - 30
        self.y = random.randint(0, WindowControl.window_HEIGHT)
        self.rect.x = self.x
        self.rect.y = self.y
        self.speed = random.uniform(enemy_minSpeed, enemy_maxSpeed) #Sets a random speed between minSpeed value and maxSpeed value

    # Reusable code to reset enemy values (based on section)
    def resetPosition(self):
        self.x = WindowControl.window_WIDTH
        self.y = random.randint(0, WindowControl.window_HEIGHT)

    def resetImage(self):
        self.image = self.image = pygame.image.load(random.choice(enemy_IMAGES))
        self.rect = self.image.get_rect()

    def resetSpeed(self):
        self.speed = random.uniform(enemy_minSpeed, enemy_maxSpeed)

    # Functions used to return enemy position values
    def getX(self):
        return self.x

    def getY(self):
        return self.y

    # Used to define enemy movement
    def movement(self):
        self.x = self.x - self.speed #Moves self left based on speed
        self.rect.x = self.x
        self.rect.y = self.y

        # Destroys the sprite if it runs off the left side of the screen
        if (self.rect.right < 0):
            self.kill()

        # Ensures that the enemy does not spawn itself below the max window height
        if(self.rect.bottom > WindowControl.window_HEIGHT):
            self.y = self.y - enemy_HEIGHT

    def update(self):
        self.movement()


from copy import deepcopy
from pathlib import Path

class FileFamily():
    def __init__(self):
        r'''A file family collects multiple asset names sharing the same path.
        '''
        self.path = b""
        self.assets = []

    def set_path(self, path):
        self.path = path

    def add_asset(self, fname):
        if fname not in self.assets:
            self.assets.append(fname)

    def remove_asset(self, fname):
        try:
            self.assets.remove(fname)
            return 1
        except:
            return 0

class FileFamilyManager():
    def __init__(self, data, parent_path=None):
        r'''A file family manager initialises and manages a group of file families.
        Pass in a list of Path objects and a parent Path object
        A parent path is a shared path of all file families if there is one
        '''
        self.file_families = []
        self.parent_path = parent_path

        template = FileFamily()

        for path in data:
            try:
                item = Path(path).relative_to(self.parent_path) #everything after parent path
            except:
                item = Path(path)
            is_path = False
            for ff in self.file_families:
                if item.parent == ff.path:
                    ff.add_asset(item.name)
                    is_path = True
            if not is_path:
                ffobj = deepcopy(template)
                ffobj.set_path(item.parent)
                ffobj.add_asset(item.name)
                self.file_families.append(ffobj)

    def get_num_assets(self):
        numassets = 0
        for family in self.file_families:
            for asset in family.assets:
                numassets += 1
        return numassets

    def remove_asset(self, fpath):
        try:
            item = fpath.relative_to(self.parent_path)
        except:
            item = fpath

        for ff in self.file_families:
            if item.parents[0] == ff.path:
                ff.remove_asset(item.name)


#Setup
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals

# Common imports
import numpy as np
import os

# to make this notebook's output stable across runs
def reset_graph(seed=42):
    tf.reset_default_graph()
    tf.set_random_seed(seed)
    np.random.seed(seed)

# To plot pretty figures
#%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

rep_racine = "C:/Users/domin/Google Drive/Code/git/TestTensorflowJava/TestTensorflowJava"
# Where to save the figures
#PROJECT_ROOT_DIR = "."
PROJECT_ROOT_DIR = rep_racine
CHAPTER_ID = "ann"

def save_fig(fig_id, tight_layout=True):
    path = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id + ".png")
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    plt.savefig(path, format='png', dpi=300)

#Perceptrons
#import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron

iris = load_iris()
X = iris.data[:, (2, 3)]  # petal length, petal width
y = (iris.target == 0).astype(np.int)

per_clf = Perceptron(random_state=42)
print("FutureWarning")
per_clf.fit(X, y)
y_pred = per_clf.predict([[2, 0.5]])

print(y_pred)

# 4
a = -per_clf.coef_[0][0] / per_clf.coef_[0][1]
b = -per_clf.intercept_ / per_clf.coef_[0][1]

axes = [0, 5, 0, 2]

x0, x1 = np.meshgrid(
        np.linspace(axes[0], axes[1], 500).reshape(-1, 1),
        np.linspace(axes[2], axes[3], 200).reshape(-1, 1),
    )
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = per_clf.predict(X_new)
zz = y_predict.reshape(x0.shape)

plt.figure(figsize=(10, 4))
plt.plot(X[y==0, 0], X[y==0, 1], "bs", label="Not Iris-Setosa")
plt.plot(X[y==1, 0], X[y==1, 1], "yo", label="Iris-Setosa")

plt.plot([axes[0], axes[1]], [a * axes[0] + b, a * axes[1] + b], "k-", linewidth=3)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#9898ff', '#fafab0'])

plt.contourf(x0, x1, zz, cmap=custom_cmap, linewidth=5)
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="lower right", fontsize=14)
plt.axis(axes)

save_fig("perceptron_iris_plot")
plt.show()

#Activation functions
def logit(z):
    return 1 / (1 + np.exp(-z))

def relu(z):
    return np.maximum(0, z)

def derivative(f, z, eps=0.000001):
    return (f(z + eps) - f(z - eps))/(2 * eps)

z = np.linspace(-5, 5, 200)

plt.figure(figsize=(11,4))

plt.subplot(121)
plt.plot(z, np.sign(z), "r-", linewidth=2, label="Step")
plt.plot(z, logit(z), "g--", linewidth=2, label="Logit")
plt.plot(z, np.tanh(z), "b-", linewidth=2, label="Tanh")
plt.plot(z, relu(z), "m-.", linewidth=2, label="ReLU")
plt.grid(True)
plt.legend(loc="center right", fontsize=14)
plt.title("Activation functions", fontsize=14)
plt.axis([-5, 5, -1.2, 1.2])

plt.subplot(122)
plt.plot(z, derivative(np.sign, z), "r-", linewidth=2, label="Step")
plt.plot(0, 0, "ro", markersize=5)
plt.plot(0, 0, "rx", markersize=10)
plt.plot(z, derivative(logit, z), "g--", linewidth=2, label="Logit")
plt.plot(z, derivative(np.tanh, z), "b-", linewidth=2, label="Tanh")
plt.plot(z, derivative(relu, z), "m-.", linewidth=2, label="ReLU")
plt.grid(True)
#plt.legend(loc="center right", fontsize=14)
plt.title("Derivatives", fontsize=14)
plt.axis([-5, 5, -0.2, 1.2])

save_fig("activation_functions_plot")
plt.show()

def heaviside(z):
    return (z >= 0).astype(z.dtype)

def sigmoid(z):
    return 1/(1+np.exp(-z))

def mlp_xor(x1, x2, activation=heaviside):
    return activation(-activation(x1 + x2 - 1.5) + activation(x1 + x2 - 0.5) - 0.5)

x1s = np.linspace(-0.2, 1.2, 100)
x2s = np.linspace(-0.2, 1.2, 100)
x1, x2 = np.meshgrid(x1s, x2s)

z1 = mlp_xor(x1, x2, activation=heaviside)
z2 = mlp_xor(x1, x2, activation=sigmoid)

plt.figure(figsize=(10,4))

plt.subplot(121)
plt.contourf(x1, x2, z1)
plt.plot([0, 1], [0, 1], "gs", markersize=20)
plt.plot([0, 1], [1, 0], "y^", markersize=20)
plt.title("Activation function: heaviside", fontsize=14)
plt.grid(True)

plt.subplot(122)
plt.contourf(x1, x2, z2)
plt.plot([0, 1], [0, 1], "gs", markersize=20)
plt.plot([0, 1], [1, 0], "y^", markersize=20)
plt.title("Activation function: sigmoid", fontsize=14)
plt.grid(True)

plt.show()

#FNN for MNIST
#using tf.learn

from tensorflow.examples.tutorials.mnist import input_data

rep_racine
rep_mnist = "{}/{}".format(rep_racine, "data/")
mnist = input_data.read_data_sets(rep_mnist)

X_train = mnist.train.images
X_test = mnist.test.images
y_train = mnist.train.labels.astype("int")
y_test = mnist.test.labels.astype("int")

import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

config = tf.contrib.learn.RunConfig(tf_random_seed=42) # not shown in the config

feature_cols = tf.contrib.learn.infer_real_valued_columns_from_input(X_train)
dnn_clf = tf.contrib.learn.DNNClassifier(hidden_units=[300,100], n_classes=10,
                                         feature_columns=feature_cols, config=config)
dnn_clf = tf.contrib.learn.SKCompat(dnn_clf) # if TensorFlow >= 1.1
dnn_clf.fit(X_train, y_train, batch_size=50, steps=40000)

print("fin using tf.learn")

from sklearn.metrics import accuracy_score

y_pred = dnn_clf.predict(X_test)
print(accuracy_score(y_test, y_pred['classes']))

from sklearn.metrics import log_loss

y_pred_proba = y_pred['probabilities']
print(log_loss(y_test, y_pred_proba))


import math

tournament_count = int(input())
initial_points = int(input())

points = 0
count = 0 #This needs to be introduced here, otherwise, it doesn't work. F.e. if you write it first under if stage_tournament =='W'

for i in range(tournament_count):
    stage_tournament = input()
    total = 0
    average = 0
    if stage_tournament == 'W':
        count += 1
        points += 2000
    if stage_tournament == 'F':
        points += 1200
    if stage_tournament == 'SF':
        points += 720

total = initial_points + points
average = math.floor(points / tournament_count)
percent = count/tournament_count*100

print(f'Final points: {total}')
print(f'Average points: {average}')
print(f'{percent:.2f}%')

#Nailed it.100 out of 100

PythonBasics/8.For Loop - Exercise/8_tennis_ranklist.py


from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from .models import Referral
from .referral import attach_referral

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

class ReferralSerializer(serializers.ModelSerializer):
    referree = serializers.CharField(source='referree.username', read_only=True)
    referrer = serializers.CharField(source='referrer.username')
    ip_address = serializers.CharField(source='referree_ip_address', required=False)

    class Meta:
        model = Referral
        fields = [
            'id',
            'referrer',
            'referree',
            'ip_address'
        ]
        read_only_fields = [
            'id',
        ]

        def create(self, validated_data, *args, **kwargs):
            user = None
            request = self.context.get('request', None)
            if request and hasattr(request, 'user'):
                user = request.user
            else:
                # serializer validation error
                raise Exception("Could not identify the user in request.")

            referrer_username = validated_data.pop('referrer')['username']
            referrer = get_object_or_404(get_user_model(), username=referrer_username)

            # create instance
            instance = attach_referral(referrer=referrer, referree=user, **validated_data)

            return instance

        def update(self, instance, validated_data, *args, **kwargs):
            # serviceunavailableerror
            raise Exception("Cannot edit referrals")


from tkinter import Tk, BOTH, Listbox, StringVar, END
from tkinter.ttk import Frame, Label

class Example(Frame):

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

    def initUI(self):
        self.master.title("ListBox Application")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlet Johansson', 'Rachel', 'Jessica Alba', 'Van Disel']

        lb = Listbox(self)

        for actress in acts:
            lb.insert(END, actress)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)

def main():

    root = Tk()
    ex = Example()
    root.geometry("300x300+300+300")
    root.mainloop()

if __name__ == '__main__':
    main()