# Path generator by Team Griffin

from __future__ import print_function

import pyvisgraph as vg

import itertools
import time
import sys

if (len(sys.argv) > 1):
    instance_number = int(sys.argv[1])
    # Import instance information
    execfile("instance_%d.py" % instance_number)

    # Calculate shortest paths

    g = vg.VisGraph()
    g.load('graph_%d.pk1' % instance_number)

    # Compute paths

    f = open('C:\\dev\\path_%d.txt' % instance_number, 'w')

    t1 = time.clock()

    loopCounter = 0
    totalCount = len(robots)
    for pair in itertools.combinations(robots, 2):
        #print("From: %d to %d:" % (pair[0].extradata_1, pair[1].extradata_1))
        shortest = g.shortest_path(pair[0], pair[1])
        numWaypoints = len(shortest) - 2
        #print("Waypoint length: %d" % numWaypoints)

        if numWaypoints > 0:
            #print(shortest)
            builtstr = "%d,%d#" % (pair[0].extradata_1, pair[1].extradata_1)
            # First element
            builtstr += str(shortest[1].extradata_1)
            builtstr += ":"
            builtstr += str(shortest[1].extradata_2)

            # All the rest
            for waypoint in shortest[2:-1]:
                builtstr += "|"
                builtstr += str(waypoint.extradata_1)
                builtstr += ":"
                builtstr += str(waypoint.extradata_2)

            print(builtstr, file=f)

        loopCounter += 1
        if (loopCounter % 20 == 0):
            elapsed = time.clock() - t1
            completed = pair[0].extradata_1
            left = totalCount - pair[0].extradata_1
            if completed > 0:
                time_for_one = elapsed / completed
            else:
                time_for_one = 0

            time_remaining = time_for_one * left
            print("Status: %d:%d / %d. Elapsed: %f seconds. Estimated time remaining: %f s." % (completed, pair[1].extradata_1, totalCount, elapsed, time_remaining))

    print("Computing paths took %f seconds." % (time.clock()-t1))

else:
    print("Invalid instance number")


import solution
from math import log

class Solution(solution.Solution):
    def solve(self, test_input=None):
        return self.pathInZigZagTree(label=test_input)

    def pathInZigZagTree(self, label):
        """
        :type label: int
        :rtype: List[int]
        """
        ans = [label]
        # 初始入口端点
        last = 2 ** int(log(label, 2))
        while label > 1:
            # 上一层节点到其出口端点的距离
            add = label - last >> 1
            # 计算父亲节点的值
            label = last - 1 - add
            # 下一个入口端点必然是除以2的关系
            last >>= 1
            ans.append(label)
        return ans[::-1]

        # ans = [label]
        # # 初始出口端点
        # last = 2 ** (int(log(label, 2)) + 1)
        # while label > 1:
        #     # 上一层节点到其入口端点的距离
        #     dis = last - 1 - label >> 1
        #     # 计算父亲节点的值
        #     label = last // 4 + dis
        #     # 下一个出口端点必然是除以2的关系
        #     last >>= 1
        #     ans.append(label)
        # return ans[::-1]


import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
from mask_shape_border import mask_shape_border

DS_y=xr.open_dataset("yield_soy_1979-2012.nc",decode_times=False).sel(lon=slice(-61,-44),lat=slice(-5,-33))
DS_y['time'] = pd.to_datetime(list(range(1979, 2013)), format='%Y').year
DS_y=DS_y.sel(time=slice('1980','2010'))
adm1_shapes = list(shpreader.Reader('gadm36_BRA_1.shp').geometries())
clipped= mask_shape_border(DS_y,'gadm36_BRA_0.shp' )
DS_y=clipped

# DS_y2 = xr.open_dataset("yield_soy_1979-2012.nc",decode_times=False).sel(lon=slice(-100.25,-80.25),lat=slice(50.25,30.25), time=slice(1,31))
# DS_y2['time'] = pd.to_datetime(list(range(1980, 2011)), format='%Y').year
# clipped= mask_shape_border(DS_y2,'gadm36_USA_0.shp' )
# DS_y2=clipped

# Iizumi data yield
ds_iizumi = xr.open_mfdataset('soybean/*.nc4', concat_dim="time", combine='nested')
ds_iizumi = ds_iizumi.assign_coords({"time" : ds_iizumi.time})
ds_iizumi['lon'] = (ds_iizumi.coords['lon'] + 180) % 360 - 180
ds_iizumi = ds_iizumi.sortby(ds_iizumi.lon)
ds_iizumi['time'] = pd.to_datetime(list(range(1981, 2017)), format='%Y').year
ds_iizumi = ds_iizumi.rename({'lon': 'longitude','lat': 'latitude','var' : 'yield'})
ds_iizumi['yield'].attrs = {'units': 'ton/ha', 'long_name': 'Yield in tons per hectare'}
# ds_iizumi.to_netcdf('soybean_iizumi.nc')
# test = xr.open_dataset("soybean_iizumi.nc")
da_iizumi = ds_iizumi['yield']
clipped= mask_shape_border(ds_iizumi,'gadm36_BRA_0.shp' )
ds_iizumi=clipped

#%% Average and standard deviation of soybean yield
yield_mean=DS_y['yield'].mean(dim = 'time', keep_attrs=True)
yield_std=DS_y['yield'].std(dim = 'time', keep_attrs=True)

plt.figure(figsize=(20,10))
ax=plt.axes(projection=ccrs.PlateCarree())
fig=yield_mean.plot(x='lon', y='lat', transform=ccrs.PlateCarree(),robust=True,cbar_kwargs={'label': yield_mean.attrs['units']}, cmap='Reds')
ax.set_title('Mean soy yield along time')
ax.set_xticks(ax.get_xticks()[::2]); ax.set_yticks(ax.get_yticks()[::1])
ax.add_geometries(adm1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-61,-44,-33,-8], ccrs.PlateCarree())
plt.show()

plt.figure(figsize=(20,10))
ax=plt.axes(projection=ccrs.PlateCarree())
fig=yield_std.plot(x='lon', y='lat', transform=ccrs.PlateCarree(),robust=True,cbar_kwargs={'label': yield_mean.attrs['units']}, cmap='Reds')
ax.set_title('Standard deviation of soybean yield along time')
ax.set_xticks(ax.get_xticks()[::2]); ax.set_yticks(ax.get_yticks()[::1])
ax.add_geometries(adm1_shapes, ccrs.PlateCarree(),edgecolor='black', facecolor=(0,1,0,0.0))
ax.set_extent([-61,-44,-33,-8], ccrs.PlateCarree())
plt.show()

