#---------------Examen Por Michael Morron---------------------------

#en el ejercicio no nos dieron valores fijos asi que use valores aleatorios...

import random
import math

# le digo al programa que quiero distancias aleatorias
def generate_random_points(num_points, min_val, max_val):
    points = []
    for _ in range(num_points):
        x = random.randint(min_val, max_val)
        y = random.randint(min_val, max_val)
        points.append((x, y))
    return points

def distance(p1, p2):
    return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)

def brute_force_closest_pair(points):
    min_distance = float('inf')
    closest_pair = None
    for i in range(len(points)):
        for j in range(i + 1, len(points)):
            dist = distance(points[i], points[j])
            if dist < min_distance:
                min_distance = dist
                closest_pair = (points[i], points[j])

    return closest_pair, min_distance

# divide y venceras :V (nombre raro para una funcion)
def divide_and_conquer_closest_pair(points):
    if len(points) <= 3:
        return brute_force_closest_pair(points)

    mid = len(points) // 2
    left_points = points[:mid]
    right_points = points[mid:]

    left_pair, left_distance = divide_and_conquer_closest_pair(left_points)
    right_pair, right_distance = divide_and_conquer_closest_pair(right_points)

    min_distance = min(left_distance, right_distance)
    min_pair = left_pair if left_distance < right_distance else right_pair

    strip_points = [point for point in points if abs(point[0] - points[mid][0]) < min_distance]
    strip_points.sort(key=lambda x: x[1])

    for i in range(len(strip_points)):
        j = i + 1
        while j < len(strip_points) and strip_points[j][1] - strip_points[i][1] < min_distance:
            dist = distance(strip_points[i], strip_points[j])
            if dist < min_distance:
                min_distance = dist
                min_pair = (strip_points[i], strip_points[j])
            j += 1

    return min_pair, min_distance

# aplicamos los args y kwargs
def measure_time(func):
    def wrapper(*args, **kwargs):
        import time
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Time taken: {end_time - start_time:.6f} seconds")
        return result
    return wrapper

# aqui esta la funcion de pares cercanos
def pares_cercanos(points):
    sorted_points = sorted(points, key=lambda x: x[0])
    closest_pair, distance = divide_and_conquer_closest_pair(sorted_points)
    return closest_pair, distance

# Generamos puntos aleatorios en cada ejecución
random.seed()
num_points = 10
min_val, max_val = 0, 20
points = generate_random_points(num_points, min_val, max_val)

# Mostramos los resultados
closest_pair, distance = pares_cercanos(points)
print("===================================================")
print(" || Puntos más cercanos:", closest_pair)
print(" || Distancia entre ellos:", distance)
print("===================================================")


from functools import cache
from matplotlib import pyplot as plt
from itertools import combinations
from joblib import Parallel, delayed

import json
import random
import os
import math
import numpy as np

# imports for Isaac's code
from filtered_constraints import filtered_constraints as fc, make_correct_rows as crows

auxdirpath = "/home/ikmarti/Desktop/ising-clustering/constraint-reduction/aux_arrays/"

def uniquify(path):
    filename, extension = os.path.splitext(path)
    counter = 1

    while os.path.exists(path):
        path = filename + " (" + str(counter) + ")" + extension
        counter += 1

    return path

def read_auxfile(filename):
    auxes = []
    with open(filename) as file:
        for line in file:
            auxes.append(json.loads(line)[0])

    return auxes

def sample_auxfile(filename, samples):
    auxes = []
    with open(filename) as file:
        for line in file:
            auxes.append(json.loads(line))

    return random.sample(auxes, k=samples)

def save_auxfile(auxes, filename):
    path = uniquify(auxdirpath + filename)
    with open(path, "w") as file:
        for aux in auxes:
            file.write(str(aux.tolist()) + "\n")

correct_rows_no_aux = {}

def pairs_to_and(N1, N2, pairs):
    try:
        correct = correct_rows_no_aux[(N1, N2)]
    except KeyError:
        correct_rows_no_aux[(N1, N2)] = crows(N1, N2, None)
        correct = correct_rows_no_aux[(N1, N2)]

    aux_vecs = np.concatenate(
        [np.expand_dims(np.prod(correct[..., key], axis=-1), axis=0) for key in pairs]
    ).astype(np.int8)
    return aux_vecs

def and_aux_generator(N1, N2, A, numsamples=10000):
    filename = f"IMul{N1}x{N2}x{A}_AND_AUX.dat"
    N = N1 + N2
    correct = crows(N1, N2, None)
    correct = correct.numpy()

    tups = set(
        {
            tuple(random.sample(list(combinations(list(range(N)), r=2)), k=A))
            for _ in range(numsamples)
        }
    )
    auxes = []
    for tup in tups:
        aux_vecs = np.concatenate(
            [np.expand_dims(np.prod(correct[..., key], axis=-1), axis=0) for key in tup]
        ).astype(np.int8)
        auxes.append(aux_vecs)

    save_auxfile(auxes, filename)

if __name__ == "__main__":
    N1 = 4
    N2 = 3
    M = N1 + N2
    G = N1 + N2 + M
    maxA = 20
    for A in range(1, maxA + 1):
        numsamples = min(math.comb(math.comb(G, 2), A), 100000)
        and_aux_generator(N1, N2, A, numsamples)
        print(f"Finished IMul{N1}x{N2}x{A}")


__author__ = 'Const'

import numpy as np

from scipy.linalg import lu

# An alternative to MATLAB '/' matrix operation
def rmatdiv(B, A):
    assert A.shape[1] == B.shape[1]
    z = np.linalg.lstsq(A.T, B.T)[0].T
    return z

def maxvol(A, max_iters=100, eps=5e-2):
    n, r = A.shape
    if n <= r:
        return np.array(xrange(n))

    perm, _, _ = lu(A)
    permutation_vector = perm.T.nonzero()[1].copy()
    ind = permutation_vector[:r]
    B = A[permutation_vector, :]
    submatrix = A[ind, :]
    z = rmatdiv(B[r:, :], submatrix)

    iter = 0
    while iter <= max_iters:
        max_indices = np.argmax(abs(z), axis=1)
        max_values = abs(z)[range(z.shape[0]), max_indices]
        max_arg = np.argmax(max_values)
        max_val = max_values[max_arg]
        if max_val <= 1 + eps:
            ind = np.sort(ind)
            return ind
        i_row = max_arg
        j_row = max_indices[i_row]
        permutation_vector[i_row + r], permutation_vector[j_row] =  \
                permutation_vector[j_row], permutation_vector[i_row + r]
        bb = z[:, j_row]
        bb[i_row] += 1
        cc = z[i_row, :]
        cc[j_row] -= 1
        #print z.shape, bb.shape, cc.shape
        z -= np.outer(bb, cc) / z[i_row, j_row]
        iter += 1
        ind = permutation_vector[:r]
        ind = np.sort(ind)
    return ind


from django import forms
from django.contrib.admin import register, ModelAdmin
from django.urls import path, reverse
from django.utils.html import format_html
from django_mptt_admin.admin import DjangoMpttAdmin
from leaflet.admin import LeafletGeoAdmin
import logging
from reversion.admin import VersionAdmin
from threading import Thread
import time

from .models import DepartmentUser, Location, OrgUnit, CostCentre
from .views import DepartmentUserExport, DepartmentUserDiscrepancyReport

LOGGER = logging.getLogger('sync_tasks')

def delayed_save(obj):
    """Wait one second, then call save() for the passed-in object.
    """
    time.sleep(1)
    obj.save()

class DepartmentUserForm(forms.ModelForm):

    class Meta:
        model = DepartmentUser
        exclude = []

    def clean_ad_guid(self):
        return self.cleaned_data['ad_guid'] or None

    def clean_employee_id(self):
        if self.cleaned_data['employee_id'] == '':
            return None
        else:
            return self.cleaned_data['employee_id']

