import hashlib
import re
from slugify import slugify
from pathlib import Path
import dataflows as DF

from conf import settings
from operators.shil import ORGANIZATION
from srm_tools.update_table import airtable_updater
from srm_tools.processors import update_mapper
from srm_tools.gov_data_proxy import collect_gov_rows

FIELD_RENAME = {
    'name': 'clinic_name',
    'city': 'city',
    'age_group': 'audience',
    'intake_wait': 'intake_wait',
    'phone_numbers': 'phone',
    'expertise': 'specialization',
    'interventions': 'intervention_type',
    'street_address': 'street',
    'hmo': 'HMO_code',
}
HMOS = {
    '1': 'לאומית',
    '2': 'מכבי',
    '3': 'כללית',
    '4': 'מאוחדת',
    '5': 'כל הקופות',
}
MISSING_VALUES = [
    'אין מומחיות מיוחדת',
    'לא קיים',
    'אין נתונים',
    'לא',
    'אין',
    'כל הקופות',
    'כל סוגי הטיפולים',
]
SITUATIONS = {
    'מבוגרים': [
        'human_situations:age_group:adults',
        'human_situations:age_group:young_adults',
        'human_situations:age_group:seniors',
    ],
    'טיפול יום-מבוגרים': [
        'human_situations:age_group:adults',
        'human_situations:age_group:young_adults',
        'human_situations:age_group:seniors',
    ],
    'מבוגרים-יועץ במרפאה ראשונית(ליאזון)': [
        'human_situations:age_group:adults',
        'human_situations:age_group:young_adults',
        'human_situations:age_group:seniors',
    ],
    'ילדים ונוער': [
        'human_situations:age_group:children',
        'human_situations:age_group:teens',
    ],
    'ילדים ונוער-יועץ במרפאה ראשונית(ליאזון)': [
        'human_situations:age_group:children',
        'human_situations:age_group:teens',
    ],
    'טיפול יום-נוער': [
        'human_situations:age_group:teens',
    ],
    'נוער': [
        'human_situations:age_group:teens',
    ]
}
ORGS = {
    'לאומית': dict(
        id='srm0010',
        data=dict(
            name='קופת חולים לאומית - מרפאות בריאות נפש',
            short_name='לאומית',
            phone_numbers='1-700-507-507',
            urls='https://www.leumit.co.il/heb/Rights/mentalhealth/',
        ),
    ),
    'מכבי': dict(
        id='srm0011',
        data=dict(
            name='מכבי שירותי בריאות - מרפאות בריאות נפש',
            short_name='מכבי',
            phone_numbers= '*3555',
            urls='https://www.maccabi4u.co.il/New/eligibilites/2062/',
        ),
    ),
    'כללית': dict(
        id='srm0012',
        data=dict(
            name='שירותי בריאות כללית - מרפאות בריאות נפש',
            short_name='כללית',
            phone_numbers= '*2700',
            url='https://www.clalit.co.il/he/your_health/family/mental_health/Pages/clalit_mental_health_clinics.aspx',
        ),
    ),
    'מאוחדת': dict(
        id='srm0013',
        data=dict(
            name='קופת חולים מאוחדת - מרפאות בריאות נפש',
            short_name='מאוחדת',
            phone_numbers= '*3833',
            urls='https://www.meuhedet.co.il/%D7%9E%D7%90%D7%95%D7%97%D7%93%D7%AA-%D7%9C%D7%A0%D7%A4%D7%A9/'
        ),
    ),
    'default': dict(
        id='srm0019',
        data=dict(
            name='מרפאות בריאות נפש',
            short_name='משרד הבריאות',
            phone_numbers= '*5400',
            urls='https://www.health.gov.il/Subjects/mental_health/treatment/clinics/Pages/default.aspx',
        ),
    ),
}
DATA_SOURCE_ID = 'mental-health-clinics'
DATA_SOURCE_TEXT = 'המידע התקבל ממשרד הבריאות'
splitter = re.compile('[.,\n]')
phone_number = re.compile('[0-9-]{7,}')

def description(row):
    fields = [
        ('interventions', 'סוגי התערבויות', 2),
        ('expertise', 'מומחיות המרפאה', 2),
        ('intake_wait', 'המתנה ממוצעת לאינטק (שבועות)', 0),
    ]
    ret = ''
    for f, title, min_len in fields:
        values = row[f]
        snippet = []
        for value in values:
            if value:
                value = splitter.split(value)
                value = [v.upper() for v in value if len(v) > min_len]
                snippet.extend(value)
        if len(snippet) > 0:
            ret += title + ': ' + ', '.join(set(snippet)) + '\n\n'
    return ret

def clinic_hash(row):
    items = [
        row['name'],
        row['phone_numbers'],
        row['address'],
        row['hmo']
    ]
    items = '|'.join(filter(None, items))
    return 'mhclinic-' + hashlib.sha1(items.encode('utf-8')).hexdigest()[:8]

def operator(*_):
    # Prepare data
    def ren(k, v):
        return DF.add_field(k, 'string', default=lambda row: row['Data'].pop(v, None))
    def del_data(row):
        for k in ['follow_up_wait', 'group_therapy_wait', 'individual_therapy_wait', ]:
            row['Data'].pop(k, None)
    DF.Flow(
        # Load and clean
        collect_gov_rows('70c0b6fd-0c36-4b7a-a087-3157123403d9'),
        DF.update_resource(-1, name='clinics'),
        *[ren(k, v) for k, v in FIELD_RENAME.items()],
        del_data,
        DF.set_type('hmo', transform=HMOS.get),
        DF.select_fields(FIELD_RENAME.keys(), resources=-1),
        DF.update_schema(-1, missingValues=MISSING_VALUES),
        DF.validate(on_error=DF.schema_validator.clear),

        # Filter out stuff
        DF.filter_rows(lambda r: 'קליניקה' not in r['age_group'], resources=-1),
        DF.filter_rows(lambda r: r['street_address'] is not None, resources=-1),

        # Prepare branch data
        DF.set_type('phone_numbers', transform=lambda v: '\n'.join(phone_number.findall(str(v))) if v else None, resources=-1),
        DF.set_type('intake_wait', type='string', transform=lambda v: str(v) if v else None, resources=-1),
        DF.add_field('address', 'string', lambda r: f'{r["street_address"]}, {r["city"]}' if r['city'] not in r['street_address'] else r['street_address'], resources=-1),
        DF.add_field('location', 'string', lambda r: r['address'], resources=-1),
        DF.delete_fields(['street_address', 'city'], resources=-1),

        DF.add_field('id', 'string', clinic_hash, resources=-1),

        DF.dump_to_path('temp/denormalized'),
        DF.printer()
    ).process()

    # Branches
    branches = DF.Flow(
        DF.load('temp/denormalized/datapackage.json'),
        # Join by branch id
        DF.join_with_self('clinics', ['id'], dict(
            id=None, name=None, address=None, location=None, hmo=None,
            phone_numbers=dict(aggregate='set'),
            interventions=dict(aggregate='set'),
            expertise=dict(aggregate='set'),
            intake_wait=dict(aggregate='set'),
        )),
        DF.add_field('description', 'string', description, resources=-1),
        DF.delete_fields(['interventions', 'expertise', 'intake_wait'], resources=-1),

        DF.set_type('phone_numbers', type='string', transform=lambda v: '\n'.join(filter(None, set('\n'.join(v).split('\n')))), resources=-1),

        # Constants
        DF.add_field('organization', 'string', lambda r: ORGS.get(r['hmo'] or 'default')['id'], resources=-1),

        DF.printer()
    ).results()[0][0]
    branches = [dict(id=b.pop('id'), data=b) for b in branches]

    # Services
    services = DF.Flow(
        DF.load('temp/denormalized/datapackage.json'),
        # Join by service name
        DF.set_type('name', transform=lambda _, row: 'מרפאת בריאות נפש ' + row['age_group'], resources=-1),
        DF.join_with_self('clinics', ['name'], dict(
            name=None,
            branches=dict(name='id', aggregate='set'),
            age_group=dict(aggregate='set'),
        )),
        DF.add_field('situations', 'array', lambda r: ['human_situations:disability:mental_illness'] + list(set(x for g in r['age_group'] for x in SITUATIONS[g])), resources=-1),
        DF.delete_fields(['age_group'], resources=-1),

        # Constants
        DF.add_field('responses', 'array', ['human_services:health:mental_health_care'], resources=-1),
        DF.add_field('data_sources', 'string', DATA_SOURCE_TEXT, resources=-1),
        DF.add_field('id', 'string', lambda r: 'mhclinic-' + slugify(r['name']), resources=-1),

        DF.printer()
    ).results()[0][0]
    services = [dict(id=s.pop('id'), data=s) for s in services]

    # Organizations
    airtable_updater(
        settings.AIRTABLE_ORGANIZATION_TABLE,
        DATA_SOURCE_ID,
        ['name', 'short_name', 'phone_numbers', 'urls'],
        ORGS.values(),
        update_mapper(),
        airtable_base=settings.AIRTABLE_ENTITIES_IMPORT_BASE
    )

    airtable_updater(
        settings.AIRTABLE_BRANCH_TABLE,
        DATA_SOURCE_ID,
        ['name', 'address', 'location', 'description', 'phone_numbers', 'organization'],
        branches,
        update_mapper(),
        airtable_base=settings.AIRTABLE_ENTITIES_IMPORT_BASE
    )

    airtable_updater(
        settings.AIRTABLE_SERVICE_TABLE,
        DATA_SOURCE_ID,
        ['name', 'branches', 'situations', 'responses', 'data_sources'],
        services,
        update_mapper(),
        airtable_base=settings.AIRTABLE_ENTITIES_IMPORT_BASE
    )

if __name__ == '__main__':
    operator(None, None, None)


import os
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset

class EqFeaData(Dataset):
    def __init__(self, area, flag): # flag = train or valid
        super(EqFeaData, self).__init__()
        feature_label_data = pd.read_csv(os.path.join('./dataset/processed/AREA_FEATURE', f'area_{area}_{flag}.csv'), index_col=0)

        # data resample to make balance for label_M=0 and label_M!=0
        if flag == 'train':
            long_data = feature_label_data[feature_label_data['label_M']==0]
            short_data = feature_label_data[feature_label_data['label_M']!=0]
            if len(long_data) < len(short_data):
                long_data, short_data = short_data, long_data
            short_data = short_data.sample(len(long_data), replace=True)
            feature_label_data = pd.concat([long_data, short_data]) # len(long_data) == len(short_data)
            feature_label_data = feature_label_data.sample(frac=1).reset_index(drop=True)
            del long_data
            del short_data

        # get feature and label
        self.target_M = feature_label_data['label_M']
        self.target_M = self.discrete_label(self.target_M)  # discrete magnitude as class
        self.target_M = np.array(self.target_M.values) # transfer to numpy format
        self.feature = feature_label_data.drop(['label_M', 'label_long', 'label_lati', 'Day'], axis=1) # delete these column
        self.feature = np.array(self.feature.values)

    def discrete_label(self, label_M):
        for i, ss in enumerate(label_M):
            if(ss < 3.5):
                label_M.iloc[i] = 0
            elif(ss < 4.0):
                label_M.iloc[i] = 1
            elif(ss < 4.5):
                label_M.iloc[i] = 2
            elif(ss < 5.0):
                label_M.iloc[i] = 3
            else:
                label_M.iloc[i] = 4
        return label_M

    def __len__(self):
        return self.feature.shape[0] # [N, D]

    def __getitem__(self, idx):
        feature_row = self.feature[idx]
        label_row = self.target_M[idx]

        return torch.tensor(feature_row, dtype=torch.float64), torch.tensor(label_row, dtype=torch.long)


import openmdao.api as om

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import floris.tools as wfct
import time
from gradient_free import GeneticAlgorithm, GreedyAlgorithm
import scipy

def get_turbine_locs(turbine_exists):

    global xlocs
    global ylocs

    layout_x = np.zeros(int(np.sum(turbine_exists)))
    layout_y = np.zeros(int(np.sum(turbine_exists)))
    ind = 0
    for i in range(len(turbine_exists)):
        if int(turbine_exists[i]) == 1:
            layout_x[ind] = xlocs[i]
            layout_y[ind] = ylocs[i]
            ind += 1

    return layout_x, layout_y