#Establish temporal behaviour of the yield function (model based wofosst) wrt to the mean, +-SD.
df_t=ds_iizumi['yield'].to_series().groupby(['time']).mean()
df_t_mean=df_t.mean()
df_t_std=df_t.std()
df_t_low=df_t_mean - df_t_std
df_t_high=df_t_mean + df_t_std
plt.figure(figsize=(20,10))
plt.axhline(y=df_t_mean, color='r', linestyle='-')
plt.axhline(y=df_t_low, color='r', linestyle='--')
plt.axhline(y=df_t_high, color='r', linestyle='--')
plt.plot(df_t)
# plt.show()

# df_t2=DS_y2['yield'].to_series().groupby(['time']).mean()
# df_t2_mean=df_t2.mean()
# df_t2_std=df_t2.std()
# df_t2_low=df_t2_mean - df_t2_std
# df_t2_high=df_t2_mean + df_t2_std
# # plt.figure(figsize=(20,10))
# plt.axhline(y=df_t2_mean, color='r', linestyle='-')
# plt.axhline(y=df_t2_low, color='r', linestyle='--')
# plt.axhline(y=df_t2_high, color='r', linestyle='--')
# plt.plot(df_t2)
# plt.show()

#%%
from sklearn.linear_model import LinearRegression

series = pd.read_csv('fao_yield_soybean.csv', sep = ';', header=0, index_col=0)
series = series.loc[(series.index >= 1980) & (series.index <= 2010)]
# fit linear model
X = [i for i in range(0, len(series))]
X = np.reshape(X, (len(X), 1))
y = series.values
model = LinearRegression()
model.fit(X, y)
# calculate trend
trend = model.predict(X)
# plot trend
plt.plot(y)
plt.plot(trend)
plt.show()
# detrend
detrended = [trend.mean() + y[i]-trend[i] for i in range(0, len(series))]
df_detrended = pd.DataFrame(detrended, index=series.index, columns=['yield'] )  # 1st row as the column names
df_data_det = df_detrended.loc[(df_detrended.index >= 1981) & (df_detrended.index <= 2010)]
df_data_det.index = pd.to_datetime(list(range(1981, 2011)), format='%Y').year
plt.plot(df_data_det)
plt.show()

#detrend yield
series = df_t
# fit linear model
X = [i for i in range(0, len(series))]
X = np.reshape(X, (len(X), 1))
y = series.values
model = LinearRegression()
model.fit(X, y)
# calculate trend
trend = model.predict(X)
# plot trend
plt.plot(y)
plt.plot(trend)
plt.show()
# detrend
detrended = [trend.mean() + y[i]-trend[i] for i in range(0, len(series))]
df_detrended = pd.DataFrame(detrended, index=series.index, columns=['yield'] )  # 1st row as the column names
df_iizumi = df_detrended.loc[(df_detrended.index >= 1980) & (df_detrended.index <= 2010)]
df_iizumi.index = pd.to_datetime(list(range(1981, 2011)), format='%Y').year
plt.plot(df_iizumi)
plt.show()

# compare model and data yield
plt.figure(figsize=(10,6))
p1=plt.plot(df_iizumi, label='Model yield')
p2=plt.axhline(y=df_t_low, color='r', linestyle='--', label='Upper SD model yield')
p3=plt.axhline(y=df_t_mean, color='r', linestyle='-', label='Mean model yield')
p4=plt.axhline(y=df_t_high, color='r', linestyle='--', label='Lower SD model yield')
p5=plt.plot(df_data_det, label='Data yield')
plt.title('Comparison model and data yield',fontsize='x-large')
plt.ylabel('Yield')
plt.xlabel('Year')
plt.legend(loc='best', fontsize='x-large')
plt.show()

# calculate Pearson's correlation
from scipy.stats import pearsonr
val1=[float(i) for i in df_data_det.values]
val2=[float(i) for i in df_iizumi.values]
corr, _ = pearsonr(val2, val1)
print('Pearsons correlation: %.3f' % corr)


from fastapi import HTTPException
from pydantic import BaseModel, EmailStr, constr
from datetime import date, timedelta
from db_mysql.Connection_mysql import conecction_mysql

class UserRegister(BaseModel):
    sexo: constr(max_length=10)
    fecha_de_nacimiento: date
    nombre: constr(max_length=100)
    apellido: constr(max_length=100)
    email: EmailStr
    direccion: constr(max_length=200)
    casa_apartamento: constr(max_length=50)
    pais: constr(max_length=100)
    departamento: constr(max_length=100)
    ciudad: constr(max_length=100)

def adult(birth_date: date) -> bool:
    today = date.today()
    limit_date = today - timedelta(days=365*18)
    return birth_date <= limit_date

def register(user_register: UserRegister):

    sexo = user_register.sexo
    fecha_de_nacimiento = user_register.fecha_de_nacimiento
    nombre= user_register.nombre
    apellido= user_register.apellido
    email= user_register.email
    direccion= user_register.direccion
    casa_apartamento=user_register.casa_apartamento
    pais=user_register.pais
    departamento= user_register.departamento
    ciudad= user_register.ciudad

    if adult(birth_date=fecha_de_nacimiento):

        query = f"SELECT COUNT(*) FROM users WHERE ciudad = '{ciudad}'"
        conecction = conecction_mysql()
        cursor = conecction.cursor()
        cursor.execute(query)
        count_city = cursor.fetchone()[0]

        if count_city < 3:

            query = f"""INSERT INTO users
            (sexo, fecha_de_nacimiento,
             nombre, apellido, email,
             direccion, casa_apartamento,
             pais, departamento,ciudad)
             VALUES ('{sexo}', '{fecha_de_nacimiento}',
            '{nombre}', '{apellido}', '{email}',
            '{direccion}', '{casa_apartamento}',
            '{pais}', '{departamento}', '{ciudad}')"""

            cursor.execute(query)
            conecction.commit()
            user_id = cursor.lastrowid

            return {"detail": f"User register with success ",
                    "id": user_id}

        else:

            raise HTTPException(status_code=401, detail="already on the limit of allowed cities")

    else:
        raise HTTPException(status_code=401, detail="the user is not of legal age")