@register(DepartmentUser)
class DepartmentUserAdmin(VersionAdmin):
    # Override the default reversion/change_list.html template:
    change_list_template = 'admin/organisation/departmentuser/change_list.html'
    form = DepartmentUserForm
    list_display = [
        'email', 'title', 'employee_id', 'username', 'active', 'vip', 'executive',
        'cost_centre', 'account_type', 'o365_licence']
    list_filter = [
        'account_type', 'active', 'vip', 'executive', 'shared_account',
        'o365_licence']
    search_fields = ['name', 'email', 'username', 'employee_id', 'preferred_name']
    raw_id_fields = ['parent', 'cost_centre', 'org_unit']
    filter_horizontal = ['secondary_locations']
    readonly_fields = [
        'username', 'org_data_pretty', 'ad_data_pretty',
        'active', 'in_sync', 'ad_deleted', 'date_ad_updated',
        'alesco_data_pretty', 'o365_licence', 'shared_account', 'date_hr_term']
    fieldsets = (
        ('Email/username', {
            'fields': ('email', 'username'),
        }),
        ('Name and organisational fields', {
            'description': '''
Do not edit information in this section
            without written permission from People Services or the cost centre manager
            (forms are required).
''',
            'fields': (
                'given_name', 'surname', 'name', 'employee_id', 'cost_centre',
                'org_unit', 'location', 'parent', 'security_clearance', 'name_update_reference'),
        }),
        ('Account fields', {
            'fields': ('account_type', 'expiry_date', 'date_hr_term', 'hr_auto_expiry', 'contractor', 'notes'),
        }),
        ('Other details', {
            'fields': (
                'vip', 'executive', 'populate_primary_group',
                'preferred_name', 'photo', 'title', 'position_type',
                'telephone', 'mobile_phone', 'extension', 'other_phone',
                'secondary_locations', 'working_hours', 'extra_data',
            )
        }),
        ('AD sync and HR data', {
            'fields': (
                'ad_guid',
                'ad_dn',
                'azure_guid',
                'active', 'in_sync', 'ad_deleted', 'date_ad_updated',
                'o365_licence', 'shared_account',
                'org_data_pretty', 'ad_data_pretty', 'alesco_data_pretty',
            )
        })
    )

    def save_model(self, request, obj, form, change):
        """Override save_model in order to log any changes to some fields:
        'given_name', 'surname', 'employee_id', 'cost_centre', 'name', 'org_unit', 'photo'
        """
        l = 'DepartmentUser: {}, field: {}, original_value: {} new_value: {}, changed_by: {}, reference: {}'
        if obj._DepartmentUser__original_given_name != obj.given_name:
            LOGGER.info(l.format(
                obj.email, 'given_name', obj._DepartmentUser__original_given_name, obj.given_name,
                request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_surname != obj.surname:
            LOGGER.info(l.format(
                obj.email, 'surname', obj._DepartmentUser__original_surname, obj.surname,
                request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_employee_id != obj.employee_id:
            LOGGER.info(l.format(
                obj.email, 'employee_id', obj._DepartmentUser__original_employee_id,
                obj.employee_id, request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_cost_centre_id != obj.cost_centre_id:
            LOGGER.info(l.format(
                obj.email, 'cost_centre', CostCentre.objects.filter(id=obj._DepartmentUser__original_cost_centre_id).first(),
                obj.cost_centre, request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_name != obj.name:
            LOGGER.info(l.format(
                obj.email, 'name', obj._DepartmentUser__original_name, obj.name,
                request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_org_unit_id != obj.org_unit_id:
            LOGGER.info(l.format(
                obj.email, 'org_unit', OrgUnit.objects.filter(id=obj._DepartmentUser__original_org_unit_id).first(), obj.org_unit,
                request.user.username, obj.name_update_reference
            ))
        if obj._DepartmentUser__original_expiry_date != obj.expiry_date:
            LOGGER.info(l.format(
                obj.email, 'expiry_date', obj._DepartmentUser__original_expiry_date, obj.expiry_date,
                request.user.username, obj.name_update_reference
            ))
        # Shrink photo for AD, if it changed.
        if obj._DepartmentUser__original_photo != obj.photo:
            LOGGER.info(l.format(
                obj.email, 'photo', obj._DepartmentUser__original_photo, obj.photo,
                request.user.username, obj.name_update_reference
            ))
            obj.update_photo_ad()

        obj.save()

        # NOTE: following a change to a DepartmentUser object, we need to call
        # save a second time so that the org_data field is correct. The lines
        # below will do so in a separate thread.
        t = Thread(target=delayed_save, args=(obj,))
        t.start()

    def get_urls(self):
        urls = super(DepartmentUserAdmin, self).get_urls()
        urls = [
            path('export/', DepartmentUserExport.as_view(), name='departmentuser_export'),
            path('departmentuser-discrepancy-report/', DepartmentUserDiscrepancyReport.as_view(), name='departmentuser_discrepancy_report'),
        ] + urls
        return urls

@register(Location)
class LocationAdmin(LeafletGeoAdmin):
    list_display = ('name', 'address', 'phone', 'fax', 'email', 'manager')
    list_filter = ('active',)
    raw_id_fields = ('manager',)
    search_fields = ('name', 'address', 'phone', 'fax', 'email', 'manager__email')
    settings_overrides = {
        'DEFAULT_CENTER': (-31.0, 115.0),
        'DEFAULT_ZOOM': 5
    }

@register(OrgUnit)
class OrgUnitAdmin(DjangoMpttAdmin):
    tree_auto_open = True
    tree_load_on_demand = False
    list_display = (
        'name', 'unit_type', 'users', 'members', 'it_systems', 'cc', 'acronym',
        'manager')
    search_fields = ('name', 'acronym', 'manager__name', 'location__name')
    raw_id_fields = ('manager', 'parent', 'location')
    list_filter = ('unit_type', 'active')

    def users(self, obj):
        from organisation.models import DepartmentUser
        dusers = obj.departmentuser_set.filter(**DepartmentUser.ACTIVE_FILTER)
        return format_html(
            '{}',
            reverse('admin:organisation_departmentuser_changelist'),
            obj.pk, dusers.count())

    def members(self, obj):
        return format_html(
            '{}',
            reverse('admin:organisation_departmentuser_changelist'),
            ','.join([str(o.pk)
                      for o in obj.get_descendants(include_self=True)]),
            obj.members().count()
        )

    def it_systems(self, obj):
        return format_html(
            '{}',
            reverse('admin:registers_itsystem_changelist'),
            obj.pk, obj.itsystem_set.count())

@register(CostCentre)
class CostCentreAdmin(ModelAdmin):
    list_display = (
        'name', 'code', 'chart_acct_name', 'org_position', 'division', 'users', 'manager',
        'business_manager', 'admin', 'tech_contact', 'active')
    search_fields = (
        'name', 'code', 'chart_acct_name', 'org_position__name', 'division__name',
        'org_position__acronym', 'division__acronym')
    list_filter = ('active', 'chart_acct_name')
    raw_id_fields = (
        'org_position', 'manager', 'business_manager', 'admin', 'tech_contact')

    def users(self, obj):
        return format_html(
            '{}',
            reverse('admin:organisation_departmentuser_changelist'),
            obj.pk, obj.departmentuser_set.count())


from mysql.connector import ProgrammingError
from db import nova_conexao

sql = 'INSERT INTO contatos (nome, tel) VALUES (%s, %s)'
args = (
    ('Luka', '4678-4412'),
    ('xDxD', '1010-3231'),
    ('Soph', '7764-1113'),
    ('May', '1121-5643'),
    ('Breo', '2341-4083'),
    ('Jeej', '1111-2222'),
)

with nova_conexao() as conexao:
    try:
        cursor = conexao.cursor()
        cursor.executemany(sql, args)
        conexao.commit()
    except ProgrammingError as e:
        print(f'Error: {e.msg}')
    else:
        print(f'{cursor.rowcount} registros incluidos')


def magick(reg, s):
    res = []
    k = len(reg)
    for i in range(len(s)-len(reg)+1):
        if s[i:i+k] == reg:
            res.append(i)
    if len(res) == 0:
        return [-1]
    return res
print(*magick(input(), input()))


import collections, copy
Card = collections.namedtuple('Card',['rank','suit'])

class Deck(object):

	def __int__(self):

		''' Initializes a deck of cards.'''

		ranks = [str(n) for n in range(2,11)] + list('JQKA')
		suits = 'spades diamonds clubs hearts'.split()

		self._cards = [Card(rank,suit) for rank in ranks for suit in suits]

	def __len__(self):
		return len(self._cards)

	def __getitem__(self, key):
		return self._cards[key]

	def flipBackSequence(self, deck = None):

		''' returns the sequence of cards, in order, if you drew the top card, put the next card at the back of the deck,
		and then repeated until only one card remained (in which case it would be returned.)'''

		if deck == None:
			deck = copy.deepcopy(self)

		if len(deck) == 1: # only one item left in the deck:
			return [deck[0]]

		else:
			topCard, secondCard = deck[0:2]

			deck = deck[1:]

			deck.insert(len(deck) + 1, secondCard)

			return [topCard] + flipBackSequence(self, deck)


import csv

def csv_add_rows(filename, data, fieldnames, write_fieldnames=False, mode='a'):

    if write_fieldnames:
        with open(filename, 'w') as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=';')
            writer.writeheader()

    with open(filename, mode) as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=';')
        for row in data:
            writer.writerow(row)


import time
import math
import operator

from PIL import Image
from functools import reduce
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from Utils.YamlMethod import XiaoMaUtils
from Base.InitDriver import init_driver

class Base(object):
    def __init__(self, phone_name):

        self.driver = init_driver(phone_name)
        self.window_size = self.driver.get_window_size()

    def find_element_o(self, loc, timeout=30, poll=0.5):
        """
        根据定位获取单个元素

        :param loc: 元素的表达形式, 以元祖形式传递, eg. (By.ID,ID属性值)
        :param timeout: 等待时长
        :param poll: 查询频率
        :return: 定位对象
        """
        return WebDriverWait(self.driver, timeout, poll).until(lambda x: x.find_element(*loc))

    def find_elements_o(self, loc, timeout=20, poll=0.5):
        """
        根据定位获取一组元素

        :param loc: 元素的表达形式, 以元祖形式传递, eg. (By.ID,ID属性值)
        :param timeout: 等待时长
        :param poll: 查询频率
        :return: 一组定位对象
        """
        return WebDriverWait(self.driver, timeout, poll).until(lambda x: x.find_element(*loc))

    def click_element(self, loc):
        """
        点击操作

        :param loc: 元素的表达形式, 以元祖形式传递, eg. (By.ID,ID属性值)
        :return: None
        """
        self.find_element_o(loc).click()

    def long_press_element(self, ele, duration=2000):
        """
        长按操作

        :param ele: 要长按的对象
        :param duration: 长按时长, 默认为2000ms
        :return: None
        """
        TouchAction(self.driver).long_press(el=ele, duration=duration)

    def get_ele_text(self, ele):
        """
        获取元素的文本值

        :param ele: 元素对象
        :return: str
        """
        return self.get_element_attribute(ele, 'text')

    def get_ele_bounds(self, ele):
        """
        获取元素的边界

        :param ele: 元素对象
        :return: str, 形式如: [x1,y1][x2,y2]
        """
        return self.get_element_attribute(ele, 'bounds')

    def input_text(self, loc, text):
        """
        输入操作

        :param loc: 元素的表达形式, 以元祖形式传递, eg. (By.ID,ID属性值)
        :param text: 输入的内容
        :return:
        """
        ele = self.find_element_o(loc)
        ele.clear()
        ele.send_keys(text)

    def is_display(self, loc):
        """
        判断元素是否存在, 存在返回True, 不存在返回False

        :param loc: 元素的表达形式, 以元祖形式传递, eg. (By.ID,ID属性值)
        :return: bool
        """

        try:
            self.find_element_o(loc, timeout=10)
            return True
        except Exception as e:
            return False

    def getSize(self):
        resolution = self.driver.get_window_size()  # 获取手机分辨率
        resolution_width = resolution.get('width')   # 赋值手机分辨率-宽
        resolution_height = resolution.get('height') # 赋值手机分辨率-高
        return (resolution_width, resolution_height)

    # 根据相对坐标滑动，start_x：起始横坐标，start_y：起始纵坐标，end_x：结束时横坐标，end_y：结束时纵坐标，duration：滑动持续时间，单位毫秒，默认None（一般设置500-1000毫秒 0.5-1秒比较合适）
    def location_slide(self,start_x,start_y,end_x,end_y,duration=None):
        self.driver.swipe(start_x / 1080 * self.getSize()[0], start_y / 2211 * self.getSize()[1], end_x / 1080 * self.getSize()[0],end_y / 2211 * self.getSize()[1])

    def swipe_o(self, ele=None, location=None, direction='right', times=1):
        """
        根据用户输入的方向和次数, 滑动屏幕
        :param ele: 需要滑动区域的元素
        :param location: 需滑动的位置, 元组形式, eg. (x1, x2, y1, y2)
        :param direction: 滑动方向, 可选参数['up', 'down', 'left', 'right']
        :param times: 滑动次数
        :return: None
        """

        # 根据传入的元素解析滑动区域
        if ele:
            x1, y1, x2, y2 = XiaoMaUtils.convert_bounds_to_location(self.get_ele_bounds(ele))
        # 根据传入的坐标值解析滑动区域
        elif location:
            x1, x2, y1, y2 = location
        # 根据屏幕解析滑动区域
        else:
            width = self.window_size['width']
            length = self.window_size['height']
            x1 = width * 0.25
            x2 = width * 0.75
            y1 = length * 0.25
            y2 = length * 0.75

        # 循环滑动
        for i in range(times):
            if direction == 'up':
                self.driver.swipe(x1, y2, x1, y1)
            if direction == 'down':
                self.driver.swipe(x1, y1, x1, y2)
            if direction == 'right':
                self.driver.swipe(x1, y1, x2, y1)
            if direction == 'left':
                self.driver.swipe(x2, y1, x1, y1)
        time.sleep(2)

    def wait_activity_o(self, activity, timeout=10, interval=1):
        """
        等待activity加载完成

        :param activity: activity名称
        :param timeout: 等待时长
        :param interval: 循环查询时间, 默认每1s查询一次
        :return:
        """
        self.driver.wait_activity(activity, timeout, interval)

    def get_element_attribute(self, ele, attribute):
        """
        获取元素属性

        :param ele: 元素对象
        :param attribute: 属性名称
        :return: 元素属性值
        """
        if attribute == 'size':
            return ele.size
        else:
            return ele.get_attribute(attribute)

    def screenshot_part(self, element, img_name, bounds=None):
        """
            功能: 截图指定元素
            参数:
                :param element: 要获取的元素
                :param img_name: 要保存的名字
                :param bounds: 元素边界(对于无法定位到的元素, 可直接使用边界定位)
        """
        time.sleep(2)

        # 截取屏幕, 并打开该图像
        XiaoMaUtils.get_screencap()
        img = Image.open('Image/screen.png')

        if bounds:
            (x1, y1, x2, y2) = bounds
        else:
            # 获取待截取的元素的边界
            x1 = int(XiaoMaUtils.convert_bounds_to_location(self.get_element_attribute(element, 'bounds'))[0])
            y1 = int(XiaoMaUtils.convert_bounds_to_location(self.get_element_attribute(element, 'bounds'))[1])
            x2 = int(XiaoMaUtils.convert_bounds_to_location(self.get_element_attribute(element, 'bounds'))[2])
            y2 = int(XiaoMaUtils.convert_bounds_to_location(self.get_element_attribute(element, 'bounds'))[3])

        # 设置图像裁剪区域 (x左上，y左上，x右下,y右下)
        box1 = (x1, y1, x2, y2)

        # 图像裁剪
        image1 = img.crop(box1)

        # 存储裁剪得到的图像
        image1.save("Image/" + img_name + ".png")

    @staticmethod
    def image_contrast(img1="img1.png", img2="img2.png"):
        """
            功能: 比较两张图片的差异
            返回: 0.0表示是完全一致的图片, 数值越大, 图片的差异越大
        """
        image1 = Image.open("Image/" + img1)
        image2 = Image.open("Image/" + img2)

        h1 = image1.histogram()
        h2 = image2.histogram()

        result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))

        return result


#Program to convert a color image to grayscale image

from skimage import color, io

#Read an image from a file
img = io.imread('image.png')

#Convert the image tp grayscale
hsv_image = color.rgb2hsv(img)

io.imshow(hsv_image)
io.show()


#python class that calls c functions to handle compression/decompression

import sz_class
import numpy as np

class py_sz_class:
    #constructor
    def __init__(self, szCfg, errBoundMode, compType, errBound=1e-5, numVars=10):
        #print("constructor called!")
        #if self.init = 0
        self.dim = [0,0,0,0,0];
        self.errBoundMode = errBoundMode;
        #self.errBound = errBound;
        self.compType = compType;
        self.szCfg = szCfg;
        self.numVectors = 0;
        sz_class.sz_constructor(szCfg, numVars);
        #self.init = 1

    #destructor
    def __del__(self):
        sz_class.sz_destructor();

    #numVectors is M
    def registerVar(self, varName, shape, dtype=np.float64, numVectors=100):
        self.numVectors = numVectors;
        d1 = shape[0]; d2 = 0; d3 = 0; d4 = 0; d5 = 0;
        l = len(shape);

        if l == 2:
            d2 = shape[1];
        if l == 3:
            d2 = shape[1]; d3 = shape[2];
        if l == 4:
            d2 = shape[1]; d3 = shape[2]; d4 = shape[3];
        if l == 5:
            d2 = shape[1]; d3 = shape[3]; d4 = shape[3]; d2 = shape[4];

        #print(d1,d2,d3,d4,d5);
        self.dim=(d1,d2,d3,d4,d5);
        sz_class.sz_registerVar(varName, numVectors, d5, d4, d3, d2, d1);

    def compress(self, data, varName, index, errBoundMode=0, errBound=1e-5, compType=0):
        #decide which errBoundMode to use: 0=ABS, 1=REL, 2=PW_REL...
        #last arg of sz_comp is compType, 0=std sz, 1=temporal sz, 2=truncation, 3=zfp
        data = np.ravel(data);
        #print(len(data))
        sz_class.sz_comp(data, varName, index, 0, errBound, compType);

    def decompress(self, varName, index, compType=0):
        #must use dimensions for output array size and reshaping
        if self.dim[1] == 0:
            data = sz_class.sz_decomp(self.dim[0], varName, index, compType);
        elif self.dim[2] == 0:
            data = sz_class.sz_decomp(self.dim[0]*self.dim[1], varName, index, compType);
            data = np.reshape((self.dim[0], self.dim[1]));
        elif self.dim[3] == 0:
            data = sz_class.sz_decomp(self.dim[0]*self.dim[1]*self.dim[2], varName, index, compType);
            data = np.reshape((self.dim[0], self.dim[1], self.dim[2]));
        elif self.dim[4] == 0:
            data = sz_class.sz_decomp(self.dim[0]*self.dim[1]*self.dim[2]*self.dim[3], varName, index, compType);
            data = np.reshape((self.dim[0], self.dim[1], self.dim[2], self.dim[3]));
        else:
            data = sz_class.sz_decomp(self.dim[0]*self.dim[1]*self.dim[2]*self.dim[3]*self.dim[4], varName, index, compType);
            data = np.reshape((self.dim[0], self.dim[1], self.dim[2], self.dim[3], self.dim[4]));

        return data;

    def printStats(self, varName):
        print(" ")  #for readability
        sz_class.sz_printVarInfo(varName);

    def getStats(self, varName):
        #stats print in sets of 3: compRatio, compTime, decompTime for each vector in M
        stats = sz_class.sz_getStats(self.numVectors * 3, varName);
        return stats;

#declare global instance of memory
memory=py_sz_class("sz.config", "ABS", "STD");


# 신고 결과 받기

# 딕셔너리 활용해서 구현한 문제

# 시도
# def solution(id_list, reports, k):
#     answer = []

#     declare_cnt = {n:0 for n in id_list}
#     declare_group = {n:[] for n in id_list}
#     id_check = []

#     for report in reports:
#         id, declare_id = report.split()
#         declare_group[id].append(declare_id)
#         # 한 id가 같은 declare_id를 신고한 경우 횟수는 1회만 증가
#         if (id, declare_id) not in id_check:
#             declare_cnt[declare_id] += 1 # 신고횟수 증가
#             id_check.append((id, declare_id))

#     print(declare_cnt)

#     return answer

def solution(id_list, reports, k):
    # 중복 없이 각 신고 당한 id 그룹을 담을 딕셔너리
    report_group = {ID:set() for ID in id_list}

    # reports 에서 뽑은 report에서 신고한 id, 신고당한 id 분리
    for report in reports:
        u, r = report.split()
        report_group[r].add(u) # report에 id를 신고한 id를 담는다.

    # 신고를 성공한 횟수 카운트 딕셔너리
    success = {ID:0 for ID in id_list}

    # 순서대로 id에 메일을 보내기 때문에 id_list에서 바로 id를 뽑는다.
    for id in id_list:
        # k 이상만 유효
        if k <= len(report_group[id]):
            for reporter in report_group[id]: # 신고한 그룹의 신고자를 뽑아서
                success[reporter] += 1 # 그 신고자에게 보낼 메일 cnt 증가

    # print(report_group)

    # print(success)

    answer = list(success.values()) # list 변환

    return answer

print(solution(["muzi", "frodo", "apeach", "neo"], ["muzi frodo","apeach frodo","frodo neo","muzi neo","apeach muzi"], 2)) # result [2, 1, 1, 0]
print(solution(["con", "ryan"], ["ryan con", "ryan con", "ryan con", "ryan con"], 3)) # result [0,0]


# -*- coding: utf-8 -*-
from pathlib import Path
import logging
from sqlalchemy.orm import sessionmaker
from scrapy.exceptions import DropItem
from database.models import Movie, MoviePoster, Director, Producer, Star, db_connect, create_table

class WikipediaScraperPipeline(object):
    def __init__(self):
        logging.info('Remove existing database.')
        path = Path('./database/movies.db')
        if path.exists():
            path.unlink()

        engine = db_connect()
        create_table(engine)
        self.Session = sessionmaker(bind=engine)

    def process_item(self, item, spider):
        session = self.Session()
        movie = Movie()
        movie_poster = MoviePoster(movie=movie)

        movie.name = item['name']
        movie.year = item['year']
        movie.awards = item['awards']
        movie.nominations = item['nominations']

        if 'image' in item and item['image']:
            movie_poster.src = item['image']['src']
            movie_poster.alt_text = item['image']['alt_text']
            movie.image = movie_poster

        persons = [{
            'item_key': 'directed_by',
            'model': Director,
            'movie_key': 'directors'
        },{
            'item_key': 'produced_by',
            'model': Producer,
            'movie_key': 'producers'
        },{
            'item_key': 'starring',
            'model': Star,
            'movie_key': 'stars'
        }]

        for person_data in persons:
            if person_data['item_key'] in item:
                for person in item[person_data['item_key']]:
                    person_exists = session.query(person_data['model']).filter_by(name = person).first()
                    if person_exists is not None:
                        getattr(movie, person_data['movie_key']).append(person_exists)
                    else:
                        getattr(movie, person_data['movie_key']).append(person_data['model'](name= person))

        try:
            session.add(movie)
            session.commit()

        except:
            session.rollback()
            raise

        finally:
            session.close()

        return item


import argparse
import cv2

ap=argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help='Path to the image')
args=vars(ap.parse_args())

image=cv2.imread(args["image"])
print("width: %d pixels" % (image.shape[1])) #goruntunun boyutlarini inceler
print("height: %d pixels" % (image.shape[0]))#bu incelemeyi shape ile yapar
print("channels: %d" % (image.shape[2]))

cv2.imshow("image",image)
cv2.waitKey(0)
cv2.imwrite("newimage.jpg",image)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Description:
# @PreInstall:
# @Author : claer
# @File : time_util.py
# @Version: 1.0.0
# @Time : 2019/9/25 18:49
# @Project: scripts_python
# @Package:
# @Software: PyCharm
import datetime
import time

def get_every_day(begin_date, end_date):
    """
    获取两个日期间的所有日期
    :param begin_date:
    :param end_date:
    :return:
    """
    date_list = []
    begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    while begin_date <= end_date:
        date_str = begin_date.strftime("%Y-%m-%d")
        date_list.append(date_str)
        begin_date += datetime.timedelta(days=1)
    return date_list

def date_compare_to(begin_date, end_date):
    """
    比较两个日期大小
    :param begin_date:
    :param end_date:
    :return: 返回0为相等，1为begin比end大，-1为begin比end小
    """
    begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    if begin_date == end_date:
        return 0
    elif begin_date < end_date:
        return -1
    else:
        return 1

def time_compare_to(begin_time, end_time):
    """
    比较两个时间大小
    :param begin_time:
    :param end_time:
    :return: 返回0为相等，1为begin比end大，-1为begin比end小
    """
    begin_time = time.strftime("%Y-%m-%d-%H_%M_%S", begin_time)
    end_time = time.strftime("%Y-%m-%d-%H_%M_%S", end_time)
    if begin_time == end_time:
        return 0
    elif begin_time < end_time:
        return -1
    else:
        return 1


#Apresentar os resultados das potências de 3, variando do expoente 0 até o expoente 15. Deve ser
#considerado que qualquer número elevado a zero é 1, e elevado a 1 é ele próprio. Observe que
#neste exercício não pode ser utilizado o operador de exponenciação

contadora = 1
acumuladora = 1

print('O número 3 elevado a 0 é igual a 1')

while contadora <= 15:
    acumuladora = acumuladora * 3
    print('O número 3 elevado a', contadora, 'é igual a:', acumuladora)
    contadora = contadora + 1


import sys
import os
import yaml
import re
import urllib.request

DEBUG_FLAG = True

class label_configure:
    def is_url(self, path: str) -> bool:
        pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
        if re.match(pattern, path):
            return True
        else:
            return False

    def __init__(self, yaml_abs_path: str, target_key: str) -> None:
        self.stylesheet_str = str()
        self.yaml_abs_path_file = yaml_abs_path
        self.target_key = target_key

        self.debug = DEBUG_FLAG

        with open(self.yaml_abs_path_file, 'r') as f:
            self.yaml_data = yaml.load(f, Loader=yaml.FullLoader)
        # exit when no yaml data
        if self.yaml_data is None:
            print("no yaml data")
            sys.exit()
        self.yaml_data = self.yaml_data[self.target_key]

    # include yaml from yaml ---------------------------------------------------
        if "include" in self.yaml_data:
            path = self.yaml_data["include"]["path"]
            key = self.yaml_data["include"]["key"]
            # is url or path
            if self.is_url(path):
                # is url -> save to ~/.cache/pyamlqt/yaml/***.yaml and load it
                # exists ~/.cache/pyamlqt/yaml/***.yaml ?
                if not os.path.exists(os.path.expanduser("~/.cache/pyamlqt/yaml/" + os.path.basename(path))):
                    os.makedirs(os.path.expanduser(
                        "~/.cache/pyamlqt/yaml"), exist_ok=True)
                    urllib.request.urlretrieve(path, os.path.expanduser(
                        "~/.cache/pyamlqt/yaml/") + os.path.basename(path))
                    print("download yaml file: " + path)
                else:
                    print("yaml file is already downloaded (Please delete ~/.cache/pyamlqt/yaml/" +
                          os.path.basename(path) + " to download again)")
                path = os.path.expanduser(
                    "~/.cache/pyamlqt/yaml/") + os.path.basename(path)

            with open(path, 'r') as f:
                self.yaml_data = yaml.load(f, Loader=yaml.FullLoader)
            self.yaml_data = label_configure(path, key).yaml_data
            print("yaml_data: " + str(self.yaml_data))
            # return force
            return

    # Using common tag --------------------------------------------------------

        if "type" in self.yaml_data:
            self.type = self.yaml_data["type"]
        else:
            print("type is undefined.")
            sys.exit()

        if "x_center" in self.yaml_data:
            self.x_center = self.yaml_data["x_center"]
        else:
            self.x_center = 0

        if "y_center" in self.yaml_data:
            self.y_center = self.yaml_data["y_center"]
        else:
            self.y_center = 0

        if "width" in self.yaml_data:
            self.width = self.yaml_data["width"]
        else:
            self.width = 50

        if "height" in self.yaml_data:
            self.height = self.yaml_data["height"]
        else:
            self.height = 50

        if "text" in self.yaml_data:
            self.text = self.yaml_data["text"]
        else:
            self.text = ""
        if "font_size" in self.yaml_data:
            self.font_size = self.yaml_data["font_size"]
        else:
            self.font_size = 10

        if "font_color" in self.yaml_data:
            self.font_color = self.yaml_data["font_color"]
        else:
            self.font_color = "#000000"

        if "background_color" in self.yaml_data:
            self.background_color = self.yaml_data["background_color"]
        else:
            self.background_color = ""

        if "font" in self.yaml_data:
            self.font = self.yaml_data["font"]
        else:
            self.font = "Arial"

        if "font_bold" in self.yaml_data:
            self.font_bold = self.yaml_data["font_bold"]
        else:
            self.font_bold = False

        if "items" in self.yaml_data:
            self.items = self.yaml_data["items"]
        else:
            self.items = []

        if "max" in self.yaml_data:
            self.max = self.yaml_data["max"]
        else:
            self.max = 100

        if "min" in self.yaml_data:
            self.min = self.yaml_data["min"]
        else:
            self.min = 0

        if "step" in self.yaml_data:
            self.step = self.yaml_data["step"]
        else:
            self.step = 1

        if "default" in self.yaml_data:
            self.default = self.yaml_data["default"]
        else:
            self.default = 0

        # if "path" in self.yaml_data:
        #     self.path = self.yaml_data["path"]
        #     if script_dir != "":
        #         self.path = script_dir + self.path
        #         self.path = os.path.abspath(self.path)
        # else:
        #     self.path = ""

    # StyleSheet ---------------------------------------------------------------
        if "style" in self.yaml_data:
            # if include key
            if "include" in self.yaml_data["style"]:
                path = self.yaml_data["style"]["include"]["path"]
                key = self.yaml_data["style"]["include"]["key"]
                # is url or path
                print("path: " + path)
                if self.is_url(path):
                    # is url -> save to ~/.cache/pyamlqt/yaml/***.yaml and load it
                    # exists ~/.cache/pyamlqt/yaml/***.yaml ?
                    if not os.path.exists(os.path.expanduser("~/.cache/pyamlqt/yaml/" + os.path.basename(path))):
                        os.makedirs(os.path.expanduser(
                            "~/.cache/pyamlqt/yaml"), exist_ok=True)
                        urllib.request.urlretrieve(path, os.path.expanduser(
                            "~/.cache/pyamlqt/yaml/") + os.path.basename(path))
                        print("download yaml file: " + path)
                    else:
                        print("yaml file is already downloaded (Please delete ~/.cache/pyamlqt/yaml/" +
                              os.path.basename(path) + " to download again)")
                    print("yaml_data: " + str(self.yaml_data))
                    path = os.path.expanduser(
                        "~/.cache/pyamlqt/yaml/") + os.path.basename(path)

                with open(path, 'r') as f:
                    self.stylesheet_str = yaml.load(f, Loader=yaml.FullLoader)
                self.stylesheet_str = label_configure(
                    path, key).stylesheet_str
                print("stylesheet_str: " + str(self.stylesheet_str))

            else:
                for key, value in self.yaml_data["style"].items():
                    # configure stylesheet
                    if (key == "background-image"):
                        # check path "./" or "../" ... (relative path)
                        # image_path : url(./image/back-image.png) -> ./image/back-image.png
                        image_path = value.replace("url(", "").replace(")", "")
                        if (image_path[0] == "." or image_path[0] == ".."):
                            basepath = os.path.dirname(self.yaml_abs_path_file)
                            image_path = os.path.join(basepath, image_path)
                            print("------------------")
                            print("image_path: " + image_path)
                            print("------------------")
                        self.stylesheet_str += key + ": url(" + image_path + ");"
                    else:
                        self.stylesheet_str += key + ": " + str(value) + "; "
        else:
            self.stylesheet_str = ""

    # Label Rect ---------------------------------------------------------------
        if "rect" in self.yaml_data:
            # if include key
            if "include" in self.yaml_data["rect"]:
                path = self.yaml_data["rect"]["include"]["path"]
                key = self.yaml_data["rect"]["include"]["key"]
                # is url or path
                if self.is_url(path):
                    # is url -> save to ~/.cache/pyamlqt/yaml/***.yaml and load it
                    # exists ~/.cache/pyamlqt/yaml/***.yaml ?
                    if not os.path.exists(os.path.expanduser("~/.cache/pyamlqt/yaml/" + os.path.basename(path))):
                        os.makedirs(os.path.expanduser(
                            "~/.cache/pyamlqt/yaml"), exist_ok=True)
                        urllib.request.urlretrieve(path, os.path.expanduser(
                            "~/.cache/pyamlqt/yaml/") + os.path.basename(path))
                        print("download yaml file: " + path)
                    else:
                        print("yaml file is already downloaded (Please delete ~/.cache/pyamlqt/yaml/" +
                              os.path.basename(path) + " to download again)")
                    path = os.path.expanduser(
                        "~/.cache/pyamlqt/yaml/") + os.path.basename(path)

                with open(path, 'r') as f:
                    self.rect_width = yaml.load(f, Loader=yaml.FullLoader)
                self.rect_width = label_configure(path, key).rect_width
                self.rect_height = label_configure(path, key).rect_height
            else:
                self.rect_width = self.yaml_data["rect"]["width"]
                self.rect_height = self.yaml_data["rect"]["height"]
        else:
            pass
            self.rect_width = self.width
            self.rect_height = self.height

        self.width = self.rect_width
        self.height = self.rect_height

    # debug ---------------------------------------------------------------
        if "debug" in self.yaml_data:
            self.debug = self.yaml_data["debug"]
        else:
            self.debug = False

        self.x = self.x_center - self.width // 2
        self.y = self.y_center - self.height // 2

        # print all
        if self.debug:
            print("==========================================================")
            print("loading " + self.yaml_abs_path_file)
            print("type:" + str(self.type))
            print("x_center: " + str(self.x_center))
            print("y_center: " + str(self.y_center))
            print("width: " + str(self.width))
            print("height: " + str(self.height))
            print("text: " + str(self.text))
            print("font_size: " + str(self.font_size))
            print("font_color: " + str(self.font_color))
            print("background_color: " + str(self.background_color))
            print("font: " + str(self.font))
            print("font_bold: " + str(self.font_bold))
            print("items: " + str(self.items))
            print("max: " + str(self.max))
            print("min: " + str(self.min))
            print("step: " + str(self.step))
            print("default: " + str(self.default))
            print("path: " + str(self.path))
            print("stylesheet_str: " + str(self.stylesheet_str))
            print("==========================================================")


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

"""Module for data simulation, geometrical resources.

Tong Zhang <zhangt@frib.msu.edu>
2017-03-27 11:29:39 AM EDT
"""

import numpy as np

EPS = np.finfo(float).eps

class Point(object):
    """Points in 2D Cartesian coordinate system, if invalid input is detected,
    return ``Point(x,y)``, ``x``, ``y`` is random number between 0 and 1.

    Initialization approaches:

    Examples
    --------
    The following ways are the same:

    >>> Point(x=1, y=2)
    >>> Point(1, y=2)
    >>> Point(1, 2)
    >>> Point((1, 2))
    >>> Point([1, 2])
    >>> Point(Point(1, 2))
    """
    __slot__ = ['_x', '_y']

    def __init__(self, x=None, y=None):
        self.point = (x, y)

    @property
    def x(self):
        """float: x coordinate."""
        return self._x

    @property
    def y(self):
        """float: y coordinate."""
        return self._y

    @x.setter
    def x(self, x):
        if isinstance(x, float):
            self._x = x
        elif isinstance(x, int):
            self._x = float(x)
        else:
            self._x = np.random.random()

    @y.setter
    def y(self, y):
        if isinstance(y, float):
            self._y = y
        elif isinstance(y, int):
            self._y = float(y)
        else:
            self._y = np.random.random()

    @property
    def point(self):
        """Array: x, y coordinate."""
        return np.array([self._x, self._y])

    @point.setter
    def point(self, p):
        x, y = p[0], p[1]
        # x is a list or tuple or array,
        # e.g. x = (1, 2); x = [1, 2]; x = np.array([1,2])
        if isinstance(x, (list, tuple)):
            self.x, self.y = x[0], x[1]
        elif isinstance(x, np.ndarray):  # np.int64 is not instance of int
            x = x.tolist()
            self.x, self.y = x[0], x[1]
        elif isinstance(x, Point):
            # x is Point
            self.x, self.y = x.point
        else:
            # two floats
            self.x, self.y = x, y

    def __eq__(self, other):
        return (self.x == other.x) and (self.y == other.y)

    def __add__(self, other):
        if isinstance(other, int):
            other = Point(0, 0)
        elif isinstance(other, (list, tuple, np.ndarray)):
            other = Point(other)
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)

    def __mul__(self, other):
        return Point(other * self.x, other * self.y)

    def __rmul__(self, other):
        return Point(other * self.x, other * self.y)

    def __truediv__(self, other):
        return Point(self.x / other, self.y / other)

    __div__ = __truediv__

    def __rtruediv__(self, other):
        return Point(self.x / other, self.y / other)

    def __radd__(self, other):
        if isinstance(other, int):
            other = Point(0, 0)
        elif isinstance(other, (list, tuple, np.ndarray)):
            other = Point(other)
        return Point(self.x + other.x, self.y + other.y)

    def __abs__(self):
        return self.distance_to_point((0, 0))

    def distance_to_point(self, p):
        """Distance to point ``p``.
        """
        return Point.calc_distance_to_point(self.point, p)

    def distance_to_line(self, a, b):
        """Distance to line built by point ``a`` and ``b``.
        """
        return Point.calc_distance_to_line(self.point, a, b)

    def proj_point(self, a, b):
        """Projected point to line built by point ``a`` and ``b``.
        """
        return Point.calc_proj_point(self.point, a, b)

    def is_in_line(self, a, b):
        """Test if point is in line built by ``a`` and ``b``.
        """
        return Point.test_is_in_line(self.point, a, b)

    @staticmethod
    def calc_proj_point(p, a, b):
        """Return projected point of ``p`` to line built by point ``a``
        and ``b``.

        Parameters
        ----------
        p : tuple, list or Point
            Point to be projected, could be array of ``(x, y)``, or ``Point()``
            instance.
        a : tuple, list or Point
        b : tuple, list or Point
            Two point to build a line that ``p`` projected on to.

        Returns
        -------
        ret : Point
            Projected point onto a line.
        """
        if isinstance(p, Point):
            p = p.point
        elif isinstance(p, (tuple, list, np.ndarray)):
            p = np.array(p)
        if isinstance(a, Point):
            a = a.point
        elif isinstance(a, (tuple, list, np.ndarray)):
            a = np.array(a)
        if isinstance(b, Point):
            b = b.point
        elif isinstance(b, (tuple, list, np.ndarray)):
            b = np.array(b)
        return Point(a + np.dot(p - a, b - a) / np.dot(b - a, b - a) * (b - a))

    @staticmethod
    def calc_distance_to_point(a, b):
        """Calculate distance between two points ``a`` and ``b``.

        Parameters
        ----------
        a : tuple, list or Point
            ``(x,y)`` coordinate to represent a point.
        b : tuple, list or Point
            ``(x,y)`` coordinate to represent a point.

        Returns
        -------
        ret: float
            Distance between two points.
        """
        return np.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)

    @staticmethod
    def calc_distance_to_line(p, a, b):
        """Distance from point ``p`` to line built by point ``a`` and
        ``b``.

        Parameters
        ----------
        p : tuple, list or Point
            Point out of a line, could be array of ``(x, y)``, or ``Point()``
            instance.
        a : tuple, list or Point
        b : tuple, list or Point
            Two point to build a line.

        Returns
        -------
        ret : float
            Distance from ``p`` to line built by ``a`` and ``b``.
        """
        if isinstance(p, Point):
            p = p.point
        elif isinstance(p, (tuple, list, np.ndarray)):
            p = np.array(p)
        if isinstance(a, Point):
            a = a.point
        elif isinstance(a, (tuple, list, np.ndarray)):
            a = np.array(a)
        if isinstance(b, Point):
            b = b.point
        elif isinstance(b, (tuple, list, np.ndarray)):
            b = np.array(b)
        return abs(np.cross(p - a, b - a) / np.sqrt(np.dot(b - a, b - a)))

    @staticmethod
    def test_is_in_line(p, a, b):
        """Test if point ``p`` is within line built by ``a`` and ``b``.

        Parameters
        ----------
        p : tuple, list or Point
            Point, could be array of ``(x, y)``, or ``Point()``
            instance.
        a : tuple, list or Point
        b : tuple, list or Point
            Two point to build a line, ``a`` and ``b`` is limits of the line.

        """
        if isinstance(p, Point):
            p = p.point
        elif isinstance(p, (tuple, list, np.ndarray)):
            p = np.array(p)
        if isinstance(a, Point):
            a = a.point
        elif isinstance(a, (tuple, list, np.ndarray)):
            a = np.array(a)
        if isinstance(b, Point):
            b = b.point
        elif isinstance(b, (tuple, list, np.ndarray)):
            b = np.array(b)

        ap, ab = p - a, b - a
        if abs(np.cross(ap, ab) - EPS) < 0.0:  # out of line AB
            return False  # , 'out of Line AB'
        if np.dot(ap, ab) < 0.0:  # left of a
            return False  # , 'in Line AB, but left of a'
        if np.dot(ap, ab) > np.dot(ab, ab):  # right of b
            return False  # , 'in Line AB, but right of b'
        return True  # , 'within Line AB'

    def __getitem__(self, i):
        return self.point[i]

    def __repr__(self):
        return "Point ({0:.3f}, {1:.3f})".format(self._x, self._y)

    def move(self, vec=None, **kws):
        """Move point by given vector.

        Parameters
        ----------
        vec : array, list or tuple
            Along vector ``(x, y)`` to move point.

        Keyword Arguments
        -----------------
        direction : tuple
            Tuple of ``(theta, length)``, ``theta`` is anti-clockwised angle
            from ``x(+)`` to vector in degree, ``length`` is moving length.
            This argument will override *vec*.

        Returns
        -------
        ret : Point
            New *Point* object after moving.
        """
        if kws.get('direction', None) is not None:
            angle, length = kws.get('direction')
            theta = angle / 180.0 * np.pi
            m_vec = np.array((np.cos(theta), np.sin(theta))) * length
        else:
            m_vec = vec
        if m_vec is None:
            m_vec = (0, 0)
        return Point(self.point + m_vec)

    def rotate(self, angle, p0=None):
        """Rotate *angle* with *p0*.

        Parameters
        ----------
        angle : float
            Anti-clockwised rotating angle, degree.
        p0 : Point
            Rotating central point, ``(0,0)`` by default.

        Returns
        -------
        ret : Point
            New Point after rotation.
        """
        if p0 is None:
            p0 = Point(0, 0)
        p1 = self - p0
        theta = angle / 180.0 * np.pi
        m = np.array([[np.cos(theta), -np.sin(theta)],
                      [np.sin(theta), np.cos(theta)]])
        p1_rot, = np.dot(m, np.vstack(p1[:])).T
        return Point(p1_rot) + p0

class Line(object):
    """Lines in 2D Cartesian coordinate system, if invalid input is detected,
    return ``Line(0,1) from Point(0,0) to Point(0,1)``.

    Note
    ----
    Always initilize with two points.

    Initialization approaches:

    Examples
    --------
    Any one of the following is to create a line from ``(0,0)`` to ``(0,1)``

    >>> Line()
    >>> Line((0,1))
    >>> Line((0,0),(0,1))
    >>> Line(p1=(0,0), p2=(0,1))
    >>> Line(Point(0,0), Point(0,1))

    """

    def __init__(self, p1=None, p2=None):
        self.vec = (p1, p2)

    @property
    def x(self):
        """float: x coordinate."""
        return self._x

    @property
    def y(self):
        """float: y coordinate."""
        return self._y

    @x.setter
    def x(self, x):
        if isinstance(x, float):
            self._x = x
        elif isinstance(x, int):
            self._x = float(x)
        else:
            self._x = 0.0

    @y.setter
    def y(self, y):
        if isinstance(y, float):
            self._y = y
        elif isinstance(y, int):
            self._y = float(y)
        else:
            self._y = 1.0

    @property
    def vec(self):
        return np.array([self._x, self._y])

    @vec.setter
    def vec(self, vec):
        p1, p2 = vec[0], vec[1]
        if p1 is None:
            if p2 is None:
                p1, p2 = Point(0, 0), Point(0, 1)
            elif isinstance(p2, (list, tuple, np.ndarray, Point)):
                p1, p2 = Point(0, 0), Point(p2)
            else:
                print("Point should be defined by list, tuple, array or Point.")
                p1, p2 = Point(0, 0), Point(0, 1)
        elif isinstance(p1, (list, tuple, np.ndarray, Point)):
            if p2 is None:
                p1, p2 = Point(0, 0), Point(p1)
            elif isinstance(p2, (list, tuple, np.ndarray, Point)):
                p1, p2 = Point(p1), Point(p2)
            else:
                print("Point should be defined by list, tuple, array or Point.")
                p1, p2 = Point(0, 0), Point(0, 1)
        else:
            print("Point should be defined by list, tuple, array or Point.")
            p1, p2 = Point(0, 0), Point(0, 1)

        self._x, self._y = (p2 - p1).point
        self._p_begin, self._p_end = p1, p2
        self._stackpoints = np.vstack([self._p_begin.point, self._p_end.point])

    @property
    def pbegin(self):
        """Point: Starting point of line."""
        return self._p_begin

    @property
    def pend(self):
        """Point: Ending point of line."""
        return self._p_end

    def __repr__(self):
        return "Line ({0:.3f}, {1:.3f}) from {2} to {3}".format(
            self._x, self._y, self._p_begin, self._p_end)

    def __eq__(self, other):
        return ((self.x == other.x)
                and (self.y == other.y)
                and (self.pbegin == other.pbegin)
                and (self.pend == other.pend))

    def __abs__(self):
        return np.sqrt(self.x * self.x + self.y * self.y)

    def angle(self, other=None, **kws):
        """Angle between lines.

        Parameters
        ----------
        other : Line
            Another line.

        Keyword Arguments
        -----------------
        direction : tuple
            Tuple of ``(theta, length)``, ``theta`` is anti-clockwised angle
            from ``x(+)`` to vector in degree, ``length`` is moving length.
            This argument will override *vec*.

        Returns
        -------
        ret : float
            Angle in degree.
        """
        if isinstance(other, Line):
            # Line
            tmp = np.dot(self.vec, other.vec) / abs(self) / abs(other)
        else:
            if kws.get('direction', None) is not None:
                angle, length = kws.get('direction')
                theta = angle / 180.0 * np.pi
                m_vec = np.array((np.cos(theta), np.sin(theta))) * length
                tmp = np.dot(self.vec, m_vec) / abs(self) / length
        if np.allclose(-1, tmp):
            tmp = -1.0
        elif np.allclose(1, tmp):
            tmp = 1.0
        return np.arccos(tmp) / np.pi * 180.0

    def cross(self, other):
        """Cross point of two lines.

        Returns
        -------
        ret : Point
            Point both on all lines.

        """
        # line1 = p1 + t1 * d1
        # line2 = p2 + t2 * d2
        p1, p2 = self.pbegin, other.pbegin
        d1, d2 = self.vec, other.vec
        t1 = np.cross((p2 - p1).point, d2) / np.cross(d1, d2)
        return p1 + t1 * d1

    def move(self, vec=None, **kws):
        """Parallel move line by given vector.

        Parameters
        ----------
        vec : array, list or tuple
            Along vector ``(x, y)`` to move line.

        Keyword Arguments
        -----------------
        direction : tuple
            Tuple of ``(theta, length)``, ``theta`` is anti-clockwised angle
            from ``x(+)`` to vector in degree, ``length`` is moving length.
            This argument will override *vec*.

        Returns
        -------
        ret : Line
            New *Line* object after moving.
        """
        if kws.get('direction', None) is not None:
            angle, length = kws.get('direction')
            theta = angle / 180.0 * np.pi
            m_vec = np.array((np.cos(theta), np.sin(theta))) * length
        else:
            m_vec = vec
        if m_vec is None:
            m_vec = (0, 0)
        new_p_begin = self._p_begin + m_vec
        new_p_end = self._p_end + m_vec
        return Line(new_p_begin, new_p_end)

    def rotate(self, angle, p0=None):
        """Rotate *angle* with *p0*.

        Parameters
        ----------
        angle : float
            Anti-clockwised rotating angle, degree.
        p0 : Point
            Rotating central point, middle point of line by default.

        Returns
        -------
        ret : Line
            New line after rotation
        """
        p1, p2 = self.pbegin, self.pend
        if p0 is None:
            p0 = (p1 + p2) * 0.5
        p1, p2 = self.pbegin - p0, self.pend - p0
        theta = angle / 180.0 * np.pi
        m = np.array([[np.cos(theta), -np.sin(theta)],
                      [np.sin(theta), np.cos(theta)]])
        p1_rot, p2_rot = np.dot(m, np.vstack((p1[:], p2[:])).T).T
        new_p1, new_p2 = Point(p1_rot) + p0, Point(p2_rot) + p0
        return Line(new_p1, new_p2)

    def __getitem__(self, i):
        return self._stackpoints[i]

if __name__ == '__main__':
    # None, None
    p1 = Point()
    print(str(p1))

    # 1, None
    p2 = Point(1, )
    print(str(p2))

    # None, 1
    p3 = Point(y=1)
    print(str(p3))

    # None, INVALID
    p4 = Point(y='a')
    print(str(p4))

    # INVALID, INVALID
    p5 = Point('a', 'b')
    print(str(p5))

    # INVALID, None
    p6 = Point(x='a')
    print(str(p6))

    # tuple
    p7 = Point((1, 2))
    print(str(p7))

    # list
    p8 = Point([1, 2])
    print(str(p8))

    # array
    p9 = Point(np.array([1, 2]))
    print(str(p9))

    # Point instance
    p0 = Point(0, 1)
    p10 = Point(p0)
    print(str(p10))

    # compare
    print(Point(1, 2) == Point(x=1, y=2))

    # projection
    a = Point(1, 1)
    b = Point(5, 3)
    p = Point(2, 5)
    p_ab = p.proj_point(a, b)
    print(p_ab)

    # distance: point to point
    print(p.distance_to_point(p_ab))

    # distance: point to line
    print(p.distance_to_line(a, b))

    # inline test
    print(p_ab.is_in_line(a, b))

    ## move
    p = Point(0, 0)
    p_moveto1 = p.move(direction=(30, 1))
    p_moveto2 = p.move(direction=(45, 1))
    p_moveto3 = p.move(direction=(60, 1))

    import matplotlib.pyplot as plt

    fig = plt.figure(1)
    ax = fig.add_subplot(111, aspect='equal', xlim=[0, 1], ylim=[0, 1])
    line1 = np.vstack([p.point, p_moveto1.point])
    line2 = np.vstack([p.point, p_moveto2.point])
    line3 = np.vstack([p.point, p_moveto3.point])
    ax.scatter(*p.point, c='r')
    ax.scatter(*p_moveto1.point, c='b', label='30')
    ax.scatter(*p_moveto2.point, c='m', label='45')
    ax.scatter(*p_moveto3.point, c='g', label='60')
    ax.plot(line1[:, 0], line1[:, 1], '--')
    ax.plot(line2[:, 0], line2[:, 1], '--')
    ax.plot(line3[:, 0], line3[:, 1], '--')
    ax.legend()
    plt.show()

    # check move
    x = Point(1, 0)
    o = Point(0, 0)
    ox = Line(x - o)
    op1 = Line(p_moveto1 - o)
    op2 = Line(p_moveto2 - o)
    op3 = Line(p_moveto3 - o)

    print(ox.angle(op1))
    print(op1.angle(ox))
    print(ox.angle(op2))
    print(ox.angle(op3))

    # line
    line = Line(0, 0)
    print(line)

    line = Line((0, 1), (1, 0))
    print(line)

    line = Line(Point(1, 0))
    print(line)

    print(Line((0, 1)) == Line((0, 0), (0, 1)))

    # cross
    line1 = Line((1, 2), (2, 1))
    line2 = Line((3, 3), (4, 4))
    print(line1.cross(line2))

    # move
    line1 = Line((1, 2), (2, 1))
    line2 = line1.move((1, 1))
    print(line1)
    print(line2)

    print(line2[:, 1])


import asyncio
import board
import keypad

agua = 0
radio = 9.0
intervalo = 10
ajuste = 1.18
limite = 1000

def pluviometria():
    global agua
    agua += 1
    print("Agua: ",agua)

# def resetPluviometria()
#     global agua
#     agua = 0

def calcularMM():
    global agua
    mm = agua * 0.2794
    return mm

async def catch_pin_transitions(pin):
    """Print a message when pin goes low and when it goes high."""
    with keypad.Keys((pin,), value_when_pressed=False) as keys:
        while True:
            event = keys.events.get()
            if event:
                if event.released:
                    pluviometria()
            await asyncio.sleep(0)

async def principal():
    while True:
        global intervalo
        global agua
        agua = 0
        await asyncio.sleep(intervalo)
        print(calcularMM(), "mm")

async def main():
    interrupt_task = asyncio.create_task(catch_pin_transitions(board.GP21))
    print_task = asyncio.create_task(principal())
    await asyncio.gather(interrupt_task, print_task)

asyncio.run(main())


import random, time
from tkinter import *

class GUI:
    def __init__(self, window):
        self.window = window
        self.frame = Frame(window)
        self.frame.pack()
        self.width = 800
        self.height = 850
        self.row = 6 #height
        self.col = 7 #width
        self.messageSize = 25
        self.diameter = self.width / 7
        self.ox1 = 'RED'
        self.ox2 = 'BLUE'
        self.ox0 = 'BLACK'
        self.watcher = 2
        self.turn = self.watcher %2
        self.gameOVER = False
        self.one= False
        self.two= False

        self.quitButton = Button(self.frame, text='Quit',fg='green', command=self.quitGame)
        self.quitButton.pack(side=LEFT)

        self.OnePlayer = Button(self.frame, text='vs AI', command=self.playwithAi)
        self.OnePlayer.pack(side=RIGHT)

        self.TwoPlayer = Button(self.frame, text='vs another Human', command=self.playwithHuman)
        self.TwoPlayer.pack(side=RIGHT)

        self.scale = Scale(self.frame, orient=HORIZONTAL, from_=0, to=3, length=200, label='IQ for AI')
        self.scale.pack(side=LEFT)

        self.NewGame = Button(self.frame, text='New Game', command=self.clear)
        self.NewGame.pack(side=RIGHT)

        self.draw = Canvas(window, height=self.height, width=self.width)
        self.draw.bind('<Button-1>', self.mouseInput)
        self.draw.pack()

        self.circles = []
        self.colors = []

        y = 0
        for row in range(self.row):
            circleRow = []
            colorRow = []
            x=0
            for col in range(self.col):
                circleRow += [self.draw.create_oval(x, y, x + self.diameter, y + self.diameter, fill='BLACK')]
                colorRow += ['BLACK']
                x += self.diameter

            self.circles += [circleRow]
            self.colors += [colorRow]
            y += self.diameter

        self.message = self.draw.create_text(self.messageSize, self.height - self.messageSize,
                                             text='CHOOSE YOUR OPPONENT!!!',
                                             anchor='w', font='Courier 24')

    def mouseInput(self, event): #mouse input funtion
        # self.window.bell()
        col = int(event.x / self.diameter) #7
        row = int(event.y / self.diameter) #6
        print('board[%s][%s]' % (row, col))
        self.turn = self.watcher %2
        #print("turn is",self.turn)

        if self.one == True: #one player game
            self.humanmove(col)
            if not self.winsFor(self.ox1):
                self.aimove()
            if self.isFull():
                self.draw.itemconfig(self.message, text='TIE!!!')
                self.one = False

        if self.two == True: # 2 player game
            if self.turn == 0:
                ox = self.ox1
                if self.allowsMove(col):
                    self.watcher += 1
                    print('watcher1 is',self.watcher)
                row = self.addMove(col,ox)
                self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])
                self.draw.itemconfig(self.message, text='PLAYER 2 MAKE YOUR MOVE')

                if self.winsFor(ox):
                    self.draw.itemconfig(self.message, text='PLAYER 1 WIN!!!')
                    self.two = False

                if self.isFull():
                    self.draw.itemconfig(self.message, text='TIE!!!')
                    self.two = False

            if self.turn == 1:
                ox = self.ox2
                if self.allowsMove(col):
                    self.watcher -= 1
                    print('watcher1 is',self.watcher)
                row = self.addMove(col,ox)
                self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])
                self.draw.itemconfig(self.message, text='PLAYER 1 MAKE YOUR MOVE')

                if self.winsFor(ox):
                    self.draw.itemconfig(self.message, text='PLAYER 2 WIN!!!')
                    self.two = False

                if self.isFull():
                    self.draw.itemconfig(self.message, text='TIE!!!')
                    self.two = False

    def playwithAi(self):
        self.one= True
        self.two = False
        self.draw.itemconfig(self.message, text='MAKE YOUR MOVE HUMAN!!!')

    def playwithHuman(self):
        self.two = True
        self.one = False
        self.draw.itemconfig(self.message, text='PLAYER 1 MAKE YOUR MOVE')

    def humanmove(self,col): #move for human
        row = self.addMove(col, self.ox1)
        self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])
        self.draw.itemconfig(self.message, text='AI IS THINKING')
        if self.winsFor(self.ox1):
            self.draw.itemconfig(self.message, text='HUMAN WIN!!!')
            self.one = False

    def aimove(self): #move for AI
        col = self.nextMove()
        row = self.addMove(col, self.ox2)
        #self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])
        self.draw.after(1000, lambda: self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col]))
        print('AI move is', col)
        self.draw.after(1000, lambda: self.draw.itemconfig(self.message, text='MAKE YOUR MOVE HUMAN!!!'))
        if self.winsFor(self.ox2):
            self.draw.after(1000, lambda:self.draw.itemconfig(self.message, text='AI WIN!!!'))
            self.one = False

    def allowsMove(self,col): #check if a spot is empty
        if 0 <= col < self.col:
            return self.colors[0][col] == 'BLACK'
        else:
            return False

    def addMove(self,col,ox): #add a move to the board
        if self.allowsMove(col): #check if the column is available to add move
            for row in range(self.row):
                if self.colors[row][col] != 'BLACK':
                    self.colors[row-1][col] = ox
                    return row-1
            self.colors[self.row-1][col] = ox
            return self.row-1

    def clear(self): #clear the board
        self.one = False
        self.two = False
        self.draw.itemconfig(self.message, text='CHOOSE YOUR NEW OPPONENT!!!')
        for row in range(self.row):
            for col in range(self.col):
                self.colors[row][col] = 'BLACK'
                self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])

    def isFull(self): #check if the board is full
        for col in range(self.col):
            if self.allowsMove(col):
                return False
        return True

    def winsFor(self,ox):
        for row in range(self.row): #checks for win horizontally
            for col in range(self.col - 3):
                if self.colors[row][col] == ox and \
                    self.colors[row][col+1] == ox and \
                    self.colors[row][col+2] == ox and \
                    self.colors[row][col+3] == ox:
                        return True

        for row in range(self.row-3): #checks for win vertically
            for col in range(self.col):
                if self.colors[row][col] == ox and \
                    self.colors[row+1][col] == ox and \
                    self.colors[row+2][col] == ox and \
                    self.colors[row+3][col] == ox:
                        return True

        for row in range(self.row -3): #checks for win NW to SE
            for col in range(self.col -3):
                if self.colors[row][col] == ox and \
                    self.colors[row+1][col+1] == ox and \
                    self.colors[row+2][col+2] == ox and \
                    self.colors[row+3][col+3] == ox:
                        return True

        for row in range(3,self.row): #checks for win NE to SW
            for col in range(self.col -3):
                if self.colors[row][col] == ox and \
                    self.colors[row-1][col+1] == ox and \
                    self.colors[row-2][col+2] == ox and \
                    self.colors[row-3][col+3] == ox:
                        return True
        return False

    def delMove(self,col): #delete one move
        for row in range(self.row):
            if self.colors[row][col] != 'BLACK':
                self.colors[row][col] = 'BLACK'
                return row

    def quitGame(self):
        self.window.destroy()

    def scoresFor(self, ox, ply):
        if ply == 0 :
            return [50] * 7

        goodMoves = [0] * 7
        for move1 in range(7):
            if not self.allowsMove(move1):
                continue

            col = move1
            row = self.addMove(move1, self.ox2)
            self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])

            if self.winsFor(self.ox2):
                # a winning moves get 100
                goodMoves[move1] = 100
                col = move1
                row = self.delMove(move1)
                self.draw.itemconfig(self.circles[row][col], fill='BLACK')
                break #no bother checking other moves if win
            else:
                # counter moves
                if self.isFull():
                    goodMoves[move1] = 0
                else:
                    for move2 in range(7):
                        if not self.allowsMove(move2):
                            continue
                        col = move2
                        row= self.addMove(move2,self.ox1)
                        self.draw.itemconfig(self.circles[row][col], fill=self.colors[row][col])

                        if self.winsFor(self.ox1):
                            # losing moves get -1
                            goodMoves[move1] = -1
                            col = move2
                            row = self.delMove(move2)
                            self.draw.itemconfig(self.circles[row][col], fill='BLACK')
                            break
                        else:
                            # recursive
                            goodMoves[move1] += max(self.scoresFor(ox, ply - 1))
                        col = move2
                        row = self.delMove(move2)
                        self.draw.itemconfig(self.circles[row][col], fill='BLACK')
            col = move1
            row = self.delMove(move1)
            self.draw.itemconfig(self.circles[row][col], fill='BLACK')
        return goodMoves

    def nextMove(self):
        strategy = self.scoresFor(self.ox2, self.scale.get())
        # get the highest scores to set it as a standard to make choice easier
        bestMove = -1
        for i in range(7):
            if strategy[i] > bestMove and self.allowsMove(i):
                bestMove = strategy[i]

        # get the move that has highest score
        execute = [] #list of the column that has good moves
        for i in range(7):
            if strategy[i] == bestMove and self.allowsMove(i):
                execute.append(i)
                print(execute)
        return random.choice(execute) #random because sometimes bestMove is not 100 but only 50