def calc_spacing(layout_x,layout_y):

        nTurbs = len(layout_x)
        npairs = int((nTurbs*(nTurbs-1))/2)
        spacing = np.zeros(npairs)

        ind = 0
        for i in range(nTurbs):
            for j in range(i,nTurbs):
                if i != j:
                    spacing[ind] = np.sqrt((layout_x[i]-layout_x[j])**2+(layout_y[i]-layout_y[j])**2)
                    ind += 1

        return spacing

def profit_obj(x):

    global floris_model
    global function_calls

    global windDirections
    global windSpeeds
    global windFrequencies
    global side
    global minSpacing
    global rotor_diameter
    global ppa
    global BOS_func

    turbine_exists = x[:]

    layout_x, layout_y = get_turbine_locs(turbine_exists)

    if len(layout_x) > 1:
            spacing = calc_spacing(layout_x,layout_y)
            spacing_con = np.min(spacing) - minSpacing*rotor_diameter
    elif len(layout_x) == 1:
        spacing_con = 0.0
    else:
        spacing_con = -1.0

    if len(layout_x) < 1 or np.max(layout_x) > side or np.max(layout_y) > side or np.min(layout_x) < 0.0 or np.min(layout_y) < 0.0 or spacing_con < 0.0:
        return 1E6

    else:
        function_calls += 1
        floris_model.reinitialize_flow_field(layout_array=(layout_x,layout_y))
        AEP = floris_model.get_farm_AEP(windDirections, windSpeeds, windFrequencies, limit_ws=True)
        nturbs = len(layout_x)

        tcc = 2500*829*nturbs
        bos = BOS_func(nturbs)
        om = 44*nturbs*2500.0
        fcr = 0.097
        cost = (tcc+bos)*fcr + om

        profit = AEP/1.0E6*ppa - cost

        return -profit/1E6

## Main
if __name__ == "__main__":

    global floris_model
    global function_calls
    global turbine_exists
    global boundary
    global windDirections
    global windSpeeds
    global windFrequencies
    global side
    global minSpacing
    global rotor_diameter
    global ppa
    global BOS_func

    global xlocs
    global ylocs

    capacity = np.array([2.5,20,50,100,150,200,400,1000])
    cost_per_kw = np.array([950,699,515,420,386,363,304,280])
    BOS_cost = capacity*cost_per_kw*1000.0
    nturbs = capacity/2.5
    BOS_func = scipy.interpolate.interp1d(nturbs, BOS_cost, kind='cubic')

    function_calls = 0

    floris_model = wfct.floris_interface.FlorisInterface("model_discrete.json")
    floris_model.set_gch(False)

    # one direction small farm
    # ndirs = 1
    # windDirections = np.array([300.0])
    # windSpeeds = np.ones(ndirs)*10.0
    # windFrequencies = np.ones(ndirs)
    # windFrequencies = windFrequencies/sum(windFrequencies)
    # side = 800.0
    # edges = np.array([0.0,0.0, 0.0,side, side,side, side,0.0]).reshape(4,2)
    # boundary = mpl.path.Path(edges)
    # ppa = 30.0
    # grid_size = 10

    # wind rose bigger farm
    # ndirs = 16
    # windDirections = np.linspace(0.0,360.-360./ndirs,ndirs)
    # windSpeeds = np.ones(ndirs)*10.0
    # windFrequencies = np.array([2.0,2.0,3.0,4.0,6.0,6.0,10.0,12.0,6.0,4.0,4.0,8.0,21.0,5.0,3.0,1.0])
    # windFrequencies = windFrequencies/sum(windFrequencies)
    # ndirs = 1
    # windDirections = np.array([300.0])
    # windSpeeds = np.ones(ndirs)*10.0
    # windFrequencies = np.ones(ndirs)
    # windFrequencies = windFrequencies/sum(windFrequencies)
    # side = 2000.0
    # edges = np.array([0.0,0.0, 0.0,side, side,side, side,0.0]).reshape(4,2)
    # boundary = mpl.path.Path(edges)
    # ppa = 40.0
    # grid_size = 25

    # wind rose bigger farm 2
    ndirs_interp = 17
    windDirections_interp = np.linspace(0.0,360.,ndirs_interp)
    windFrequencies_interp = np.array([2.0,2.0,3.0,4.0,6.0,6.0,10.0,12.0,6.0,4.0,4.0,8.0,21.0,5.0,3.0,1.0,2.0])
    freq_func = scipy.interpolate.interp1d(windDirections_interp, windFrequencies_interp, kind='cubic')
    ndirs = 72
    windDirections = np.linspace(0.0,360.-360./ndirs,ndirs)
    windSpeeds = np.ones(ndirs)*10.0
    windFrequencies = freq_func(windDirections)
    windFrequencies = windFrequencies/sum(windFrequencies)
    side = 1600.0
    edges = np.array([0.0,0.0, 0.0,side, side,side, side,0.0]).reshape(4,2)
    boundary = mpl.path.Path(edges)
    grid_size = 20
    ppa = 30.0

    # wind rose bigger farm unidirectional
    # ndirs = 1
    # windDirections = np.array([300.0])
    # windSpeeds = np.ones(ndirs)*10.0
    # windFrequencies = np.ones(ndirs)
    # windFrequencies = windFrequencies/sum(windFrequencies)
    # side = 1600.0
    # edges = np.array([0.0,0.0, 0.0,side, side,side, side,0.0]).reshape(4,2)
    # boundary = mpl.path.Path(edges)
    # grid_size = 20
    # ppa = 30.0

    x_grid = np.linspace(0.0,side,grid_size)
    y_grid = np.linspace(0.0,side,grid_size)

    # xlocs, ylocs = np.meshgrid(x_grid,y_grid)
    # xlocs = np.ndarray.flatten(xlocs)
    # ylocs = np.ndarray.flatten(ylocs)
    xlocs = np.zeros(grid_size*grid_size)
    ylocs = np.zeros(grid_size*grid_size)
    for i in range(grid_size):
        for j in range(grid_size):
            if i%2 == 0:
                xlocs[i*grid_size+j] = x_grid[j]
                ylocs[i*grid_size+j] = y_grid[i]
            else:
                xlocs[(i+1)*grid_size-j-1] = x_grid[j]
                ylocs[i*grid_size+j] = y_grid[i]

    # for i in range(len(xlocs)):
    #     plt.text(xlocs[i],ylocs[i],"%s"%i)

    # plt.xlim(-100,side+100)
    # plt.ylim(-100,side+100)
    # plt.show()

    minSpacing = 2.0 #rotor diameters
    rotor_diameter = 117.8

    nruns = 5

    save = True
    plot = True

    PPAS = np.array([25.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0])

    for j in range(len(PPAS)):
        for i in range(nruns):

            ppa = PPAS[j]
            # gradient-free optimization
            start_time = time.time()
            function_calls = 0

            ga = GreedyAlgorithm()
            ga.bits = np.zeros(grid_size*grid_size,dtype=int)
            ga.bounds = np.zeros((grid_size*grid_size,2))
            ga.variable_type = np.array([])
            for i in range(grid_size*grid_size):
                ga.variable_type = np.append(ga.variable_type,"int")
                ga.bounds[i] = (0,1)
            ga.objective_function = profit_obj

            ga.optimize_switch(initialize="limit")

            opt_val = ga.optimized_function_value
            DVopt = ga.optimized_design_variables

            run_time = time.time() - start_time
            print("opt_val: ", opt_val)
            print("time to run: ", run_time)
            print("function calls: ", function_calls)

            xf, yf = get_turbine_locs(DVopt)
            print("number of turbines: ", len(xf))

            if save:
                file = open('final_results3/variable_profit/%s_profit.txt'%(ppa), 'a')
                file.write('%s'%(opt_val) + '\n')
                file.close()

                file = open('final_results3/variable_profit/%s_x.txt'%(ppa), 'a')
                file.write('%s'%(repr(xf)) + '\n')
                file.close()

                file = open('final_results3/variable_profit/%s_y.txt'%(ppa), 'a')
                file.write('%s'%(repr(yf)) + '\n')
                file.close()

                file = open('final_results3/variable_profit/%s_time.txt'%(ppa), 'a')
                file.write('%s'%(run_time) + '\n')
                file.close()

                file = open('final_results3/variable_profit/%s_calls.txt'%(ppa), 'a')
                file.write('%s'%(function_calls) + '\n')
                file.close()

                file = open('final_results3/variable_profit/%s_history.txt'%(ppa), 'a')
                file.write('%s'%(repr(ga.solution_history)) + '\n')
                file.close()


from api.models import Order
from rest_framework.decorators import api_view
from rest_framework.response import Response
from var_dump import var_dump
from yookassa.domain.common import SecurityHelper
from yookassa.domain.notification import (
    WebhookNotificationEventType,
    WebhookNotificationFactory,
)

@api_view(['POST'])
def yookassaWebhookHandler(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        # Если заголовок X-Forwarded-For отсутствует, получаем IP-адрес из REMOTE_ADDR.
        ip = request.META.get('REMOTE_ADDR')

    if not SecurityHelper().is_ip_trusted(ip):
        return Response({'error': 'Недопустимый отправитель'}, status=400)

    try:
        eventData = WebhookNotificationFactory().create(request.data)
        resp = eventData.object
        print('resp', var_dump(resp))
        if eventData.event == WebhookNotificationEventType.PAYMENT_SUCCEEDED and resp.status == 'succeeded':
            if resp.metadata['product'] == 'inAppBalance':
                orderNumber = resp.metadata['orderNumber']
                order = Order.objects.filter(pk=orderNumber).first()
                if order:
                    order.status = 'alreadyPaid'
                    order.save()

        return Response(status=200)
    except Exception as e:
        print(e)
        return Response(status=400)


import sys

#this is a random comment

def funtionCall(pstring):
    #this is another comment to see what can be done
    arr = []
    cd = {')':'(', ']':'[', '}':'{'}
    for i in pstring:
        if i in ['(', '[', '{']:
            arr.append(i)
        elif i in [')', ']', '}']:
            if len(arr) == 0:
                return False
            if arr[-1] != cd[i]:
                return False
            arr = arr[:-1]
    return len(arr) == 0


import nltk
from nltk.corpus import stopwords
import re

nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')

# Stop words
stop_words = stopwords.words('english')

tokenizer = nltk.tokenize.TweetTokenizer(
    preserve_case=False, reduce_len=True, strip_handles=True, match_phone_numbers=False)
# stemmer = nltk.stem.PorterStemmer()
lemmer = nltk.stem.WordNetLemmatizer()

emojis_pattern = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE)

def process_text(text):

    text.encode('unicode-escape')

    # remove stock market tickers like $GE
    text = re.sub(r'\$\w*', '', text)

    # remove old style retweet text "RT"
    text = re.sub(r'^RT[\s]+', '', text)

    # Remove links
    text = re.sub(r'http\S+', '', text)

    # Seperate sentences
    sentences = nltk.tokenize.sent_tokenize(text, language='english')

    sentences.reverse()
    final_sentence = []
    for sentence in sentences:
        # Emojis
        emojis = emojis_pattern.findall(sentence)
        sentence = emojis_pattern.sub('', sentence)

        # Tokenize sentence
        tokenized_sentence = tokenizer.tokenize(sentence)

        # Remove #
        filtered_sentence = [w[1:] if w.startswith('#') else w for w in tokenized_sentence]

        # Remove stop words
        filtered_sentence = [w for w in filtered_sentence if not w in stop_words]

        # Remove numbers
        filtered_sentence = [w for w in filtered_sentence if not re.match(r'^([,.\d]*)([,.]?\d*)$', w)]

        # Remove punctuation
        #filtered_sentence = [w for w in filtered_sentence if not re.match(r'[^\w\s]', w)]

        # Stem words
        final_sentence += [lemmer.lemmatize(token) for token in filtered_sentence]

        final_sentence.extend(emojis)

    return final_sentence