#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Created by sublime_text at home on  2018/2/28—20:12！
@Gnome:   Live and learn!
@Author: 葛绪涛
@Nickname:  wordGe
@QQ:  690815818
@Filename: web.py
@Blog: http://higexutao.blog.163.com
"""
import os.path
from tornado import httpserver, web, ioloop

# 功能模块 实现具体的功能
class MainPageHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        # self.write("Hello world!")
        self.render("formSubmit.html")

    def post(self, *args, **kwargs):
        # pass
        # file_metas = self.request.files.get('file')
        # print(type(file_metas))
        # print("Hi")
        user_name = self.get_argument("username")
        user_email = self.get_argument("email")
        user_website = self.get_argument("website")
        user_language = self.get_argument("language")
        self.render("user.html", username=user_name, email=user_email, website=user_website, language=user_language)

template_path = os.path.join(os.path.dirname(__file__), "template")
print(template_path)
# 设置路径
settings = {
    'template_path': "template",
    #     模板文件路径参数 ，一般指 网页
    'static_path': "static",

}

# 路由 也即分机，也可以理解为功能模块在哪里
# 下面是没有加设置参数时的代码，**是设置动态参数
# application = web.Application([
#     (r"/", MainPageHandler),
# ])
# 上面设置了动态参数，下面开始应用，注意是加**settings
application = web.Application([
    (r"/", MainPageHandler),
], **settings)

# handlers = [
#     (r"/", IndexHandler),
#     (r"/user", UserHandler)
# ]
# socket 服务  前台 联系方式   诸如端口
if __name__ == '__main__':
    http_server = httpserver.HTTPServer(application)
    http_server.listen(5407)
    ioloop.IOLoop.current().start()


from typing import Any, List, Dict
import xlwt
import xlrd2
import openpyxl
from ..basic.exClass import CommonException
from ..exFunc import *
from .fileFunc import readLines, isExist, createFile, deleteFile, writeAppend

class XlsWriter():

    def __init__(self, path: str) -> None:
        self.path = path

        if path.endswith('.xlsx'):
            self.isXlsx = True
            self.workbook = openpyxl.Workbook(write_only=True)
        elif path.endswith('.xls'):
            self.isXlsx = False
            self.workbook = xlwt.Workbook(encoding="utf-8")
        else:
            raise CommonException('文件类型不正确')

    def save(self):
        self.workbook.save(self.path)

    def createSheet(self, headers: List[str], datas: List[List[Any]],
                    sheetName: str='sheet1'):
        # 生成sheet
        if self.isXlsx:

            sheet = self.workbook.create_sheet(sheetName)
            # 写入标题
            sheet.append(headers)

            # 写入每一行
            for data in datas:
                sheet.append(data)
        else:

            sheet = self.workbook.add_sheet(sheetName)
            # 写入标题
            for col, column in enumerate(headers):
                sheet.write(0, col, column)

            # 写入每一行
            for row, data in enumerate(datas):
                for col, col_data in enumerate(data):
                    sheet.write(row + 1, col, col_data)

    def createSheetWithDict(self, dataList: List[Dict[str, Any]],
                            sheetName: str='sheet1'):
        if len(dataList) > 10:
            headers = list(set(dataList[0:10].flatMap(lambda d: d.ks())))
        else:
            headers = list(set(dataList.flatMap(lambda d: d.ks())))
        datas = []
        for data in dataList:
            tmp = []
            for t in headers:
                if t in data and data[t]:
                    tmp.append(data[t])
                else:
                    tmp.append('')
            datas.append(tmp)
        self.createSheet(headers, datas, sheetName)

class XlsReader():

    def __init__(self, path) -> None:
        self.workbook = xlrd2.open_workbook(path)

    def sheetNames(self):
        return self.workbook.sheet_names()

    def readSheetByName(self, sheetName: str) -> List[Dict[str, Any]]:
        sh = self.workbook.sheet_by_name(sheetName)
        re = []
        headers = sh.row_values(0)
        for i in range(1, sh.nrows):
            d = dict(zip(headers, sh.row_values(i)))
            re.append(d)
        return re

    def readSheetByIndex(self, sheetIndex: int=0) -> List[Dict[str, Any]]:
        sh = self.workbook.sheet_by_index(sheetIndex)
        re = []
        headers = sh.row_values(0)
        for i in range(1, sh.nrows):
            d = dict(zip(headers, sh.row_values(i)))
            re.append(d)
        return re

    def readSheetAsMatrixByName(self, sheetName: str) -> List[Dict[str, Any]]:
        sh = self.workbook.sheet_by_name(sheetName)
        re = []
        for i in range(0, sh.nrows):
            re.append(sh.row_values(i))
        return re

class CsvRW():
    def __init__(self, path, splitFlag: str = ',', encoding='utf-8') -> None:
        self.path = path
        self.splitFlag = splitFlag
        self.encoding = encoding

        if not isExist(self.path):
            createFile(self.path)

    def headers(self):
        lines = readLines(self.path, 1, encoding=self.encoding)
        if len(lines) >= 1:
            return lines[0].split(self.splitFlag).filter(lambda s: s != '')
        return []

    def read(self):
        lines = readLines(self.path, encoding=self.encoding)
        re = []
        headers = self.headers()
        for line in lines:
            d = dict(zip(headers, line.split(self.splitFlag)))
            re.append(d)
        return re

    def clear(self):
        deleteFile(self.path)
        createFile(self.path)

    def write(self, datas: List[dict]):
        headers = self.headers()
        strs = []
        if len(headers) == 0:
            headers = list(datas[0].keys())
            strs.append(self.splitFlag.join(headers)+'\n')

        for data in datas:
            tmp = []
            for t in headers:
                if t in data and data[t]:
                    tmp.append(
                        '"'+str(data[t]).replace('\\', '\\\\').replace('"', '\"')+'"')
                else:
                    tmp.append('""')
            strs.append(self.splitFlag.join(tmp)+'\n')
        writeAppend(self.path, lines=strs, encoding=self.encoding)


#Universidad de la Fuerzas Armadas-ESPE
#Autor:Pamela Jesabel Carriel Mier
"""Modifica la función buscar_valor en Python para que reciba un árbol binario y un valor como
parámetros, y devuelva True si el valor se encuentra en el árbol, y False en caso contrario."""
#Fecha : 23 de junio del 2023
class Nodo:
    def __init__(self, valor):
        self.valor = valor
        self.izquierda = None
        self.derecha = None

def crear_arbol():
    return None

arbol = crear_arbol()

def insertar(arbol, valor):
    if arbol is None:
        return Nodo(valor)
    else:
        if valor < arbol.valor:
            arbol.izquierda = insertar(arbol.izquierda, valor)
        else:
            arbol.derecha = insertar(arbol.derecha, valor)
        return arbol

"""arbol = insertar(arbol, 10)
arbol = insertar(arbol, 13)
arbol = insertar(arbol, 16)
arbol = insertar(arbol, 19)"""

def buscar_valor(arbol, valor):
    if arbol is None:
        return False
    elif arbol.valor == valor:
        return True
    elif valor < arbol.valor:
        return buscar_valor(arbol.izquierda, valor)
    else:
        return buscar_valor(arbol.derecha, valor)

print(buscar_valor(arbol , 1))


#!/usr/bin/env python
import argparse
import glob
import os
import re

import cv2
import numpy as np
import pandas as pd
from skimage import transform as tf

from utils import create_dictionary_lang

CHROME_PATH = "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"

lang_code_dict = create_dictionary_lang()
root_dir = "Data/FLORES/"

# TODO: font weight?
dict_properties = {
    "color": ["black"],
    "opacity": ["1", "0.3"],
    "font_size": ["20px"],
    "letter_spacing": ["normal", "0.2em", "-0.2em"],
    "italic": [True, False],
    "bold": [True, False],
    "gauss": [True, False],
    "skew": [True, False]
}

def read_fonts_file():
    df = pd.read_csv('Data/misc/languages_fonts_codes.csv')
    lang_codes = df["Code"].tolist()
    lang_fonts = df["Fonts"].tolist()
    return lang_codes, lang_fonts

def create_style_file(
        font, color, opacity, font_size, letter_spacing, italic, bold, name_style
):
    str_font = "src: url(fonts/" + font + ".ttf);"
    full_style = (
            """
        @font-face {
        font-family: defined_font;
        """
            + str_font
            + """
    }
    p {
        font-family: defined_font;
        color: """
            + color
            + ";"
            + """
        opacity: """
            + opacity
            + ";"
            + """
        letter-spacing:"""
            + letter_spacing
            + ";"
            + """
        font-size:"""
            + font_size
            + ";"
    )
    if italic:
        full_style += """
        font-style: italic;"""
    if bold:
        full_style += """
        font-weight: bold;"""

    full_style += """
    }
    """
    with open("Data/augmentation/styles/" + name_style + ".css", "w+") as f:
        f.write(full_style)

def create_html_file(root_path, list_sentences, name_html_file, name_style):
    str_style = (
            f"""<link rel="stylesheet" href="{os.path.abspath('Data/augmentation/styles/' + name_style + '.css')}">"""
    )
    str_html_head = (
            """
        <!DOCTYPE html>
        <html lang="en">

        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content=
              "width=device-width, initial-scale=1.0">
        """
            + str_style
            + """
    </head>
    <body>
    """
    )
    # put all text into one paragraph
    str_html_text = "<p>" + "".join(list_sentences) + "</p>"
    str_html_head_close = """
    </body>
    </html>
    """
    full_text = str_html_head + str_html_text + str_html_head_close
    with open(os.path.join(root_path, name_html_file + ".html"), "w") as f:
        f.write(full_text)

def save_html_to_pdf(root_save_pdfs: str, root_html_url: str, name_html_file: str) -> None:
    os.system(
        CHROME_PATH
        + " --headless --print-to-pdf-no-header --print-to-pdf="
        + root_save_pdfs
        + name_html_file
        + ".pdf "
        + root_html_url
        + name_html_file
        + ".html"
    )

def save_pdf_to_png(lang_name, name_file, name_html_file, root_path: str = "Data/FLORES/"):
    # if entire pdf -> need to first split into pages
    root_save_pdfs = "Data/augmentation/pdfs/"
    os.makedirs(root_path + lang_name + "/png/" + name_file, exist_ok=True)
    path_png_out = root_path + lang_name + "/png/" + name_file + "/" + name_html_file
    path_pdf_in = root_save_pdfs + name_html_file + ".pdf"
    print("Saving pdf to png for " + lang_name)
    os.system("convert -density 300 -trim " + path_pdf_in + " -quality 100 " + path_png_out + "%02d.png")

def add_gaussian_noise(lang_name, name_file, name_html_file, root_path: str = "Data/FLORES/"):
    img = cv2.imread(root_path + lang_name + "/png/" + name_file + "/" + name_html_file + ".png")
    # Generate Gaussian noise
    gauss = np.random.normal(0, 1, img.size)
    gauss = gauss.reshape(img.shape[0], img.shape[1], img.shape[2]).astype("uint8")
    # Add the Gaussian noise to the image
    img_gauss = cv2.add(img, gauss)

    img_gauss = cv2.cvtColor(img_gauss, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(
        root_path
        + lang_name
        + "/png/"
        + name_file
        + "/"
        + name_html_file
        + "_gauss"
        + ".png",
        img_gauss,
    )

def add_salt_pepper_noise(lang_name, name_file, name_html_file, amount, s_vs_p, root_path: str = "Data/FLORES/"):
    image = cv2.imread(
        root_path + lang_name + "/png/" + name_file + "/" + name_html_file + ".png"
    )
    img_noise = np.copy(image)
    # Salt mode
    num_salt = np.ceil(amount * image.size * s_vs_p)
    coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape]
    img_noise[coords] = 1

    # Pepper mode
    num_pepper = np.ceil(amount * image.size * (1. - s_vs_p))
    coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape]
    img_noise[coords] = 0
    img_noise = cv2.cvtColor(img_noise, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(
        root_path
        + lang_name
        + "/png/"
        + name_file
        + "/"
        + name_html_file
        + "_salt_pepper"
        + ".png",
        img_noise,
    )

def add_speckle_noise(lang_name, name_file, name_html_file, root_path: str = "Data/FLORES/"):
    img = cv2.imread(
        root_path + lang_name + "/png/" + name_file + "/" + name_html_file + ".png"
    )
    gauss = np.random.normal(0, 1, img.size)
    gauss = gauss.reshape(img.shape[0], img.shape[1], img.shape[2]).astype('uint8')
    img_noise = img + img * gauss
    img_noise = cv2.cvtColor(img_noise, cv2.COLOR_BGR2GRAY)

    cv2.imwrite(
        root_path
        + lang_name
        + "/png/"
        + name_file
        + "/"
        + name_html_file
        + "_gauss"
        + ".png",
        img_noise,
    )

def add_skew(lang_name, name_file, name_html_file, root_path: str = "Data/FLORES/"):
    img = cv2.imread(
        root_path + lang_name + "/png/" + name_file + "/" + name_html_file + ".png"
    )
    # Create Affine transform
    affine_tf = tf.AffineTransform(shear=0.1)
    # Apply transform to image data
    img_skew = tf.warp(img, inverse_map=affine_tf) * 255
    cv2.imwrite(
        root_path
        + lang_name
        + "/png/"
        + name_file
        + "/"
        + name_html_file
        + "_skew"
        + ".png",
        img_skew,
    )

def run_augmentation_udhr(lang_code):
    lang_name = lang_code_dict[lang_code]

    lang_codes, lang_fonts = read_fonts_file()
    index_lang_code = lang_codes.index(lang_code)

    fonts = lang_fonts[index_lang_code].split("; ")

    color = dict_properties["color"][0]
    opacity = dict_properties["opacity"][0]
    letter_spacing = dict_properties["letter_spacing"][0]
    italic = dict_properties["italic"][1]
    bold = dict_properties["bold"][1]

    font = fonts[0]
    root = os.path.join('Data/UDHR/', lang_name)
    root_path = os.path.join('Data/UDHR/annotations/', lang_code, "pdfs_synth")
    os.makedirs(root_path, exist_ok=True)
    txt_files = glob.glob(root + '/*[0-9].txt')
    name_style = font + "_" + color.replace("#", "") + "_" + opacity + "_" + letter_spacing
    if italic:
        name_style += "_" + "italic"
    if bold:
        name_style += "_" + "bold"

    for txt_file in txt_files:
        with open(txt_file, encoding="utf8") as file:
            list_sentences = file.read()
        name_file = txt_file.split("/")[-1][:-4]
        nb = str(re.findall(r'\d+', name_file)[0])
        name_html_file = f"{lang_code}_{nb}"
        create_html_file(root_path, list_sentences, name_html_file, name_style)

        root_save_pdfs = root_path
        root_html_url = root_path
        save_html_to_pdf(root_save_pdfs, root_html_url, name_html_file)
        print("Saving pdf to png for " + name_html_file)
        path_png_out = os.path.join(root_path, name_html_file + ".png")
        path_pdf_in = os.path.join(root_path, name_html_file + ".pdf")
        os.system("convert -density 300 -trim " + path_pdf_in + " -quality 100 " + path_png_out)

def run_augmentation(lang_code):
    lang_name = lang_code_dict[lang_code]
    root_lang_name = root_dir + lang_name + "/"

    lang_codes, lang_fonts = read_fonts_file()
    index_lang_code = lang_codes.index(lang_code)

    fonts = lang_fonts[index_lang_code].split("; ")

    color = dict_properties["color"][0]
    opacity = dict_properties["opacity"][0]
    letter_spacing = dict_properties["letter_spacing"][0]
    italic = dict_properties["italic"][1]
    bold = dict_properties["bold"][1]
    gauss = dict_properties["gauss"][1]
    skew = dict_properties["skew"][1]

    font = fonts[0]
    name_file = lang_code
    with open(os.path.join(root_lang_name, name_file + ".txt"), encoding="utf-8") as file:
        list_sentences = file.readlines()

    name_style = font + "_" + color.replace("#", "") + "_" + opacity + "_" + letter_spacing
    if italic:
        name_style += "_" + "italic"
    if bold:
        name_style += "_" + "bold"
    name_html_file = name_file + "_" + name_style

    root_path = "Data/augmentation/htmls"
    create_html_file(root_path, list_sentences, name_html_file, name_style)

    root_save_pdfs = "Data/augmentation/pdfs"
    root_html_url = f"file://{os.path.abspath('Data/augmentation/htmls')}"
    save_html_to_pdf(root_save_pdfs, root_html_url, name_html_file)
    save_pdf_to_png(lang_name, name_file, name_html_file)
    if gauss:
        add_salt_pepper_noise(lang_name, name_file, name_html_file, amount=0.005, s_vs_p=0.5)
    if skew:
        add_skew(lang_name, name_file, name_html_file)

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--dataset", choices=["FLORES", "UDHR"], default="FLORES")
    return parser.parse_args()

def main() -> None:
    args = parse_args()

    for lang_code in lang_code_dict:
        if args.dataset == "FLORES":
            run_augmentation(lang_code)
        elif args.dataset == "UDHR":
            run_augmentation_udhr(lang_code)
        else:
            raise ValueError(f"Unknown dataset: {args.dataset}")

if __name__ == "__main__":
    main()


#!/usr/etc/env python3

def main():

    marvelchars= {
    "Starlord":
        {"real name": "peter quill",
        "powers": "dance moves",
        "archenemy": "Thanos"},

    "Mystique":
        {"real name": "raven darkholme",
        "powers": "shape shifter",
        "archenemy": "Professor X"},

    "Hulk":
        {"real name": "bruce banner",
        "powers": "super strength",
        "archenemy": "adrenaline"}
    }

    another = True;
    while another:
        choice = input(" Which character do you want to know about? (Starlord, Mystique, Hulk) ")
        character = marvelchars.get(choice.title())
        choice2 = input(" What statistic do you want to know about? (real name, powers, archenemy) ")
        stats = character.get(choice2.lower())

        print(f"{choice.title()}'s {choice2.lower()} is: {stats.title()}")

        another = eval(input("Try another character/stat? (True/False) "))

main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('promotions_app', '0002_promotionmanager'),
    ]

    operations = [
        migrations.DeleteModel(
            name='PromotionManager',
        ),
        migrations.AddField(
            model_name='promotion',
            name='account',
            field=models.ForeignKey(default='', to=settings.AUTH_USER_MODEL),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='promotion',
            name='desc',
            field=models.TextField(),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='promotion',
            name='image',
            field=models.ImageField(upload_to=b'promotions'),
            preserve_default=True,
        ),
    ]


# -*- coding: utf-8 -*-
"""
Preppin' Data 2023: Week 15 - Easter Dates
https://preppindata.blogspot.com/2023/04/2023-week-15-easter-dates.html