def main():
    root = Tk()
    root.title('Connect 4')
    b= GUI(root)
    root.mainloop()

if __name__ == '__main__':
    main()


# importing models.
import argparse
import torch
import json
import torchvision
from torchvision import datasets, transforms, models
from torch import nn
from torch import optim
import torch.nn.functional as F
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

def main():
    # getting arguments
    args = get_input_args()

    # loading model
    model = load_checkpoint(args.model_dir)

    # device = gpu_check(args.gpu)
    if args.gpu:
        device = 'cuda'
    else:
        device = 'cpu'
    # converting model to device type
    model.to(device)

    with open(args.cat_to_name, 'r') as f:
        cat_to_name = json.load(f)

    # predict image
    probs, names = predict(args.image_path,args.on_gpu, model,device,cat_to_name,topk=args.top_k)

    # Print name of predicted flower with highest probability
    print("This flower is most likely to be a: {} with a probability of {}% ".format(names[0],np.round(probs[0][0]*100,2)))

 # function for arguments
def get_input_args():
    parser = argparse.ArgumentParser(description="Train a Neural Network to Predict Images")
    parser.add_argument('--model_dir', type=str, default= "my_checkpoint.pth", help="directory of the model")
    parser.add_argument('--image_path',type=str, default= "flowers/test/1/image_06743.jpg",help="Enter path to image for prediction")
    parser.add_argument('--cat_to_name', type=str, default="cat_to_name.json", help="Enter path to cat_to_name file")
    parser.add_argument('--gpu', action = "store_true",help= "GPU")
    parser.add_argument('--top_k', type=int,  default=5, help="Top K")
    parser.add_argument('--on_gpu', type=str, default= "gpu", help="use gpu or cpu, default is gpu. Make sure gpu is turned on")

    args = parser.parse_args()

    return args