#calc total # months included in dataset
#calc net total amount of profit/losses over entire period
#calc change in profit/losses over entire period
#calc average of changes in profit/losses
#calc greatest increase in profits GPI (date and amt)
#calc greatest decrease in profits GPD (date and amt)

# Modules
import os
import csv

# define variables
month_tot = []
net_PL = 0
delta_PL = []
previous_row = 0
GPI = 0
GPD = 0
average_change = 0
GIM = ""
GDM = ""

# Set path for file
# C:\Users\msfte\Desktop\GT-VIRT-DATA-PT-09-2022-U-LOLC\Homeworks\03-Python\Instructions\PyBank\Resources\budget_data.csv
budget_data = os.path.join("Resources", "budget_data.csv")
output_data = os.path.join("Analysis", "budget_analysis.txt")
# Open and read csv and read header row
with open(budget_data) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    header = next(csv_reader)
    #print(header)
    first_record = next(csv_reader)
    month_tot.append(first_record[0])
    net_PL += int(first_record[1])
    previous_row = int(first_record[1])
    # Read through each row of data after the header
    for row in csv_reader:
        month_tot.append(row[0])
        net_PL += int(row[1])
        change = int(row[1]) - previous_row
        delta_PL.append(change)
        previous_row = int(row[1])
# Greatest Profit Increase and Decrease calculations
    GPI = max(delta_PL)
    GPD = min(delta_PL)

    min_index = delta_PL.index(GPD)
    max_index = delta_PL.index(GPI)
# gives the correct corresponding month with GPI and GPD by adding 1 to the index
    GIM = month_tot[max_index +1]
    GDM = month_tot[min_index +1]
# change, accounting for rounding to the 100th place
    average_change = round(sum(delta_PL)/len(delta_PL), 2)
# correct formatting so the output is understandable to the user
Output = (
f"Financial Analysis\n"
f"  ----------------------------\n"
f"  Total Months: {len(month_tot)}\n"
f"  Total: ${net_PL}\n"
f"  Average Change: ${average_change}\n"
f"  Greatest Increase in Profits: {GIM} (${GPI})\n"
f"  Greatest Decrease in Profits: {GDM} (${GPD})\n")
print(Output)
# write the .txt file for the final output
with open(output_data, "w") as output_file:
    output_file.write(Output)


n = int(input())
sum = 0
list_n = []
for i in range(1, n+1):
    sum += i

    if n % i == 0:
        list_n.append(i)

    if i%2==0:
        continue
    print(i)

print("sum : ", sum)
print("n의 약수 : ", list_n)

섹션 1/반복문_예제.py


# optimized by:
# Reusign the connect_to_db Function: Reused the connect_to_db function instead of a separate connection in list_all_items.
# Refactoring Table Name Determination: Created a separate function to determine the table name based on the item type. This removes redundancy across the functions.
# Refactoring Query Execution: Created a common function to execute queries that can be used across multiple functions.

import mysql.connector
import json
def read_json_file():
    with open('data.json', 'r') as file:
        data = json.load(file)
    return data

def connect_to_db():
    return mysql.connector.connect(user='root', password='', host='localhost', database='PackingWithJSON')

def read_json_file():
    with open('data.json', 'r') as file:
        data = json.load(file)
    return data

def write_json_file(data):
    with open('./PackingWithJSON/data.json', 'w') as file:
        json.dump(data, file)

def get_table_name(item_type):
    tables = {'personal': 'personal_items', 'household': 'household_items', 'work': 'work_essentials'}
    return tables.get(item_type, None)

def execute_query(connection, query, values=None):
    cursor = connection.cursor()
    if values:
        cursor.execute(query, values)
    else:
        cursor.execute(query)
    connection.commit()
    cursor.close()

# create_item function
def create_item(item_type, item_name, quantity, colors, importance, complete):
    table_name = get_table_name(item_type)
    if table_name is None:
        print("Invalid item_type provided. Must be 'personal', 'household', or 'work'.")
        return

    query = f"INSERT INTO {table_name} (type, item_name, quantity, colors, importance, complete) VALUES (%s, %s, %s, %s, %s, %s)"
    values = (item_type, item_name, quantity, colors, importance, complete)

    connection = connect_to_db()
    execute_query(connection, query, values)
    connection.close()

# Remaining functions can use similar refactoring based on the above approach

def read_item(item_type, item_name):
    table_name = get_table_name(item_type)
    if table_name is None:
        print("Invalid item_type provided. Must be 'personal', 'household', or 'work'.")
        return None, None

    query = f"SELECT * FROM {table_name} WHERE item_name = %s"
    values = (item_name,)

    connection = connect_to_db()
    cursor = connection.cursor()
    cursor.execute(query, values)
    result = cursor.fetchall()

    json_result = []
    for row in result:
        json_result.append({
            'id': row[0],
            'type': row[1],
            'item_name': row[2],
            'quantity': row[3],
            'colors': row[4],
            'importance': row[5],
            'complete': row[6]
        })

    cursor.close()
    connection.close()

    return result, json_result

def update_data(item_type, item_name, quantity=None, colors=None, importance=None, complete=None):
    table_name = get_table_name(item_type)
    if table_name is None:
        print("Invalid item_type provided. Must be 'personal', 'household', or 'work'.")
        return

    update_parts = []
    values = []
    if quantity is not None:
        update_parts.append("quantity = %s")
        values.append(quantity)
    if colors is not None:
        update_parts.append("colors = %s")
        values.append(colors)
    if importance is not None:
        update_parts.append("importance = %s")
        values.append(importance)
    if complete is not None:
        update_parts.append("complete = %s")
        values.append(complete)

    values.append(item_name)
    update_query = f"UPDATE {table_name} SET {', '.join(update_parts)} WHERE item_name = %s"

    connection = connect_to_db()
    execute_query(connection, update_query, tuple(values))
    connection.close()

def delete_item(item_type, item_name):
    table_name = get_table_name(item_type)
    if table_name is None:
        print("Invalid item_type provided. Must be 'personal', 'household', or 'work'.")
        return

    delete_query = f"DELETE FROM {table_name} WHERE item_name = %s"
    values = (item_name,)

    connection = connect_to_db()
    execute_query(connection, delete_query, values)
    connection.close()

def list_all_items():
    connection = connect_to_db()
    cursor = connection.cursor()

    items = {
        'personal_items': [],
        'household_items': [],
        'work_essentials': []
    }

    tables = ['personal_items', 'household_items', 'work_essentials']

    for table in tables:
        cursor.execute(f"SELECT * FROM {table}")
        result = cursor.fetchall()

        # Processing code here
        for row in result:
            item = {
                'item_type': row[1],  # Assuming item_type is in the second column
                'item_name': row[2],  # Assuming item_name is in the third column
                'quantity': row[3],   # Assuming quantity is in the fourth column
                'colors': row[4],     # Assuming colors is in the fifth column
                'importance': row[5],  # Assuming importance is in the sixth column
                'complete': row[6]    # Assuming complete is in the seventh column
            }
            items[table].append(item)

    cursor.close()
    connection.close()

    return items


import pymysql
import requests

def get_sql():
    #  打开数据库，参数分别名数据库服务器，用户名，密码和数据库名称
    db = pymysql.connect('192.168.10.16', 'root', 'etlx29_st4x6su', 'siteportal_vip')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # SQL 查询语句
    sql = 'select period,numbers from l_xjssc_winning_number limit 1'
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录（元组类型）
        res = cursor.fetchall()
        for row in res:
            period = row[0]
            numbers = row[1]
            # 打印结果
            # print('period:', period, 'numbers:', numbers)
            print("预期结果:", numbers)
    except:
        print("Error: unable to fetch data")
    # 关闭数据库连接
    db.close()
    return numbers

def get_interface():
    # 请求接口
    url = requests.get('https://mo.1394x.com/xjssc/GetAwardData?version=3000')
    url_json = url.json()
    act_number = url_json['items']['current']['result']
    print('接口返回的数据:', url_json)
    print("实际结果：", act_number)
    # 调用get_sql函数，并返回结果山给numbers字段
    numbers = get_sql()
    if numbers == act_number:
        print('实际结果与预期结果一致，测试通过!!')
    else:
        print('实际结果与预期结果不一致，测试不通过!!!')

if __name__ == '__main__':
    get_interface()


#!/usr/bin/env python3
import pandas as pd
import numpy as np
import os
import random
import string
import subprocess

from config import IP_PREFIX, NETWORK_NAME, DEBUG_MODE

df = pd.read_csv('users.csv')
for index, row in df.iterrows():
    username = row['username']
    start, end = (index + 1) * 1000 + 1, (index + 1) * 1000 + 999

    docker_ip = f"{IP_PREFIX}.{2 + index}"
    print(docker_ip)

    networking_commands = [
        f"DOCKER -t nat -p tcp -m tcp ! -i {NETWORK_NAME} --dport {start}:{end} -j DNAT --to-destination {docker_ip}:{start}-{end}",
        f"DOCKER -p tcp -m tcp -d {docker_ip}/32 ! -i {NETWORK_NAME} -o {NETWORK_NAME} --dport {start}:{end} -j ACCEPT",
        f"POSTROUTING -t nat -p tcp -m tcp -s {docker_ip}/32 -d {docker_ip}/32 --dport {start}:{end} -j MASQUERADE"
    ]

    for command in networking_commands:
        if DEBUG_MODE:
            print(command)
        else:
            process = subprocess.Popen("sudo iptables -C" + command, shell=True, stdout=subprocess.PIPE)
            process.wait()

            if process.returncode:  # Check if this entry is not yet created
                os.system("sudo iptables -A" + command)

df.to_csv('users.csv')


from django.conf.urls import patterns, url
from ratethiscourse import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^register/?$', views.register, name='register'),
    url(r'^login/?$', views.user_login, name='login'),
    url(r'^logout/?$', views.user_logout, name='logout'),
    url(r'^add_degree/?$', views.add_course, name='add course'),
    url(r'^add_course/?$', views.add_module, name='add module'),
    url(r'^user_profile/?$', views.user_profile, name='user profile'),
    url(r'^validate_user/?$', views.validate_user, name='validate user'),
    url(r'^resend_validation_email/?$', views.resend_validation_email, name='resend validation email'),
    url(r'^university/?$', views.universities, name='universities'),
    url(r'^university/(?P<uni_name_url>\w+)/?$', views.university, name='university'),
    url(r'^university/(?P<uni_name_url>\w+)/(?P<course_name_url>\w+)/?$', views.course, name='course'),
    url(r'^university/(?P<uni_name_url>\w+)/(?P<course_name_url>\w+)/(?P<module_name_url>\w+)/?$', views.module, name='module'),
    url(r'^get_courses/?$', views.get_courses, name='get courses'),
    url(r'^get_user_uni/?$', views.get_user_uni, name='get user uni'),
    url(r'^get_user_course/?$', views.get_user_course, name='get user course'),
    url(r'^ajax_login/?$', views.ajax_login, name='ajax login'),
    url(r'^ajax_logout/?$', views.ajax_logout, name='ajax logout'),
    )


import setup_environment
import pandas as pd

import numpy as np
from sklearn.metrics import precision_score, recall_score, precision_recall_curve, \
    confusion_matrix, roc_auc_score
from evaluation_functions import precision_at_k, recall_at_k, binarize_at_k

import matplotlib.pyplot as plt
plt.switch_backend('agg')

import seaborn as sns
sns.set_style('darkgrid')

from write_to_db import write_labels, write_to_result_stats, write_to_feature_importances