- Input the data
- Reshape it so that we have a list of Easter Sunday dates
- Filter the dataset so that we only have past dates
    - i.e. 1700 - 2023
- Output the data

Author: Kelly Gilbert
Created: 2023-04-12
Requirements:
  - input dataset:
      - easterdates.xls
  - output dataset (for results check only):
      - Easters.csv
"""

import pandas as pd
from output_check import output_check    # custom function for checking my output vs. the solution

#---------------------------------------------------------------------------------------------------
# input the data
#---------------------------------------------------------------------------------------------------

df = pd.read_excel(r'.\inputs\easterdates.xls')

#---------------------------------------------------------------------------------------------------
# process the data
#---------------------------------------------------------------------------------------------------

# reshape the month/day headers into two columns
df_headers = ( df.iloc[-2:].T
                 .set_axis(['day', 'month'], axis=1)
                 .query("day == day")
                 .assign(month = lambda df_x: df_x['month'].str.replace(' ', ''),
                         day = lambda df_x: df_x['day'].astype(int))
                 .ffill() )

# reshape the years into one column and join them to the month/days
df_easters = ( df.iloc[:-2]
                 .melt(var_name='col_name', value_name='year')
                 .assign(year = lambda df_x: pd.to_numeric(df_x['year'], errors='coerce'))
                 .query("year == year & year <= 2023")
                 .merge(df_headers,
                        how='inner',
                        left_on='col_name',
                        right_index=True) )

# construct the date and add the year rank
df_easters['Easter Sunday'] = ( pd.DatetimeIndex(df_easters['month'] + ' '
                                                    + df_easters['day'].astype(str) + ', '
                                                    + df_easters['year'].astype(int).astype(str))
                                     .to_period('D')
                                     .astype('datetime64[D]') )

df_easters['Calculation1'] = df_easters['year'].rank().astype(int)

#---------------------------------------------------------------------------------------------------
# output the file
#---------------------------------------------------------------------------------------------------

df_easters.to_csv(r'.\outputs\output-2023-15.csv',
                  index=False,
                  columns=['Calculation1', 'Easter Sunday'],
                  date_format='%d/%m/%Y')

#---------------------------------------------------------------------------------------------------
# check results
#---------------------------------------------------------------------------------------------------

solution_files = [r'.\outputs\Easters.csv']
my_files = [r'.\outputs\output-2023-15.csv']
unique_cols = [['Calculation1']]
col_order_matters = True
round_dec = 8

output_check(solution_files=solution_files, my_files=my_files, unique_cols=unique_cols,
             col_order_matters=col_order_matters, round_dec=round_dec)


import numpy as np
import pathlib, os, time

class Neuron:

    def __init__(self, numofinputs, weights=[-999], layerName="undefined"):
        """ initialises neuron class type. weights MUST be list, not integer. If only 1 weighting of n then pass [n] """
        self.activation = tanh
        self.layerName = layerName
        self.output = 0
        if weights[0] == -999:
            seed = gen_random_seed()
            np.random.seed()
            self.synaptic_weights = 2 * np.random.random((numofinputs, 1)) - 1
        else:
            self.synaptic_weights = weights
        # self.output = []
        true = True

    def mutate(self):  # this function randomly changes the weightings on the neuron
        for weight in self.synaptic_weights:
            weight = weight + 0.05 * (2 * np.random.random() - 1)

    # alternative way of thinking that stores output as object property:
    def think(self, input):
        self.output = self.activation(np.dot(input, self.synaptic_weights))

# activation function being used ---------------------------------------------------------------------------------------------------------------------------------------------
def tanh(input):
    return (np.tanh(input))

def tanh_derivative(x):
    return (1 - np.square(tanh(x)))

def gen_random_seed():
    return int(round(time.time() * 100) / 200) - np.random.rand(0, 1000)

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

class NeuralNet:
    """ This class constitutes multi layer neural network, with variable layer sizes. This translates into one input layer, one output layer and n hidden layers
        Requires inputs of matrix of layer sizes, form [n, m, o etc] where sum m,n,o = num of layers and m, n and o are respective layer sizes.
        Then, weights for each if known , the name of the net and the generation number.

        Passing -999 * layersize will generate weights randomly."""

    def __init__(self, layers=[], weights=[[], [], []], name=None, generation=0):
        self.name = name or str(int(round(time.time() * 1000)))
        self.layers = []
        self.generation = generation
        self.score = 0
        self.path = ""

        count = -1
        for n in range(0, len(layers)):
            count += 1
            self.layers.append([""] * layers[n])
            if n == 0:
                numOfInputs = layers[0]
            else:
                numOfInputs = layers[n - 1]
            self.init_layer(self.layers[n], weights[n], numOfInputs)

    def init_layer(self, layer, weights, numOfInputs):  # numOfInputs is num PER NEURON not total for layer
        if weights == []:
            weights.append(0) * len(layer)  # <-----------------------------------------
        for i in range(0, len(layer)):  # <----------------------------------------- HERE NEEDS WORK
            layer[i] = Neuron(numOfInputs, weights[0][i])  # <-----------------------------------------

    def run_first_layer(self, board):
        """the first layer takes inputs in a different way to the other layers and thus requires a seperate subroutine
        takes board as input. players squares should be represented as a one """

        count = 0
        for row in board:
            for square in row:
                self.layers[0][count].think(square)
                count += 1

    def feed_forward(self, layerRef=1):
        """ takes reference of the layer to pass info from [reference being with indexing starting at 1,
        so to pass info from first layer to second, layerRef = 1 etc]"""
        inputs = []
        for source in self.layers[layerRef - 1]:
            inputs.append(source.output)
        for target in self.layers[layerRef]:
            target.think(inputs)

    def mutate_network(self):
        """ layer1 should not be mutated as weightings must always remain zero
        This method mutates the other two layers randomly"""

        for layer in self.layers[1:]:
            for i in layer:
                i.mutate()

    def rtn_rating(self):
        return self.layers[-1][0].output

    def save_network(self):
        """ saves network into directory set """

        fLayers = open(self.path + "/layers.txt", "w")
        fLayers.write(str(len(self.layers)))
        fLayers.close()

        for i in range(0, len(self.layers)):
            fLayer = open(self.path + "/layer_%s.txt" % i, "w")

            for n in self.layers[i]:
                fLayer.write(str(n.synaptic_weights))
                fLayer.write("\n\n")
            fLayer.close()

        return 0

    def read_weights_from_file(self, projectName):
        """ reads weights from file, needs projectName parameter. rest of file path is derived from self data."""

        fLayers = open(self.path + "/layers.txt", "r")
        numOfLayers = int(fLayers.read())
        fLayers.close()

        weights = []
        tempNeuron = []
        tempLayer = []

        for i in range(0, numOfLayers):
            fLayer = open(self.path + "/layer_%s.txt" % i, "r")

            for line in fLayer:
                if line != "\n":
                    tempNeuron.append(float(strip_brackets_and_whitespace(line)))
                else:
                    tempLayer.append(tempNeuron)
                    tempNeuron = []

            weights.append(tempLayer)
            tempLayer = []

        return weights

    def make_net_dir(self, projectName):
        """ Makes new directory for Network.
        Takes path of file to save relative to, name of project, generation reference string, """

        self.path = os.path.join(os.getcwd(), projectName, "gen_" + str(self.generation), self.name)
        pathlib.Path(self.path).mkdir(parents=True, exist_ok=True)

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

def strip_brackets_and_whitespace(input):
    return input.rstrip().replace('[', '').replace(']', '')

def load_network(projectName, generation, name):
    """ loads network from a file. """
    networkPath = os.path.join(os.cwd(), projectName, generation, name)

    ############### to this point, return

    return 1


def train_epoch(model, dataloader, criterion, reg_criterion, optimizer, scheduler, device, wandb):
    losses = []
    model.train()
    for i, (img_names, images, genders, ages) in enumerate(dataloader):
        images = images.to(device)
        gt_genders = genders.to(device)
        gt_ages = ages.to(device)
        pred_genders, pred_ages = model(images)

        gender_loss = criterion(pred_genders, gt_genders)
        age_loss = reg_criterion(pred_ages, gt_ages)
        # loss = gender_loss + age_loss
        loss = gender_loss

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if scheduler is not None:
            scheduler.step()

        losses.append(loss.item())
        wandb.log({'lr': scheduler.get_lr()[0], 'loss': loss.item()})

    return losses


import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
from undetected_chromedriver import Chrome, ChromeOptions
from getCarInfo import getCarInfo
from bs4 import BeautifulSoup
from pegaproxy import pegar_proxy

completo = []

with open('linkYearsCar.txt', 'r') as file:
    for linha in file:
        separado = linha.split(" c")
        for linha2 in separado:
            completo.append(linha2)

for i in range(len(completo)):
    if "atalogo" in completo[i]:
        completo[i] = completo[i].replace("atalogo", "catalogo")

for i in range(len(completo)):
    if "ccatalogo" in completo[i]:
        completo[i] = completo[i].replace("ccatalogo", "catalogo")

def get_random_user_agent():
    user_agent = UserAgent()
    return user_agent.random

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = f'170.106.117.131:11513'

options = Options()

def generate_random_user_agent():
    user_agent = UserAgent()
    return user_agent.random

extension_path = '/home/davi/Downloads/adblock.crx'
options.add_argument("--window-size=800,600")
options.add_extension(extension_path)
options.add_argument("--disable-images")

options.add_argument("--no-first-run")
# Desativar o uso de cookies
options.add_argument("--proxy-server=http://{}".format(proxy.http_proxy))
prefs = {"profile.managed_default_content_settings.images": 2}  # 2 significa não carregar imagens
options.add_experimental_option("prefs", prefs)

# Desativar plugins
def reiniciar_proxy():
    global driver
    driver.quit()
    options = Options()
    print('reiniciando proxy')
    extension_path = '/home/davi/Downloads/adblock.crx'
    prefs = {"profile.managed_default_content_settings.images": 2}  # 2 significa não carregar imagens
    options.add_experimental_option("prefs", prefs)
    options.add_argument("--no-first-run")
    ip, port = pegar_proxy()
    proxy.http_proxy = f'{ip}:{port}'
    options.add_argument("--proxy-server=http://{}".format(proxy.http_proxy))
    driver = webdriver.Chrome(options=options)
    driver.set_page_load_timeout(60)

driver = webdriver.Chrome(options=options)
driver.set_page_load_timeout(60)

def reiniciar_pagina(driver):
    reiniciar_proxy()
    time.sleep(10)

carrosNaWeb = "https://carrosnaweb.com.br/"

linksCarros = []
c = 0
#1363
for index, link2 in enumerate(completo[3987:], start=3987):
        filename = "esta agora.txt"
        with open(filename, "a") as f:
                f.write(f'index: {index}' + "\n")
        print(link2)
        print(index)
        try:
            z = 0
            while z < 1:
                try:
                    while True:
                        if c == 10:
                            reiniciar_proxy()
                            c = 0
                        else:
                            c = c+1
                        driver.get(carrosNaWeb + link2)
                        time.sleep(3)
                        url_atual = driver.current_url
                        z = 10
                        if url_atual == 'https://www.carrosnaweb.com.br/erro.asp':
                            reiniciar_proxy()
                            time.sleep(24)
                        else:
                            break
                except TimeoutException:
                    print("reiniciando pagina")
                    reiniciar_pagina(driver)
                    z = 0
            while True:
                html12 = driver.page_source
                doc = BeautifulSoup(html12, "html.parser")
                links = doc.find_all(["td"], bgcolor="#ffffff", align="left")
                for link in links:
                    a_tags = link.find_all('a')
                    for a_tag in a_tags:
                        a_tag = a_tag.get('href')
                        try:
                            x = 0
                            while x < 1:
                                try:
                                    while True:
                                        print('chegou aqui')
                                        driver.get(carrosNaWeb + a_tag)
                                        time.sleep(7)
                                        url_atual = driver.current_url
                                        x = 10
                                        if url_atual == 'https://www.carrosnaweb.com.br/erro.asp':
                                            reiniciar_proxy()
                                            time.sleep(10)
                                        else:
                                            break
                                except TimeoutException:
                                    print('reiniciando pagina')
                                    x = 0
                                    reiniciar_pagina(driver)
                                    time.sleep(10)
                            html = driver.page_source
                            pegou = getCarInfo(html)
                            filename = "esta agora.txt"
                            with open(filename, "a") as f:
                                f.write(f'Esse carro deu certo' + "\n")
                            if pegou == 'error':
                                filename = "erro de carros.txt"
                                with open(filename, "a") as f:
                                        f.write(f'{carrosNaWeb + a_tag}' + "\n")
                        except:
                            filename = "esta agora.txt"
                            with open(filename, "a") as f:
                                    f.write(f'erro no link do carro que esta agora link {carrosNaWeb + a_tag}' + "\n")
                            pass

                element = doc.find("b", string="Próxima")
                if element is not None:
                    print('tem mais que 10')
                    parent_element = element.parent
                    link_real = parent_element.get('href')
                    link_completo = carrosNaWeb + link_real
                    try:
                        while True:
                            driver.get(link_completo)
                            time.sleep(10)
                            url_atual = driver.current_url
                            if url_atual == 'https://www.carrosnaweb.com.br/erro.asp':
                                reiniciar_proxy()
                                time.sleep(20)
                            else:
                                break
                    except TimeoutException:
                        print("reiniciando pagina")
                        reiniciar_pagina(driver)
                        time.sleep(20)
                else:
                    print('Não tem mais')
                    break
        except:
            filename = "esta agora.txt"
            with open(filename, "a") as f:
                f.write(f'Erro' + "\n")
            pass

print("ELE FUNCIONOU CARALHO HUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU")


import uwwwauth

# Example from https://tools.ietf.org/html/rfc2617#section-2

headers = {"WWW-Authenticate": 'Basic realm="WallyWorld"'}
auth_req = uwwwauth.parse_auth_req(headers["WWW-Authenticate"])
print(auth_req)
assert auth_req == {'realm': 'WallyWorld', 'type': 'Basic'}

resp = uwwwauth.basic_resp("Aladdin", "open sesame")
print(repr(resp))
assert resp == "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

resp = uwwwauth.auth_resp(headers["WWW-Authenticate"], "Aladdin", "open sesame")
assert resp == "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

auther = uwwwauth.WWWAuth("Aladdin", "open sesame")
resp = auther.resp(headers["WWW-Authenticate"], "GET", "/foo/bar")
assert resp == "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

# Example from https://tools.ietf.org/html/rfc2069#section-2.4, with errata in
# https://www.rfc-editor.org/errata_search.php?rfc=2069

headers = {"WWW-Authenticate": 'Digest    realm="testrealm@host.com", ' \
    'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", ' \
    'opaque="5ccc069c403ebaf9f0171e9517f40e41"'}

auth_req = uwwwauth.parse_auth_req(headers["WWW-Authenticate"])
print(auth_req)

assert auth_req == {
    'type': 'Digest',
    'nonce': 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
    'realm': 'testrealm@host.com',
    'opaque': '5ccc069c403ebaf9f0171e9517f40e41'
}

resp = uwwwauth.auth_resp(headers["WWW-Authenticate"], "Mufasa", "CircleOfLife", "GET", "/dir/index.html")
assert 'response="1949323746fe6a43ef61f9606e7febea"' in resp

auther = uwwwauth.WWWAuth("Mufasa", "CircleOfLife")
resp = auther.resp(headers["WWW-Authenticate"], "GET", "/dir/index.html")
print(resp)
assert 'response="1949323746fe6a43ef61f9606e7febea"' in resp

try:
    resp = auther.resp("foo", "GET", "/dir/index.html")
    assert False
except ValueError:
    pass


#!/usr/bin/env python3

# We are an import and import company
import sys

# Variable Setup
count = 0  # initial card count
elevens = 0  # counter, for aces counting as 11 in hand

# Prints the player's current hand, the total value, and the running count

def gui(cards, total, count):
    print(f"Player Hand: {cards}")
    print(f"Current card value: {total}")
    print(f"Current deck count: {count}")

# Convert face cards to their integer value, uses the current total to prevent aces from busting you

def faceSum(card, total, elevens):
    card_sum = 0
    if card in ['J', 'Q', 'K']:
        card_sum = 10
    elif card == 'A':
        if total + 11 > 21:
            card_sum = 1
        else:
            card_sum = 11
            elevens += 1
    else:
        card_sum = int(card)
    total += card_sum
    return total, elevens

# Checks and modifies the running count, using the Hi-Lo System

def hilo_counter(card, count):
    try:
        thisCard = int(card)
        if thisCard <= 6:
            count += 1
        elif thisCard <= 9:
            count += 0
    except:
        if card in [10, 'J', 'Q', 'K', 'A']:
            count += -1
    return count

# If ph_total is over 21, check to see if any aces in hand are 11s, and if so, switches it to a 1

def ace_bust_check(ph_total, elevens):
    if elevens > 0:
        ph_total += -10
        elevens += -1
    return ph_total, elevens

# Asks if you want to hit or stand

def player_action(player_hand, ph_total, elevens):
    while True:
        q = input("(H)it/(S)tand/(Q)uit?: ")
        q = q.lower()
        if q == "h":
            break
        if q == "s":
            player_hand = 0
            ph_total = 0
            elevens = 0
        elif q == "q":
            print("Exit through the gift shop")
            sys.exit()
    return player_hand, ph_total, elevens

# Message if run directly
if __name__ == "__main__":
    print("This file contains basic blackjack functions")
    sys.exit()


#!/usr/bin/env python

from setuptools import find_packages, setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

requirements = ['scitools-iris', 'numpy', 'scipy', 'matplotlib', 'metpy']

setup_requirements = []

test_requirements = []

setup(
    author="Leo Saffin",
    author_email='string_buster@hotmail.com',
    classifiers=[
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 2 - Pre-Alpha',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python",
        'Programming Language :: Python :: 3',
        'Topic :: Scientific/Engineering :: Atmospheric Science'],
    description="Scripts for work.",
    install_requires=requirements,
    license="MIT license",
    long_description=readme,
    include_package_data=True,
    keywords='',
    name='myscripts',
    packages=find_packages(include=['myscripts']),
    setup_requires=setup_requirements,
    test_suite='tests',
    tests_require=test_requirements,
    url='https://github.com/LSaffin/myscripts',
    version='0.2',
)