# function to load model
def load_checkpoint(filepath):
    checkpoint = torch.load(filepath)
    model = models.vgg16(pretrained=True)

    model.classifier = checkpoint['classifier']
    model.load_state_dict(checkpoint['state_dict'])
    model.class_to_idx = checkpoint['class_to_idx']

    for param in model.parameters():
        param.requires_grad = False

    return model

# function to load model using PIL image and passing it to the model
def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
    '''
    # open imgae using PIL.Image
    img = Image.open(image)

    # define means and std
    means = [0.485, 0.456, 0.406]
    deviations = [0.229, 0.224, 0.225]
    # define transforms
    transform = transforms.Compose([transforms.Resize(256),
                                         transforms.CenterCrop(224),
                                         transforms.ToTensor(),
                                         transforms.Normalize(means, deviations)])
    # apply transform to the image
    image = transform(img)

    # return image
    return image

# function to predict the image.
def predict(image_path,on_gpu, model,device,cat_to_name,topk=5):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''

    model.to(device)
    # process image
    img = process_image(image_path)
    img.unsqueeze_(0)
    # convert image to float
    img = img.float()

    model.eval()

    # check if gpu exist. if gpu exits  transformed image is converted to cuda, else pass transformed image to model
    if on_gpu == "gpu":
        with torch.no_grad():
            output = model(img.cuda())
    else:
        with torch.no_grad():
            output = model(img)

    # calculating probabilites
    prob = torch.exp(output)
    probs = np.array(prob.topk(topk)[0])
    idxs = np.array(prob.topk(topk)[1])

    # convert indicies to classes
    idxs = np.array(idxs)
    idx_to_class = {value:key for key, value in model.class_to_idx.items()}
    classes = [idx_to_class[idx] for idx in idxs[0]]

    #map the class name with collect topk classes
    names = []
    for class_ in classes:
        names.append(cat_to_name[str(class_)])

    return probs, names

if __name__ == '__main__':main()


import urllib.request
from bs4 import BeautifulSoup
import csv

class Scraper:
    def __init__(self, site):
        self.site = site

    def save_data(self,data):
        headers = data[0].keys()
        with open("news_data.csv", 'w') as out_file:
            dict_writer = csv.DictWriter(out_file,headers)
            dict_writer.writeheader()
            dict_writer.writerows(data)

    def scrape(self):
        news_list = []
        r = urllib.request.urlopen(self.site)
        html = r.read()
        parser = "html.parser"
        sp = BeautifulSoup(html,parser)
        section = sp.find('section',class_="mainbox")
        article = section.find('article',class_="leftcol MT30")
        div_list = article.find('div',class_="listingholder")
        for div in div_list:
            news_dict = {}
            figure = div.find('figure')
            if figure != -1:
                news_dict['figure'] = figure.find('img').get('src')
            h2 = div.find('h2')
            if h2 != -1:
                news_dict['title'] = h2.select('a')[0].text
                news_dict['date'] = div.select('span')[0].text
            short_description = div.find('p')
            if short_description != -1:
                news_dict['short_desc'] = short_description.get_text()
            if news_dict:
                news_list.append(news_dict)
        self.save_data(news_list)

news = "https://www.loksatta.com/sampadkiya/agralekh/"
Scraper(news).scrape()


import requests
import os
from jose import jwk, jwt
from jose.utils import base64url_decode
import time
import re

# The below token validation is based on
# https://github.com/awslabs/aws-support-tools/blob/master/Cognito/decode-verify-jwt/decode-verify-jwt.py
# and https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/
def validate_token(token):
    if not token:
        return False

    keys = requests.get(
        f'{os.environ["USER_POOL_ENDPOINT"]}/.well-known/jwks.json'
    ).json()["keys"]

    # Get the kid from the headers prior to verification
    headers = jwt.get_unverified_headers(token)

    # Search for the kid of the token in the downloaded public keys
    try:
        key = next(key for key in keys if key["kid"] == headers["kid"])
    except StopIteration:
        return False

    # Construct the public key
    public_key = jwk.construct(key)

    # Get the last two sections of the token, message and signature (encoded in base64)
    message, encoded_signature = str(token).rsplit(".", 1)

    # Decode the signature
    decoded_signature = base64url_decode(encoded_signature.encode("utf-8"))

    # Verify the signature
    if not public_key.verify(message.encode("utf8"), decoded_signature):
        # Signature verification failed
        return False

    # Signature successfully verified
    claims = jwt.get_unverified_claims(token)

    # Verify the token expiration
    if time.time() > claims["exp"]:
        # Token is expired
        return False

    # Verify the token issuer
    if claims["iss"] != os.environ["USER_POOL_ENDPOINT"]:
        # Token was not issued by this user pool
        return False

    return claims

def authenticate(event, context):
    claims = validate_token(event.get("authorizationToken"))
    if not claims:
        return False

    policy = AuthPolicy(claims["username"])

    method_arn = event["methodArn"].split(":")
    api_gateway = method_arn[5].split("/")
    policy.stage = api_gateway[1]

    policy.awsAccountId = method_arn[4]
    policy.restApiId = api_gateway[0]
    policy.region = method_arn[3]

    policy.allowAllMethods()

    response = policy.build()
    response["context"] = {"cognito:groups": ",".join(claims.get("cognito:groups", []))}

    return response

class HttpVerb:
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    PATCH = "PATCH"
    HEAD = "HEAD"
    DELETE = "DELETE"
    OPTIONS = "OPTIONS"
    ALL = "*"

# The below policy generator was sourced from the Lambda blueprint titled
# "api-gateway-authorizer-python"
class AuthPolicy(object):
    # The principal used for the policy, this should be a unique identifier for the end user.
    principalId = ""
    # The policy version used for the evaluation. This should always be '2012-10-17'
    version = "2012-10-17"
    # The regular expression used to validate resource paths for the policy
    pathRegex = "^[/.a-zA-Z0-9-\*]+$"

    """Internal lists of allowed and denied methods.

    These are lists of objects and each object has 2 properties: A resource
    ARN and a nullable conditions statement. The build method processes these
    lists and generates the approriate statements for the final policy.
    """
    allowMethods = []
    denyMethods = []

    # The AWS account id the policy will be generated for. This is used to create the method ARNs.
    # By default this is set to '*'
    awsAccountId = "*"
    # The API Gateway API id. By default this is set to '*'
    restApiId = "*"
    # The region where the API is deployed. By default this is set to '*'
    region = "*"
    # The name of the stage used in the policy. By default this is set to '*'
    stage = "*"

    def __init__(self, principal):
        self.principalId = principal
        self.allowMethods = []
        self.denyMethods = []

    def _addMethod(self, effect, verb, resource, conditions):
        """Adds a method to the internal lists of allowed or denied methods. Each object in
        the internal list contains a resource ARN and a condition statement. The condition
        statement can be null."""
        if verb != "*" and not hasattr(HttpVerb, verb):
            raise NameError(
                "Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class"
            )
        resourcePattern = re.compile(self.pathRegex)
        if not resourcePattern.match(resource):
            raise NameError(
                "Invalid resource path: "
                + resource
                + ". Path should match "
                + self.pathRegex
            )

        if resource[:1] == "/":
            resource = resource[1:]

        resourceArn = "arn:aws:execute-api:{}:{}:{}/{}/{}/{}".format(
            self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource
        )

        if effect.lower() == "allow":
            self.allowMethods.append(
                {"resourceArn": resourceArn, "conditions": conditions}
            )
        elif effect.lower() == "deny":
            self.denyMethods.append(
                {"resourceArn": resourceArn, "conditions": conditions}
            )

    def _getEmptyStatement(self, effect):
        """Returns an empty statement object prepopulated with the correct action and the
        desired effect."""
        statement = {
            "Action": "execute-api:Invoke",
            "Effect": effect[:1].upper() + effect[1:].lower(),
            "Resource": [],
        }

        return statement

    def _getStatementForEffect(self, effect, methods):
        """This function loops over an array of objects containing a resourceArn and
        conditions statement and generates the array of statements for the policy."""
        statements = []

        if len(methods) > 0:
            statement = self._getEmptyStatement(effect)

            for curMethod in methods:
                if curMethod["conditions"] is None or len(curMethod["conditions"]) == 0:
                    statement["Resource"].append(curMethod["resourceArn"])
                else:
                    conditionalStatement = self._getEmptyStatement(effect)
                    conditionalStatement["Resource"].append(curMethod["resourceArn"])
                    conditionalStatement["Condition"] = curMethod["conditions"]
                    statements.append(conditionalStatement)

            if statement["Resource"]:
                statements.append(statement)

        return statements

    def allowAllMethods(self):
        """Adds a '*' allow to the policy to authorize access to all methods of an API"""
        self._addMethod("Allow", HttpVerb.ALL, "*", [])

    def denyAllMethods(self):
        """Adds a '*' allow to the policy to deny access to all methods of an API"""
        self._addMethod("Deny", HttpVerb.ALL, "*", [])

    def allowMethod(self, verb, resource):
        """Adds an API Gateway method (Http verb + Resource path) to the list of allowed
        methods for the policy"""
        self._addMethod("Allow", verb, resource, [])

    def denyMethod(self, verb, resource):
        """Adds an API Gateway method (Http verb + Resource path) to the list of denied
        methods for the policy"""
        self._addMethod("Deny", verb, resource, [])

    def allowMethodWithConditions(self, verb, resource, conditions):
        """Adds an API Gateway method (Http verb + Resource path) to the list of allowed
        methods and includes a condition for the policy statement. More on AWS policy
        conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
        self._addMethod("Allow", verb, resource, conditions)

    def denyMethodWithConditions(self, verb, resource, conditions):
        """Adds an API Gateway method (Http verb + Resource path) to the list of denied
        methods and includes a condition for the policy statement. More on AWS policy
        conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
        self._addMethod("Deny", verb, resource, conditions)

    def build(self):
        """Generates the policy document based on the internal lists of allowed and denied
        conditions. This will generate a policy with two main statements for the effect:
        one statement for Allow and one statement for Deny.
        Methods that includes conditions will have their own statement in the policy."""
        if (self.allowMethods is None or len(self.allowMethods) == 0) and (
            self.denyMethods is None or len(self.denyMethods) == 0
        ):
            raise NameError("No statements defined for the policy")

        policy = {
            "principalId": self.principalId,
            "policyDocument": {"Version": self.version, "Statement": []},
        }

        policy["policyDocument"]["Statement"].extend(
            self._getStatementForEffect("Allow", self.allowMethods)
        )
        policy["policyDocument"]["Statement"].extend(
            self._getStatementForEffect("Deny", self.denyMethods)
        )

        return policy


#Data Manipulation
import numpy as np
import pandas as pd

#plotting

import matplotlib.pyplot as plt

##Mchine Learning
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

## Data fetching
df=pd.read_csv('E:/dta/Google.csv')

df=df.dropna()
df=df[['Open','High','Low','Close']]
df.head()

#####Predictor Variables
df['Open-Close']=df.Open-df.Close
df['High-Low']=df.High-df.Low
df.dropna()
X=df[['Open-Close','High-Low']]
X.head()

##Target Variable
Y=np.where(df['Close'].shift(-1)>df['Close'],1,-1)
print(Y)

##Split the Dataset
split_percentage=0.7
split=int(split_percentage*len(df))

X_train=X[:split]
Y_train=Y[:split]

X_test=X[split:]
Y_test=Y[split:]
##################OR===Split the Dataset(Randomly)
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test=train_test_split(X,Y, test_size=0.3,random_state=10)

####KNN Learning Model (K=15)
knn=KNeighborsClassifier(n_neighbors=15)

##Fit the model

knn.fit(X_train,Y_train)

####Accuracy Score

accuracy_train=accuracy_score(Y_train,knn.predict(X_train))
accuracy_test=accuracy_score(Y_test, knn.predict(X_test))

print('Train_data Accuracy:%2f' %accuracy_train)
print('Test_data Accuracy: %.2f' %accuracy_test)

#####Predict Signal
df['Predicted_Signal']=knn.predict(X)

###SPY Cumulative Returns
df['SPY_Returns']=np.log(df['Close']/df['Close'].shift(1))
Cumulative_SPY_Returns=df[split:]['SPY_Returns'].cumsum()*100

###Cumulative Strategey Returns
df['Strategy_Returns']=df['SPY_Returns']* df['Predicted_Signal'].shift(1)
Cum_Strategy_Returns=df[split:]['Strategy_Returns'].cumsum()*100

#####Plot the results
plt.figure(figsize=(10,5))
plt.plot(Cumulative_SPY_Returns,Color='r',label='SPY Returns')
plt.plot(Cum_Strategy_Returns,color='g',label='Strategy Returns')
plt.legend
plt.show()