def test_evaluation():
    """
    Testing evaluation pipeline. Uses some test data
    """
    def demo_data():
        DEMO_QUERY = """
        select cast(street_id as varchar)||'_'||cast(year_curr as varchar) block_year, wo_next1 y_true, random() y_pred_proba
        from features.combined
        where year_curr != 2015
        limit 1000
        """
        from setup_environment import db_dict
        with setup_environment.connect_to_syracuse_db(**db_dict) as conn:
            data = pd.read_sql_query(
                DEMO_QUERY, conn, index_col=['block_year'])
        data.columns = ['y_true', 'y_pred_proba']
        return data

    TEST_OUTPUT = {
        'timestamp': '000000',
        'debug': True,
        'results_dir': './results/figures/',
        'full_results': True,
        'visualize': True,
        'use_imputed': True,
        'model_name': 'Test',
        'y_validate': demo_data(),
        'y_train': demo_data(),
        'break_window': 'wo_next1',
        'features': ['diameters', 'pipe_age', 'musym_Ub'],
        'cross_val': 'seventy_thirty',
        'rebalancing': 'none',
        'parameters': {'C': 0.01, 'penalty': 'l1'},
        'date_dic': {'train': [2004, 2005, 2006],
                     'valid': [2007, 2008],
                     'test':  2014},
        'feature_import': {'wo_curr': 0.07,
                           'diameters': 0.25},
        'static_features': ['diameters', 'pipe_age'],
        'past_yr': 2
    }

    full_evaluation(TEST_OUTPUT)

def plot_score_distribution(y_pred, so):
    """ Plots scores of predicted values """
    min_x = min(min(y_pred), 0)
    max_x = max(max(y_pred), 1)
    sns.distplot(y_pred, kde=False)
    plt.title("distribution of scores for {} model".format(so['model_name']))
    plt.xlabel("raw prediction score")
    plt.xlim([min_x, max_x])
    plt.ylabel("number of street segments")
    base = so['results_dir'] + so['model_name'] + "_" + \
        str(so['timestamp']) + "_" + so['break_window']
    plt.savefig(base + '_score_distribution.png', bbox_inches='tight')
    plt.close()

def plot_precision_recall_n(y_true, y_prob, so):
    # from Rayid's magicloops code
    y_score = y_prob
    precision_curve, recall_curve, pr_thresholds = precision_recall_curve(
        y_true, y_prob)
    precision_curve = precision_curve[:-1]
    recall_curve = recall_curve[:-1]
    pct_above_per_thresh = []
    number_scored = len(y_prob)
    for value in pr_thresholds:
        num_above_thresh = len(y_score[y_prob >= value])
        pct_above_thresh = num_above_thresh / float(number_scored)
        pct_above_per_thresh.append(pct_above_thresh)
    pct_above_per_thresh = np.array(pct_above_per_thresh)
    plt.clf()
    fig, ax1 = plt.subplots()
    ax1.plot(pct_above_per_thresh, precision_curve, 'b')
    ax1.set_xlabel('percent of population')
    ax1.set(ylim=(0, 1))

    ax1.set_ylabel('precision', color='b')
    ax2 = ax1.twinx()
    ax1.plot(pct_above_per_thresh, recall_curve, 'r')
    ax2.set_ylabel('recall', color='r')

    base = so['results_dir'] + so['model_name'] + "_" + \
        str(so['timestamp']) + "_" + so['break_window']
    plt.savefig(base + '_precision_recall_n.png', bbox_inches='tight')
    plt.close()

def calc_confusion_matrix(y_true, y_prob, k):
    """ Calculates confusion matrix given some set of y_true, predicted values y_prob, and a threshold """
    cm = confusion_matrix(y_true, binarize_at_k(y_prob, k))
    return cm

def show_confusion_matrix(C, so, class_labels=['0', '1']):
    """
    C: ndarray, shape (2,2) as given by scikit-learn confusion_matrix function
    class_labels: list of strings, default simply labels 0 and 1.

    Draws confusion matrix with associated metrics.
    """
    import matplotlib.pyplot as plt
    import numpy as np

    assert C.shape == (
        2, 2), "Confusion matrix should be from binary classification only."

    # true negative, false positive, etc...
    tn = C[0, 0]
    fp = C[0, 1]
    fn = C[1, 0]
    tp = C[1, 1]

    NP = fn + tp  # Num positive examples
    NN = tn + fp  # Num negative examples
    N = NP + NN

    fig = plt.figure(figsize=(8, 8))

    ax = fig.add_subplot(111)
    ax.imshow(C, interpolation='nearest', cmap=plt.cm.Blues)

    # Draw the grid boxes
    ax.set_xlim(-0.5, 2.5)
    ax.set_ylim(2.5, -0.5)
    ax.plot([-0.5, 2.5], [0.5, 0.5], '-k', lw=2)
    ax.plot([-0.5, 2.5], [1.5, 1.5], '-k', lw=2)
    ax.plot([0.5, 0.5], [-0.5, 2.5], '-k', lw=2)
    ax.plot([1.5, 1.5], [-0.5, 2.5], '-k', lw=2)

    # Set xlabels
    ax.set_xlabel('Predicted Label', fontsize=16)
    ax.set_xticks([0, 1, 2])
    ax.set_xticklabels(class_labels + [''])
    ax.xaxis.set_label_position('top')
    ax.xaxis.tick_top()
    # These coordinate might require some tinkering. Ditto for y, below.
    ax.xaxis.set_label_coords(0.34, 1.06)

    # Set ylabels
    ax.set_ylabel('True Label', fontsize=16, rotation=90)
    ax.set_yticklabels(class_labels + [''], rotation=90)
    ax.set_yticks([0, 1, 2])
    ax.yaxis.set_label_coords(-0.09, 0.65)

    # Fill in initial metrics: tp, tn, etc...
    ax.text(0, 0,
            'True Neg: %d\n(Num Neg: %d)' % (tn, NN),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(0, 1,
            'False Neg: %d' % fn,
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(1, 0,
            'False Pos: %d' % fp,
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(1, 1,
            'True Pos: %d\n(Num Pos: %d)' % (tp, NP),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    # Fill in secondary metrics: accuracy, true pos rate, etc...
    ax.text(2, 0,
            'False Pos Rate: %.2f' % (fp / (fp + tn + 0.)),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(2, 1,
            'True Pos Rate: %.2f' % (tp / (tp + fn + 0.)),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(2, 2,
            'Accuracy: %.2f' % ((tp + tn + 0.) / N),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(0, 2,
            'Neg Pre Val: %.2f' % (1 - fn / (fn + tn + 0.)),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    ax.text(1, 2,
            'Pos Pred Val: %.2f' % (tp / (tp + fp + 0.)),
            va='center',
            ha='center',
            bbox=dict(fc='w', boxstyle='round,pad=1'))

    base = so['results_dir'] + so['model_name'] + "_" + \
        str(so['timestamp']) + "_" + so['break_window']
    plt.savefig(base + '_confusion_matrix.png', bbox_inches='tight')
    plt.close()

def full_evaluation(so):
    """
    Given some set of data from a model run so (saved_output),
    generates figures and stores model predictions and summary stats
    in .png and SQL
    """
    rename_columns = {'wo_next1': 'y_true',
                      'wo_next2': 'y_true', 'wo_next3': 'y_true'}
    y_validate = so['y_validate']
    y_validate.rename(columns=rename_columns, inplace=True)
    y_train = so['y_train']
    y_train.rename(columns=rename_columns, inplace=True)

    if so['full_results'] == True:
        write_to_result_stats(so)
        write_to_feature_importances(so)
        write_labels(so['y_validate'], so['timestamp'], tablename='valid')
        write_labels(so['y_train'], so['timestamp'], tablename='train')
    if so['visualize'] == True:
        plot_score_distribution(y_validate['y_pred_proba'], so)
        plot_precision_recall_n(
            y_validate['y_true'], y_validate['y_pred_proba'], so)
        cm = calc_confusion_matrix(y_validate['y_true'], y_validate[
                                   'y_pred_proba'], 0.05)
        show_confusion_matrix(cm, so)

if __name__ == '__main__':
    test_evaluation()


'''
给定一个数组，它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易（你必须在再次购买前出售掉之前的股票）。

示例 1:
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天（股票价格 = 0）的时候买入，在第 6 天（股票价格 = 3）的时候卖出，这笔交易所能获得利润 = 3-0 = 3 。
     随后，在第 7 天（股票价格 = 1）的时候买入，在第 8 天 （股票价格 = 4）的时候卖出，这笔交易所能获得利润 = 4-1 = 3 。

示例 2:
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天（股票价格 = 1）的时候买入，在第 5 天 （股票价格 = 5）的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     注意你不能在第 1 天和第 2 天接连购买股票，之后再将它们卖出。
     因为这样属于同时参与了多笔交易，你必须在再次购买前出售掉之前的股票。

示例 3:
输入: [7,6,4,3,1]
输出: 0
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。
'''
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0

        len_prices = len(prices)
        buy1, sell1, buy2, sell2 = -prices[0], 0, -prices[0], 0

        for i in range(1, len_prices):
            buy1 = max(buy1, -prices[i])
            sell1 = max(sell1, buy1 + prices[i])
            buy2 = max(buy2, sell1 - prices[i])
            sell2 = max(sell2, buy2 + prices[i])

        return max(0, sell1, sell2)


# Model evaluation script
# As the model is unsupervised, this script tries all possible mappings
# Of segmentation to label and takes the best one.

# Since the model works on patches, we don't need to do any transforms, instead, we just
# need to cut the image into patches and feed all of them through
# Author: Griffin Bishop

from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt

from config import Config
import util
from model import WNet
from evaluation_dataset import EvaluationDataset

def main():
    print("PyTorch Version: ",torch.__version__)
    if torch.cuda.is_available():
        print("Cuda is available. Using GPU")

    config = Config()

    ###################################
    # Image loading and preprocessing #
    ###################################

    evaluation_dataset = EvaluationDataset("test")

    evaluation_dataloader = torch.utils.data.DataLoader(evaluation_dataset,
        batch_size=config.test_batch_size, num_workers=4, shuffle=False)

    ###################################
    #          Model Setup            #
    ###################################

    # We will only use .forward_encoder()
    if torch.cuda.is_available():
        autoencoder = torch.load("./models/model")
    else:
        autoencoder = torch.load("./models/model", map_location=torch.device('cpu'))
    util.enumerate_params([autoencoder])

    ###################################
    #          Testing Loop           #
    ###################################

    autoencoder.eval()

    def combine_patches(image, patches):
        w, h = image[0].shape
        segmentation = torch.zeros(w, h)
        x, y = (0,0) # Start of next patch
        for patch in patches:
            if y+size > h:
                y = 0
                x += size
            segmentation[x:x+size,y:y+size] = patch
            y += size
        return segmentation

    # Because this model is unsupervised, our predicted segment labels do not
    # correspond to the actual segment labels.
    # We need to figure out what the best mapping is.
    # To do this, we will just count, for each of our predicted labels,
    # The number of pixels in each class of actual labels, and take the max in that image
    def count_predicted_pixels(predicted, actual):
        pixel_count = torch.zeros(config.k, config.k)
        for k in range(config.k):
            mask = (predicted == k)
            masked_actual = actual[mask]
            for i in range(config.k):
                pixel_count[k][i] += torch.sum(masked_actual == i)
        return pixel_count

    # Converts the predicted segmentation, based on the pixel counts
    def convert_prediction(pixel_count, predicted):
        map = torch.argmax(pixel_count, dim=1)
        for x in range(predicted.shape[0]):
            for y in range(predicted.shape[1]):
                predicted[x,y] = map[predicted[x,y]]
        return predicted

    def compute_iou(predicted, actual):
        intersection = 0
        union = 0
        for k in range(config.k):
            a = (predicted == k).int()
            b = (actual == k).int()
            #if torch.sum(a) < 100:
            #    continue # Don't count if the channel doesn't cover enough
            intersection += torch.sum(torch.mul(a, b))
            union        += torch.sum(((a + b) > 0).int())
        return intersection.float() / union.float()

    def pixel_accuracy(predicted, actual):
        return torch.mean((predicted == actual).float())

    iou_sum = 0
    pixel_accuracy_sum = 0
    n = 0
    # Currently, we produce the most generous prediction looking at a single image
    for i, [images, segmentations] in enumerate(evaluation_dataloader, 0):
        size = config.input_size
        # Assuming batch size of 1 right now
        image = images[0]
        target_segmentation = segmentations[0]

        # NOTE: We cut the images down to a multiple of the patch size
        cut_w = (image[0].shape[0] // size) * size
        cut_h = (image[0].shape[1] // size) * size
        image = image[:,0:cut_w,0:cut_h]
        target_segmentation = target_segmentation[:,0:cut_w,0:cut_h]

        # NOTE: problem - the above won't get all patches, only ones that fit. (Resolved by above cutting code)
        patches = image.unfold(0, 3, 3).unfold(1, size, size).unfold(2, size, size)
        patch_batch = patches.reshape(-1, 3, size, size)

        if torch.cuda.is_available():
            patch_batch = patch_batch.cuda()
        seg_batch = autoencoder.forward_encoder(patch_batch)
        seg_batch = torch.argmax(seg_batch, axis=1).float()

        predicted_segmentation = combine_patches(image, seg_batch)

        prediction = predicted_segmentation.int()
        actual     = target_segmentation[0].int()

        pixel_count = count_predicted_pixels(prediction, actual)
        prediction = convert_prediction(pixel_count, prediction)

        iou = compute_iou(prediction, actual)
        iou_sum += iou
        accuracy = pixel_accuracy(prediction, actual)
        pixel_accuracy_sum += accuracy
        n += 1

        if config.verbose_testing:
            print(f"Intersection over union for this image: {iou}")
            print(f"Pixel Accuracy for this image: {accuracy}")

        if config.verbose_testing:
            f, axes = plt.subplots(1, 5, figsize=(8,8))
            axes[0].imshow(predicted_segmentation)
            axes[1].imshow(prediction)
            axes[2].imshow(image.permute(1, 2, 0))
            axes[3].imshow(target_segmentation[0])
            correctness_map = (prediction == target_segmentation)
            axes[4].imshow(correctness_map[0]) # Yellow = Correct, Purple = wrong
            plt.show()

        if n % 2 == 0:
            print(f"{n}")

    print(f"Average performance on n={n} validation images:")
    print(f"mean IoU: {iou_sum/n}   | mean pixel accuracy: {pixel_accuracy_sum/n}")

if __name__ == "__main__":
    main()


import copy
from decimal import Decimal
from money import Money
from typing import Dict, Mapping, List
from collections import defaultdict
from src.domain.transactions import *
from src.domain.errors import InsufficientAssetError

class Wallet:
    """Wallet keeps track of assets, it is updated by buy/sell/fund/withdraw/exchange/tax/dividend/corporate_action/issuance_fee/stock_split operations"""

    def __init__(self, initial_assets: Mapping[str, Decimal] = {}):
        self._assets = defaultdict(Decimal, initial_assets)

    def fund(self, item: FundingItem) -> None:
        self._assets[item.funding_amount.currency] += item.funding_amount.amount

    def withdraw(self, item: WithdrawalItem) -> None:
        # check transaction possible
        if item.withdrawal_amount.currency not in self._assets:
            raise InsufficientAssetError(f"Tried to withdraw {item.withdrawal_amount}, but no such asset in the wallet")
        if item.withdrawal_amount.amount > self._assets[item.withdrawal_amount.currency]:
            raise InsufficientAssetError(f"Tried to withdraw {item.withdrawal_amount}, but only has {self._assets[item.withdrawal_amount.currency]}")

        # apply transaction
        self._assets[item.withdrawal_amount.currency] -= item.withdrawal_amount.amount

    def exchange(self, item: ExchangeItem) -> None:
        # check transaction possible
        if item.exchange_from.currency not in self._assets:
            raise InsufficientAssetError(f"Tried to exchange {item.exchange_from}, but no such asset in the wallet: {self._assets}")
        if item.exchange_from.amount > self._assets[item.exchange_from.currency]:
            raise InsufficientAssetError(f"Tried to exchange {item.exchange_from}, but only has {self._assets[item.exchange_from.currency]}")

        # apply transaction
        self._assets[item.exchange_from.currency] -= item.exchange_from.amount
        self._assets[item.exchange_to.currency] += item.exchange_to.amount

    # in 2023 it turned out that autoconversion can be a standalone transaction
    def autoconversion(self, item: AutoConversionItem) -> None:
        Wallet._autoconversion(item, self._assets)

    @staticmethod
    def _autoconversion(item: AutoConversionItem, assets: Dict[str, Decimal]) -> None:
        """autoconversion if effectively the same as exchange"""
        # check transaction possible
        if item.conversion_from.currency not in assets:
            raise InsufficientAssetError(f"Tried to autoconvert {item.conversion_from}, but no such asset in the wallet: {assets}, id: {item.transaction_id}")
        if item.conversion_from.amount > assets[item.conversion_from.currency]:
            raise InsufficientAssetError(
                f"Tried to autoconvert {item.conversion_from}, but only has {assets[item.conversion_from.currency]}, id: {item.transaction_id}"
            )

        # apply transaction
        assets[item.conversion_from.currency] -= item.conversion_from.amount
        assets[item.conversion_to.currency] += item.conversion_to.amount

    def dividend(self, item: DividendItem) -> None:
        self._assets[item.received_dividend.currency] += item.received_dividend.amount

        # first receive money, then autoconvert if needed. Eg. happens for Singapor dollars SGD -> USD
        for autoconversion in item.autoconversions:
            Wallet._autoconversion(autoconversion, self._assets)

        # issuance fee is always less than received dividend so no need to check for sufficient money
        if item.paid_issuance_fee is not None:
            self._assets[item.paid_issuance_fee.paid_fee.currency] -= item.paid_issuance_fee.paid_fee.amount

        # tax is always less than received dividend so no need to check for sufficient money
        if item.paid_tax is not None:
            self._assets[item.paid_tax.paid_tax.currency] -= item.paid_tax.paid_tax.amount

    def tax(self, item: TaxItem) -> None:
        # check transaction possible
        if item.paid_tax.currency not in self._assets:
            raise InsufficientAssetError(f"Tried to pay tax {item.paid_tax}, but no such currency in the wallet")
        if item.paid_tax.amount > self._assets[item.paid_tax.currency]:
            raise InsufficientAssetError(f"Tried to pay tax {item.paid_tax}, but only has {self._assets[item.paid_tax.currency]}; item: {item}")

        # apply transaction
        self._assets[item.paid_tax.currency] -= item.paid_tax.amount

    def issuance_fee(self, item: IssuanceFeeItem) -> None:
        # check transaction possible
        if item.paid_fee.currency not in self._assets:
            raise InsufficientAssetError(f"Tried to pay issuance fee {item.paid_fee}, but no such currency in the wallet")
        if item.paid_fee.amount > self._assets[item.paid_fee.currency]:
            raise InsufficientAssetError(f"Tried to pay issuance fee {item.paid_fee}, but only has {self._assets[item.paid_fee.currency]}")

        # apply transaction
        self._assets[item.paid_fee.currency] -= item.paid_fee.amount

    def corporate_action(self, item: CorporateActionItem) -> None:
        # check transaction possible
        if item.from_share.symbol not in self._assets:
            raise InsufficientAssetError(f"Tried to corporate action from {item.from_share}, but no such share in the wallet")
        if item.from_share.amount > self._assets[item.from_share.symbol]:
            raise InsufficientAssetError(f"Tried to corporate action from {item.from_share}, but only has {self._assets[item.from_share.symbol]}")

        # apply transaction
        self._assets[item.from_share.symbol] -= item.from_share.amount
        self._assets[item.to_share.symbol] += item.to_share.amount

    def stock_split(self, item: StockSplitItem) -> None:
        # check transaction possible
        if item.from_share.symbol not in self._assets:
            raise InsufficientAssetError(f"Tried to stock split from {item.from_share}, but no such share in the wallet")
        if item.from_share.amount > self._assets[item.from_share.symbol]:
            raise InsufficientAssetError(f"Tried to stock split from {item.from_share}, but only has {self._assets[item.from_share.symbol]}")

        # apply transaction
        self._assets[item.from_share.symbol] -= item.from_share.amount
        self._assets[item.to_share.symbol] += item.to_share.amount

    def buy(self, item: BuyItem) -> None:
        # check transaction possible
        assets = self.assets_copy

        # 1. first autoconvert money if needed
        for autoconversion in item.autoconversions:
            Wallet._autoconversion(autoconversion, assets)

        # 2. then try paying for asset
        assets[item.paid.currency] -= item.paid.amount
        assets[item.commission.currency] -= item.commission.amount
        if assets[item.paid.currency] < 0 or assets[item.commission.currency] < 0:
            raise InsufficientAssetError(f"Tried to buy {item.__dict__} but insufficient money")

        # apply transaction
        for autoconversion in item.autoconversions:
            Wallet._autoconversion(autoconversion, self._assets)
        self._assets[item.asset_name] += item.amount
        self._assets[item.paid.currency] -= item.paid.amount
        self._assets[item.commission.currency] -= item.commission.amount

    def sell(self, item: SellItem) -> None:
        # check transaction possible

        # 1. First deduct asset and add money
        assets = self.assets_copy
        assets[item.asset_name] -= item.amount
        assets[item.received.currency] += item.received.amount

        # 2. Next do autoconversions, because exante first converts all received money, and then converts back just to pay commission. stupid
        for autoconversion in item.autoconversions:
            Wallet._autoconversion(autoconversion, assets)

        # 3. And then pay commission as we now have money for that
        assets[item.commission.currency] -= item.commission.amount
        if assets[item.asset_name] < 0 or assets[item.commission.currency] < 0:
            raise InsufficientAssetError(f"Tried to sell {item.__dict__} but insufficient money/asset")

        # apply transaction
        self._assets[item.asset_name] -= item.amount
        self._assets[item.received.currency] += item.received.amount
        for autoconversion in item.autoconversions:
            Wallet._autoconversion(autoconversion, self._assets)
        self._assets[item.commission.currency] -= item.commission.amount

    @property
    def assets_copy(self) -> Dict[str, Decimal]:
        return copy.deepcopy(self._assets)


import cvcuda
import pytest as t
import numpy as np
import cvcuda_util as util

RNG = np.random.default_rng(0)

@t.mark.parametrize(
    "input",
    [
        (((1, 460, 640, 1), cvcuda.Type.U8, "NHWC")),
        (((2, 640, 460, 3), cvcuda.Type.U8, "NHWC")),
        (((1, 1920, 1080, 3), cvcuda.Type.U8, "NHWC")),
        (((3, 1000, 1000, 1), cvcuda.Type.U8, "NHWC")),
        (((2, 100, 100, 1), cvcuda.Type.U8, "NHWC")),
        (((2, 460, 640, 1), cvcuda.Type.U8, "NHWC")),
        (((100, 100, 3), cvcuda.Type.U8, "HWC")),
        (((460, 640, 1), cvcuda.Type.U8, "HWC")),
    ],
)
def test_op_histogrameq(input):

    inputTensor = cvcuda.Tensor(*input)

    out = cvcuda.histogrameq(inputTensor, inputTensor.dtype)
    assert out.layout == inputTensor.layout
    assert out.shape == inputTensor.shape
    assert out.dtype == inputTensor.dtype

    out = cvcuda.Tensor(inputTensor.shape, inputTensor.dtype, inputTensor.layout)
    tmp = cvcuda.histogrameq_into(out, inputTensor)

    assert tmp is out
    assert out.layout == inputTensor.layout
    assert out.shape == inputTensor.shape
    assert out.dtype == inputTensor.dtype

    stream = cvcuda.Stream()
    out = cvcuda.histogrameq(src=inputTensor, dtype=inputTensor.dtype, stream=stream)
    assert out.layout == inputTensor.layout
    assert out.shape == inputTensor.shape
    assert out.dtype == inputTensor.dtype

    tmp = cvcuda.histogrameq_into(dst=out, src=inputTensor, stream=stream)
    assert tmp is out
    assert out.layout == inputTensor.layout
    assert out.shape == inputTensor.shape
    assert out.dtype == inputTensor.dtype

@t.mark.parametrize(
    "num_images, format, max_size",
    [
        (
            1,
            cvcuda.Format.RGB8,
            (480, 720),
        ),
        (
            5,
            cvcuda.Format.RGB8,
            (720, 480),
        ),
        (
            4,
            cvcuda.Format.Y8,
            (1920, 1080),
        ),
        (
            2,
            cvcuda.Format.BGR8,
            (1000, 1000),
        ),
        (
            3,
            cvcuda.Format.Y8,
            (100, 100),
        ),
        (
            5,
            cvcuda.Format.Y8,
            (460, 640),
        ),
    ],
)
def test_op_histogrameq_varshape(num_images, format, max_size):

    b_src = util.create_image_batch(num_images, format, max_size=max_size, rng=RNG)

    out = cvcuda.histogrameq(b_src)
    assert out.uniqueformat is not None
    assert out.uniqueformat == b_src.uniqueformat
    assert len(out) == len(b_src)
    assert out.capacity == b_src.capacity
    assert out.uniqueformat == b_src.uniqueformat
    assert out.maxsize <= max_size

    tmp = cvcuda.histogrameq_into(out, b_src)
    assert tmp is out
    assert out.uniqueformat is not None
    assert out.uniqueformat == b_src.uniqueformat
    assert len(out) == len(b_src)
    assert out.capacity == b_src.capacity
    assert out.uniqueformat == b_src.uniqueformat
    assert out.maxsize <= max_size

    stream = cvcuda.Stream()
    out = cvcuda.histogrameq(
        src=b_src,
        stream=stream,
    )
    assert out.uniqueformat is not None
    assert out.uniqueformat == b_src.uniqueformat
    assert len(out) == len(b_src)
    assert out.capacity == b_src.capacity
    assert out.uniqueformat == b_src.uniqueformat
    assert out.maxsize <= max_size

    tmp = cvcuda.histogrameq_into(
        src=b_src,
        dst=out,
        stream=stream,
    )
    assert tmp is out
    assert out.uniqueformat is not None
    assert out.uniqueformat == b_src.uniqueformat
    assert len(out) == len(b_src)
    assert out.capacity == b_src.capacity
    assert out.uniqueformat == b_src.uniqueformat
    assert out.maxsize <= max_size


import os
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from MyDataset import MyDataset
from cnn import CNN
from tools import accuracy, get_variable

batch_size = 16
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

def test():
    test_dataset = MyDataset('test', transforms.ToTensor(), transforms.ToTensor())
    test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size)

    net = CNN()
    if torch.cuda.is_available():
        net = net.cuda()
    net.load_state_dict(torch.load('cnn.pkl'))
    val_accuracy = []
    net.eval()
    for (data, target) in test_loader:
        output = net(get_variable(data))
        accuracies = accuracy(output, get_variable(target))
        val_accuracy.append(accuracies)

    val_r = (sum([tup[0] for tup in val_accuracy]), sum([tup[1] for tup in val_accuracy]))
    print('测试集准确率: {:.2f}%'.format(100. * val_r[0] / val_r[1]))


#! /usr/bin/python3
import sys, os
from distutils.core import setup
from glob import glob

from othman import __version__

# to install type:
# python setup.py install --root=/

from distutils.command.build import build
from distutils.command.clean import clean

class my_build(build):
  def run(self):
    build.run(self)
    # generate data
    from othman.core import othmanCore, searchIndexer

    if not os.path.isfile('othman-data/ix.db'):
      q=othmanCore(False)
      ix=searchIndexer(True)
      for n,(o,i) in enumerate(q.getAyatIter(1, 6236)):
        for w in i.split(): ix.addWord(w,n+1)
      d=os.path.dirname(sys.argv[0])
      ix.save()

class my_clean(clean):
  def run(self):
    clean.run(self)
    try: os.unlink('othman-data/ix.db')
    except OSError: pass

locales=map(lambda i: ('share/'+i,[''+i+'/othman.mo',]),glob('locale/*/LC_MESSAGES'))
data_files=[('share/othman/',glob('othman-data/*'))]
data_files.extend(locales)
setup (name='Othman', version=__version__,
      description='Othman Quran Browser',
      author='Muayyad Saleh Alsadi',
      author_email='alsadi@ojuba.org',
      url='http://othman.ojuba.org/',
      license='Waqf',
      packages=['othman'],
      scripts=['othman-browser'],
      classifiers=[
          'Development Status :: 4 - Beta',
          'Intended Audience :: End Users/Desktop',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          "Programming Language :: Python :: 2",
          "Programming Language :: Python :: 2.7",
          "Programming Language :: Python :: 3",
          "Programming Language :: Python :: 3.5",
          "Programming Language :: Python :: 3.6",
          "Programming Language :: Python :: 3.7",
          ],
      cmdclass={'build': my_build, 'clean': my_clean},
      data_files=data_files
)


"""
項目17: 引数に対してイテレータを使うときは確実さを尊ぶ

Be Defensive When Iterating Over Arguments

- 日本語版書籍の翻訳に関してネガティブな意見がネットで確認したが何となくわかってきた。日本語が分かりづらい…。
- 引数が複数回反復する場合は気をつける。引数がイテレータの場合は想定外の事が起きる
- __iter__ メソッドをジェネレータとして実装する事で、自分のイテラブルなコンテナ型を作る事ができる
- 引数がイテレータであることは iterに二度入れて比較するつことでわかる。
"""

def normalize_defensive(numbers):
    """
    数値リスト numbers の総計と其々の値のパーセンテージをリストにして返す

    >>> numbers = [15, 35, 80]
    >>> normalize_defensive(numbers)
    [11.538461538461538, 26.923076923076923, 61.53846153846154]
    """
    if iter(numbers) is iter(numbers):
        raise TypeError('Must supply a container')

    total = sum(numbers)
    result = []

    for value in numbers:
        percent = 100 * value / total
        result.append(percent)

    return result

class ReadVisits(object):
    """
    ファイルを読み込み、各行を数値にした上で返す。
    イテレータで呼ばれる事を想定しており、行単位でyieldで返す
    """

    def __init__(self, data_path):
        """ コンストラクタ
        """
        self.data_path = data_path

    def __iter__(self):
        """ イテレータマジックメソッド
        """
        with open(self.data_path) as fp:
            for line in fp:
                yield int(line)

if __name__ == "__main__":
    visits = ReadVisits('sec17_test.txt')
    percentages = normalize_defensive(visits)
    print(percentages)


import json
from inventory_report.importer.importer import Importer

class JsonImporter(Importer):
    @staticmethod
    def import_data(json_file_path):
        file_extension = str(json_file_path).split(".")[-1]
        if file_extension != 'json':
            raise ValueError("Arquivo inválido")
        try:
            with open(json_file_path) as json_file:
                inventory = json.load(json_file)
                return inventory
        except (IsADirectoryError, FileNotFoundError) as err:
            print(err)
            print("Wrong path name")
            return None


import spacy
from spacytextblob.spacytextblob import SpacyTextBlob
import streamlit as st

nlp = spacy.load('en_core_web_sm')
spacy_text_blob = SpacyTextBlob()
nlp.add_pipe(spacy_text_blob)
text = 'Today is an amazing day!'

st.title('Sentiment app')
user_input = st.text_input("Text", text)
doc = nlp(user_input)

st.write('Polarity:', round(doc._.sentiment.polarity, 2))
st.write('Subjectivity:', round(doc._.sentiment.subjectivity, 2))


#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseForbidden
from django.core.urlresolvers import reverse
from videoclient.views import render_to_response_ex, tester
from utils import getDefaultParams, REVISION, VERSION, check_rule
from django.utils import simplejson
from videoclient.configuration.kpp import forms
from django.shortcuts import get_object_or_404
from videoclient import models
import logging
import sys

def get_cameras(kpp):
    cameras = models.Camera.objects.filter(kpp=kpp)
    setattr(kpp, "cameras", cameras)
    return kpp

@tester
def view_kpp(request):
    data = dict()
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    data = dict()
    kpp_list = models.Kpp.objects.all().order_by("-id")
    data["kpp_list"] = kpp_list
    data["kpp_list_count"] = models.Kpp.objects.all().count()
    data.update(getDefaultParams(request, 'settings'))
    data.update({'select_subpage': 'kpp_list'})
    return render_to_response_ex(request, "kpp_lists.html", data)

@tester
def new(request, id=None):
    data = dict()

    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    data.update(getDefaultParams(request, 'settings'))
    data.update({'select_subpage': 'kpp_list'})
    status = False
    if id:
        kpp = models.Kpp.objects.filter(id=int(id))
        if kpp:
            data["kpp"] = kpp[0]
    return render_to_response_ex(request, "kpp_form.html", data)

@tester
def update(request, id=None):
    data = dict()
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    data = dict()
    error = ""
    status = False
    form = forms.CheckKpp(request.POST)
    if form.is_valid():
        name = form.cleaned_data["name"]
        location = form.cleaned_data.get("location", "")
        if id:
            kpp = models.Kpp.objects.filter(id=int(id))
            if kpp:
                kpp.update(name=name, location=location)
            else:
                models.Kpp.objects.create(name=name, location=location)
        else:
            models.Kpp.objects.create(name=name, location=location)

    else:
        error = form.errors
        data["error"] = error
        return render_to_response_ex(request, "kpp_form.html", data)

    return HttpResponseRedirect(reverse("kpp_list", args=[]))

@tester
def change_camera_cpp(request):
    data = dict()
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    data = dict()
    error = ""
    status = False
    formid = forms.ChangeCameraKpp(request.POST)
    if formid.is_valid():
        camera_id = formid.cleaned_data["camera_id"]
        kpp_id = formid.cleaned_data["kpp_id"]
        kpp = models.Kpp.objects.filter(id=int(kpp_id))
        camera = models.Camera.objects.filter(id=int(camera_id))
        if camera and kpp:
            camera.update(kpp=kpp[0])
            status = "success"
    else:
        error = formid.errors

    data["error"] = error
    data["result"] = status
    return HttpResponse(simplejson.dumps(data), mimetype='application/json')


# requirement
# tensorflow
# cuda 10.1
# keras
# pandas
# matplotlib
# scikitlearn

# Mengimport  librari
import numpy as np #numpy untuk komputasi
import matplotlib.pyplot as plt #matplotlib untuk visualisasi
import pandas as pd #pandas untuk manipulasi dataset
# Mengimport data untuk dijadikan training set
dataset_train = pd.read_csv('dataset-training.csv')
training_set = dataset_train.iloc[:, 1:2].values #menggunakan kolom open & high
dataset_train.head()
# melakukan scalling data diantara 0 hingga 1
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)
# membuat 3D array dengan x_train, 60 timestep, satu fitur
X_train = []
y_train = []
for i in range(60, 2035):
    X_train.append(training_set_scaled[i-60:i, 0])
    y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
# Reshaping
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

# Part 2 - Building the RNN
# Imporr keras
from keras.models import Sequential # menggunakan model neural network berupa sequential network
from keras.layers import Dense # menjalankan full connection nn kita
from keras.layers import LSTM # menambahkan layer lstm
from keras.layers import Dropout #mencegah overfitting
# Initialising the RNN
regressor = Sequential()
# menambah layer lstm dengan 50 hidden unit dengan mengembalikan hidden output pada input time step, input shape sebagai training dataset kita
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2)) #melakukan drop pada data input sebanyak 20%
# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units = 1)) #sigmoid
# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') #menggunakan optimasi adam
# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)

# Part 3 - Making the predictions and visualising the results
# import data real untuk digunakan prediksi
dataset_test = pd.read_csv('dataset-test.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values
# membuat prediksi
dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 76):
    X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)
# menampilkan hasil menggunakan matplotlib
plt.plot(real_stock_price, color = 'green', label = 'Real Harga Saham')
plt.plot(predicted_stock_price, color = 'red', label = 'Predicted Harga Saham')
plt.title('Prediksi Harga Saham')
plt.xlabel('Time')
plt.ylabel('Harga Saham')
plt.legend()
plt.show()


import pickle
from flask import Flask,request
import flasgger
from flasgger import Swagger

app = Flask(__name__)
Swagger(app)
pickle_inp = open("classifier.pkl","rb")
classifier = pickle.load(pickle_inp)

@app.route("/")
def welcome():
    return "Welcome to my first flask- flasgger app"

@app.route("/predict",methods=["GET"])
def predict_note():
    """Let's Authenticate the Banks Note
        This is using docstrings for specifications.
        ---
        parameters:
          - name: variance
            in: query
            type: number
            required: true
          - name: skewness
            in: query
            type: number
            required: true
          - name: curtosis
            in: query
            type: number
            required: true
          - name: entropy
            in: query
            type: number
            required: true
        responses:
            200:
                description: The output values

        """
    variance = request.args.get('variance')
    skewness = request.args.get('skewness')
    curtosis = request.args.get('curtosis')
    entropy = request.args.get('entropy')
    prediction = classifier.predict([[variance,skewness,curtosis,entropy]])
    if str(prediction) == '[0]':
        return "Forged bank note"
    else:
        return "Genuine bank note"
    #return "The predicted value is" +str(prediction)

if __name__=='__main__':
    app.run(host='0.0.0.0')


# Given the root of a binary tree, return the number of uni-value subtrees.

# A uni-value subtree means all nodes of the subtree have the same value.

# https://leetcode.com/problems/count-univalue-subtrees/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
        self.ans = 0
        def solve(root):
            if(not root):
                return None
            left = solve(root.left)
            right = solve(root.right)
            if(not left and not right):
                self.ans +=1
                return root
            elif(not left):
                if(right.val == root.val):
                    self.ans += 1
                    return root
                else:
                    root.val = sys.maxsize
                    return root
            elif(not right):
                if(left.val == root.val):
                    self.ans += 1
                    return root
                else:
                    root.val = sys.maxsize
                    return root
            elif(left.val == right.val == root.val):
                self.ans += 1
                return root
            else:
                root.val = sys.maxsize
                return root
        solve(root)
        return self.ans


class Solution:
    def numberToWords(self, num: int) -> str:
        word_below_20 = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
                         "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        word_multiple_of_10 = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        word_multiple_of_1000 = ["Thousand", "Million", "Billion"]
        if num == 0:
            return "Zero"
        res = ""
        thousands = 0
        while num > 0:
            num1, num2 = num % 1000, num % 100
            hundreds, tens, ones = num1 // 100, num2 // 10, num2 % 10
            if thousands > 0 and num1 > 0:
                res = word_multiple_of_1000[thousands - 1] + " " + res
            if 0 < num2 < 20:
                res = word_below_20[num2 - 1] + " " + res
            elif num2 >= 20:
                res = word_multiple_of_10[tens - 2] + " " + (word_below_20[ones - 1] + " " if ones > 0 else "") + res
            if hundreds > 0:
                res = word_below_20[hundreds - 1] + " Hundred " + res
            num //= 1000
            thousands += 1
        res = res[0:-1]
        return res


from tkinter import *
from tkinter import ttk
import pandas as pd
import numpy as np
from sympy import symbols, Eq, solve
from sympy.vector import CoordSys3D
import numpy as np
import pandas as pd
import tabla_carga_equivalente
from Esfuerzos_medios import X_Y
import obtener_data
diametros = []

class Grafica(Frame):

    def __init__(self, master, *args):
        super().__init__(master,*args)
        # Creaación del frame principal
        self.Principalframe = Frame(self.master,  bg='#5484c7', bd=2)
        self.Principalframe.config(bg="white", width=800, height=530)
        self.Principalframe.pack()
        #Llamar las configuraciones del Principalframe
        self.widgets()
        self.Label_Entradas()
        self.Label_Salidas()

    def widgets(self):
        #Tres Frame, para el llenado de los datos
        self.Decframe = Frame(self.Principalframe)
        self.Izqframe = Frame(self.Principalframe)
        self.bajoframe = Frame(self.Principalframe)
        self.config_frame()

    def config_frame(self):
        #configuración de los tres frames
        self.bajoframe.config(bg="#e03e53", width=800, height=100)
        self.bajoframe.pack(side="bottom")
        self.Decframe.config(bg="#37d4cc", width=400, height=430)
        self.Decframe.pack(side="left")
        self.Izqframe.config(bg="#00a5b5", width=400, height=430)
        self.Izqframe.pack(side="right")
        self.Title_entrada = Label(self.Decframe, text =  'Ingrese los valores').place(x = 58, y = 20 , width=284, height=25)
        self.Title_salida  = Label(self.Izqframe, text = 'Respuestas obtenidas').place(x = 50, y = 50 , width=300, height=25)

    def Label_Entradas(self):
        #Label para los datos a pedir
        self.Hp = Label(self.Decframe, text =   'Potencia [Hp]').place(x = 60, y = 70 , width=100, height=25)
        self.n  = Label(self.Decframe, text = 'Velocidad [rpm]').place(x = 60, y = 120, width=100, height=25)
        self.L5 = Label(self.Decframe, text       = 'L5 [pies]').place(x = 60, y = 170, width=100, height=25)
        self.L6 = Label(self.Decframe, text       = 'L6 [pies]').place(x = 60, y = 220, width=100, height=25)
        self.L7 = Label(self.Decframe, text       = 'L7 [pies]').place(x = 60, y = 270, width=100, height=25)
        self.L10= Label(self.Decframe, text       =      'L10h').place(x = 60, y = 320, width=100, height=25)
        self.Entradas()

    def Entradas(self):
        # bloques, para introducir los valores pedidos
        self.Hp_e = Entry(self.Decframe)
        self.n_e  = Entry(self.Decframe)
        self.L5_e = Entry(self.Decframe)
        self.L6_e = Entry(self.Decframe)
        self.L7_e = Entry(self.Decframe)
        self.L10_e= Entry(self.Decframe)
        #configuración de la ubicación de los frame
        self.Hp_e.place(x = 190, y = 70 , width=150, height=25)
        self.n_e.place (x = 190, y = 120, width=150, height=25)
        self.L5_e.place(x = 190, y = 170, width=150, height=25)
        self.L6_e.place(x = 190, y = 220, width=150, height=25)
        self.L7_e.place(x = 190, y = 270, width=150, height=25)
        self.L10_e.place(x =190, y = 320, width=150, height=25)
        self.boton()

    # Botones que se utilizarán en la interfaz
    def boton(self):
        self.calcular = Button(self.Decframe, text = 'Calcular', font=('Arial',12), command = self.calculos).place(x = 150, y = 365, width=100, height=25)
        self.table_compat = Button(self.bajoframe, text = 'Cuadro de comparación', font=('Arial',12), command = self.new_table_comp).place(x = 130, y = 37, width=200, height=26)
        self.table_compat2 = Button(self.bajoframe, text = 'Cuadro de comparación2', font=('Arial',12), command = self.new_table_comp2).place(x =466, y = 37, width=200, height=26)

    #Label_de_los_valores_que_se_nos_dara
    def Label_Salidas(self):
        self.Axial_E = Label(self.Izqframe, text =  'Reacción Axial en E [lbf]').place(x = 47, y = 110, width=140, height=25)
        self.Radia_E = Label(self.Izqframe, text = 'Reacción Radial en E [lbf]').place(x = 47, y = 170, width=140, height=25)
        self.Axial_F = Label(self.Izqframe, text =  'Reacción Axial en F [lbf]').place(x = 47, y = 230, width=140, height=25)
        self.Radia_F = Label(self.Izqframe, text = 'Reacción Radial en F [lbf]').place(x = 47, y = 290, width=140, height=25)
        self.Salidas()

    #Valores de salida, que son calculados
    def Salidas(self):
        self.Axial_E_s = Entry(self.Izqframe)
        self.Radia_E_s = Entry(self.Izqframe)
        self.Axial_F_s = Entry(self.Izqframe)
        self.Radia_F_s = Entry(self.Izqframe)
        self.Axial_E_s.place(x = 205, y = 110, width=150, height=25)
        self.Radia_E_s.place(x = 205, y = 170, width=150, height=25)
        self.Axial_F_s.place(x = 205, y = 230, width=150, height=25)
        self.Radia_F_s.place(x = 205, y = 290, width=150, height=25)

    #Delete para cuando se cambien los valores  se puedan volver a calcular y no se sobre escriba
    def Delete_Entry(self):
        self.Axial_E_s.delete(0, END)
        self.Radia_E_s.delete(0, END)
        self.Axial_F_s.delete(0, END)
        self.Radia_F_s.delete(0, END)

    #Calculo de las Fuerzas que obtuvieron de los valores ingresados
    def calculos(self):
        self.Delete_Entry()
        self.Numero_dientes,self.Angulo_presion, self.Angulo_paso_helice, self.Paso_diametral, self.Ancho_cara = self.leer_datos_excel()
        self.obte_Hp = float(self.Hp_e.get())
        self.obte_n  = float( self.n_e.get())
        self.obte_L5 = float(self.L5_e.get())
        self.obte_L6 = float(self.L6_e.get())
        self.obte_L7 = float(self.L7_e.get())
        self.obte_L10= float(self.L10_e.get())

        N2, N3, N4, N5, N6, N7 = self.Numero_dientes

        #Calcula los diámetros de los engranajes
        for i in range(6):
            diametro = self.diametro_paso(self.Numero_dientes[i],self.Paso_diametral[i])
            diametros.append(diametro)

        #Velocidad angular de los engranajes necesario
        self.w_5 = self.obte_n*(N2/N3)*(N4/N5)
        w_6 = self.w_5

        #Velocidad de línea de los engranajes necesarios
        v_5 = self.velocidad_linea(self.w_5,diametros[3]) #Velocidad angular de 5 usando relación de engranes
        v_6 = self.velocidad_linea(w_6,diametros[4]) #Al estar en el mismo eje
        ##Encontradas las velocidades, procedemos a encontrar las fuerzas.

        #Fuerzas para engrane cónico 5
        ft_5 = self.fuerza_tangencial(self.obte_Hp,v_5)        #Fuerza tangencial del engrane cónico 5
        fr_5 = ft_5*np.tan(np.deg2rad(self.Angulo_presion[3]))*np.cos(np.deg2rad(self.Angulo_paso_helice[3]))    #Fuerza radial del engrane cónico 5 , a partir del angulo de presion y de paso obtenidos de excel
        fa_5 = fr_5*np.tan(np.deg2rad(self.Angulo_presion[3]))*np.sin(np.deg2rad(self.Angulo_paso_helice[3]))    #Fuerza axial del engrane cónico 5 , a partir del angulo de presion y de paso obtenidos de excel

        #Fuerzas para engrane recto 6
        ft_6 = self.fuerza_tangencial(self.obte_Hp,v_6)        #Fuerza tangencial del engrane recto 6
        fr_6 = ft_6*np.tan(np.deg2rad(self.Angulo_presion[4]))

        ## Encontradas las fuerzas de los engranes involucradas, realizaremos análisis estático para encontrar reacciones en los cojinetes.
        # Asignamos nuestros vectores fuerza en los cojinetes
        # E= [Ex,Ey,0]     pues por dato solo tendrá fuerza radial y axial
        # F= [0,Fy,0]      pues por dato solo tendrá fuerza radial

        # Definir las variables desconocidas como simbólicas
        Ey, Fy = symbols('Ey Fy')
        # Definir el sistema de coordenadas
        N = CoordSys3D('N')

        #Inicamos el análisis estático con Sumatoria de fuerzas en X: Ex - fa_5 = 0
        self.Ex = abs(fa_5*0.00444822) #Valor absoluto y se pasa  a KN

        #Sumatoria de fuerzas en Y:
            # Ey + fr_5 - fr_6 + Fy = 0        Ec1 (su mención es solo como guía para proseguir con el desarollo)

        #Sumatoria de momentos en E:
        #  FE x F + f6E x f6 + f5E x f5 = 0        Ec2 (su mención es solo como guía para proseguir con el desarollo)

        #Creamos los vectores de Fuerzas de los engranes en forma vectorial:
        f6 = -fr_6*N.j + ft_6*N.k
        f5 = -fa_5*N.i + fr_5*N.j + ft_5*N.k
        F = Fy*N.j

        #Creamos los vectores de posición desde el cojinete E a cada una de las fuerzas:
        F_E = (self.obte_L5+self.obte_L6)*N.i                             #F_E = (l5+l6)*N.i
        f6_E = -self.obte_L7*N.i + (diametros[4]/2)*N.j                   #f6_E = -l7*N.i + (diametros[4]/2)*N.j
        f5_E = (self.obte_L6-diametros[2])*N.i - diametros[3]*N.j         #f5_E = (l6-diametros[2])*N.i - diametros[3]*N.j

        # Definimos las ecuaciones Ec1 y Ec2 que se mencionaron anteriormente:
        eq1 = Eq(Ey + fr_5 - fr_6 + Fy, 0)
        eq2 = Eq(F_E.dot(N.i) * F.dot(N.j) + f6_E.dot(N.i) * f6.dot(N.j) + f5_E.dot(N.i) * f5.dot(N.k), 0)

        # Resolvemos el sistema de ecuaciones para encontrar Ey , Fy
        sol = solve((eq1, eq2), (Ey, Fy))

        # Obtener las soluciones
        Ey_sol = abs(sol[Ey]*0.00444822)#Valor absoluto y se pasa  a KN
        Fy_sol = abs(sol[Fy]*0.00444822)#Valor absoluto y se pasa  a KN

        self.fE = [self.Ex, Ey_sol]
        self.fF = [0, Fy_sol]

        #Insertar los valores encontrados en se respectivo Entry
        self.Axial_E_s.insert(0, round(self.Ex,2))
        self.Radia_E_s.insert(0, round(Ey_sol,2))
        self.Axial_F_s.insert(0, 0)
        self.Radia_F_s.insert(0, round(Fy_sol,2))

    #Creación de la nueva pestaña  e impresion del cojinete E
    def new_table_comp(self):
        self.new_pest = Toplevel(self.Principalframe)
        self.config_new_pest()
        self.cojineteE()
        self.destro()

    #Armado de la tabla del cojinete E
    def cojineteE(self):
        table2 = ttk.Treeview(self.new_principal)
        # Definir las columnas de la tabla
        table2["columns"] = ("column1", "column2", "column3", "column4", "column5", "column6","column7","column8","column9","column10")

        # Configurar encabezados de columnas
        text = ["C [KN]", "Cor [KN]","Fo","fo.Fa/Cor","e","Fa/Fr","Y","P [KN]","Creq [KN]", "Creq < C"]
        for i in range(len(text)):
            table2.heading(f"column{i+1}", text=text[i])
        lista_final = []
        self.actualizacion(self.fE,lista_final)
        # Agregar filas de datos
        for i in range(69):
            table2.insert('', index='end', text=f"{i+1}", values=(lista_final[i][0], lista_final[i][1], lista_final[i][2], lista_final[i][3],
                           lista_final[i][4], lista_final[i][5], lista_final[i][6], lista_final[i][7],
                           lista_final[i][8], lista_final[i][9]))
        # Ajustar el tamaño de las columnas
        table2.column("#0", width=40)
        for i in range(1, 11):
            table2.column(f"column{i}", width=60)
        # Cambiar el nombre de las filas
        for i, row_id in enumerate(table2.get_children(), start=1):
            table2.item(row_id, text=f"{i}")
        # Mostrar la tabla
        table2.place(width=780, height=180 ,x = 5, y = 5)

    #Configuración de la pestaña para el cojinete E
    def config_new_pest(self):
        self.new_pest.title('Tabla comparativa E')
        self.new_pest.geometry('800x250')
        self.new_pest.config(bg='#515d6e', bd=4)
        self.new_principal = Frame(self.new_pest)
        self.new_principal.config(bg="#f0cf59", width=800, height=250)
        self.new_principal.pack()

    #creación de la pestaña  e impresion del cojitene F
    def new_table_comp2(self):
        self.new_pest2 = Toplevel(self.Principalframe)
        self.config_new_pest2()
        self.cojineteF()
        self.destro2()

    #configuración de la pestaña para el cojitene F
    def config_new_pest2(self):
        self.new_pest2.title('Tabla comparativa F')
        self.new_pest2.geometry('800x250')
        self.new_pest2.config(bg='#515d6e', bd=4)
        self.new_principal2 = Frame(self.new_pest2)
        self.new_principal2.config(bg="#f0cf59", width=800, height=250)
        self.new_principal2.pack()

    #Armado de la tabla del cojinete F
    def cojineteF(self):
        table3 = ttk.Treeview(self.new_principal2)
        # Definir las columnas de la tabla
        table3["columns"] = ("column1", "column2", "column3", "column4", "column5", "column6","column7","column8","column9","column10")

        # Configurar encabezados de columnas
        text3 = ["C [KN]", "Cor [KN]","Fo","fo.Fa/Cor","e","Fa/Fr","Y","P [KN]","Creq [KN]", "Creq < C"]
        for i in range(len(text3)):
            table3.heading(f"column{i+1}", text=text3[i])
        lista_final2 = []
        self.actualizacion(self.fF,lista_final2)
        # Agregar filas de datos
        for i in range(69):
            table3.insert('', index='end', text=f"{i+1}", values=(lista_final2[i][0], lista_final2[i][1], lista_final2[i][2], lista_final2[i][3],
                           lista_final2[i][4], lista_final2[i][5], lista_final2[i][6], lista_final2[i][7],
                           lista_final2[i][8], lista_final2[i][9]))
        # Ajustar el tamaño de las columnas
        table3.column("#0", width=40)
        for i in range(1, 11):
            table3.column(f"column{i}", width=60)
        # Cambiar el nombre de las filas
        for i, row_id in enumerate(table3.get_children(), start=1):
            table3.item(row_id, text=f"{i}")
        # Mostrar la tabla
        table3.place(width=780, height=180 ,x = 5, y = 5)

    #Cerrar la pestaña del cojinete E
    def destro(self):
        boton_cerrar = Button(self.new_principal, text="Cerrar", command=self.new_pest.destroy)
        boton_cerrar.place(x = 350, y = 200, width=150, height=25)

    #Cerrar la pestaña del cojinete E
    def destro2(self):
        boton_cerrar2 = Button(self.new_principal2, text="Cerrar", command=self.new_pest2.destroy)
        boton_cerrar2.place(x = 350, y = 200, width=150, height=25)
        # Agregar contenido y widgets a la nueva ventana
        #etiqueta = Label(, text="¡Esta es una nueva pestaña!")
        #etiqueta.pack()

    def leer_datos_excel(self):
        # Lee el archivo de Excel
        df = pd.read_excel('Datos_engranajes.xlsx')
        # Crea los vectores con los nombres de las filas
        Numero_dientes = df.iloc[0, 1:].tolist()
        Angulo_presion = df.iloc[1, 1:].tolist()
        Angulo_paso_helice = df.iloc[2, 1:].tolist()
        Paso_diametral = df.iloc[3, 1:].tolist()
        Ancho_cara = df.iloc[4, 1:].tolist()

        return Numero_dientes,Angulo_presion, Angulo_paso_helice, Paso_diametral, Ancho_cara

    # Función para calcular la velocidad de salida del sistema de transmisión
    def velocidad_salida(self,velocidad_entrada,N2,N3,N4,N5,N6,N7):
        return velocidad_entrada*(N2/N3)*(N4/N5)*(N6/N7)

    # Función para calcular el diametro de paso a partir del numero de dientes y paso diametral
    def diametro_paso(self,num_dientes, P):
        diametro_paso = num_dientes/P
        return diametro_paso

    # Función para encontrar la velocidad lineal en cada engrane
    def velocidad_linea(self,w,d):
        return (np.pi*d*w)/12

    # Función para encontrar la fuerza tangencial 'Wt' en cada engrane a partir de su potencia y velocidad lineal
    def fuerza_tangencial(self,p,v):
        return (33000*p)/v

    def create_table(self):
        table = ttk.Treeview(self.bajoframe)
        # Definir las columnas de la tabla
        table["columns"] = ("column1", "column2", "column3", "column4", "column5", "column6", "column7", "column8", "column9")

        text1 = ["N° Rodamiento", "C(kN)", "Cor(kN)", "fo", "f0.Fa/Cor", "e", "Fa/Fr", "Y", "P(kN)"]

        for i in range(len(text1)):
            table.heading(f"column{i+1}", text=text1[i])
        # Configurar encabezados de columnas

        # Agregar filas de datos
        for i in range(5):
            table.insert('', index='end', text=f"{i+1}", values=(f"Dato {i+1}", f"Dato {i+2}", f"Dato {i+3}", f"Dato {i+4}",
                                                                f"Dato {i+5}", f"Dato {i+6}", f"Dato {i+7}", f"Dato {i+8}",
                                                                f"Dato {i+9}"))
        # Ajustar el tamaño de las columnas
        table.column("#0", width=40)
        table.column("column1", width=120)
        for i in range(2, 10):
            table.column(f"column{i}", width=77)
        # Cambiar el nombre de las filas
        for i, row_id in enumerate(table.get_children(), start=1):
            table.item(row_id, text=f"{i}")
        # Mostrar la tabla
        table.place(width=780, height=160, x = 5, y = 3)

    #Función con el fin de obtener los valores de evaluación del cojinete
    def actualizacion(self,term,lista_final):
        L10h = self.obte_L10

        for i in range(69):
            Fa = term[0]
            Fr = term[1]
            fila_deseada = i + 1  # Número de fila deseada
            valores_fila = obtener_data.obtener_valores_fila(fila_deseada)
            #print("Valores de la fila:", valores_fila)

            # Valores de tabla
            C = valores_fila[1]
            Cor = valores_fila[2]
            f0 = valores_fila[3]

            def relacion(Fa, Fr):
                return Fa / Fr

            def factor(fo, fa,cor):
                return round((fo*fa)/cor,3)

            def creq(P, n, L10h):
                return P * (((60 * n * L10h) / 10 ** 6) ** (1 / 3))

            def carga_equivalente(fa, fr, x, y):
                return x * fr + y * fa

            tabla = tabla_carga_equivalente.tabla
            valor = factor(f0, Fa, Cor)

            x, y, e = X_Y(tabla, valor, Fa, Fr)
            y = round(y,3)
            e = round(e,3)

            P = round(carga_equivalente(Fa, Fr, x, y),3)

            Rela = round(relacion(Fa, Fr),3)
            Factor = factor(f0, Fa, Cor)
            c_req = round(creq(P, L10h, self.w_5),3)

            if c_req < C:
                caso = "Si"
            else:
                caso = "No"

            lista_tabla = [C,Cor, f0, Factor,e,Rela,y,P,c_req,caso]
            lista_final.append(lista_tabla)
        return lista_final

#Inicialización del codigo
if __name__ == "__main__":
    ventana = Tk()
    ventana.geometry('800x530')
    ventana.wm_title('Calculos de Rodamiento')
    ventana.config(bg='#515d6e', bd=4)
    #ventana.iconbitmap('roda.ico')
    app = Grafica(ventana)
    app.mainloop()


from collections import defaultdict

input_file = 'day-08/input.txt'

def get_max_reg(input, all_time_max = False):
  max_value = 0
  registers = defaultdict(int) #Registers ininitally zero
  for line in input.splitlines():
    reg, op, val, _, cond_reg, cond_op, cond_val = line.split()
    if eval(str(registers[cond_reg]) + cond_op + cond_val):
      if op == "dec":
        val = -int(val)
      registers[reg] += int(val)
      max_value = max(max_value, registers[reg])
  if not all_time_max:
    max_value = max(registers.values())
  return max_value

def part1(input):
  return get_max_reg(input)

def part2(input):
  return get_max_reg(input, True)

if __name__ == "__main__":
  with open(input_file) as f:
    data = f.read()
  print("Part 1: ", part1(data))
  print("Part 2: ", part2(data))


import requests
import json
from mysql_query import *

# API get request for metadata from OpenLibrary.org
def api_request_metadata(isbn):
    response = requests.get("http://openlibrary.org/isbn/{}.json".format(isbn))
    while True:
        try:
            book_metadata_json = response.json()
            return book_metadata_json
        except json.decoder.JSONDecodeError:
            print("JSON Decoding Failed. Check ISBN.")
            break

# Retrieve an ISBN from a dictionary
def dict_to_isbn(record):
    if record['ISBN13']:
        isbn = record['ISBN13']
    elif record['ISBN10']:
        isbn = record['ISBN10']
    else:
        isbn = ''
        print("NO ISBN PROVIDED")
    return isbn

# Query for a book from intake cache table
def query_for_book():
    db = 'book-report'
    sql_query = 'SELECT * FROM intake_cache LIMIT 1'
    records = mysql_query_select(db, sql_query)
    # Removing the array that encapsulates the dictionary.
    records = records[0]
    print(records)
    return records