from __future__ import absolute_import
import argparse
import os
import shutil
import tarfile
import tempfile
import unittest

from telemetry.core import fuchsia_interface
from telemetry.internal.browser import browser_options
from telemetry.internal.platform import fuchsia_device
import mock

_FUCHSIA_DEVICE_IMPORT_PATH = 'telemetry.internal.platform.fuchsia_device'

class FuchsiaDeviceTest(unittest.TestCase):

  def testFindFuchsiaDevice(self):
    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                        '.fuchsia_interface.run_ffx_command',
                    return_value=argparse.Namespace(
                        stdout='{"device":"list"}')):
      self.assertEqual(fuchsia_device._FindFuchsiaDevice(), {"device":"list"})

  def testFindAllAvailableDevicesFailsNonFuchsiaBrowser(self):
    options = browser_options.BrowserFinderOptions('not_fuchsia_browser')
    self.assertEqual(fuchsia_device.FindAllAvailableDevices(options), [])

  def testFindAllAvailableDevicesFailsNonLinuxHost(self):
    options = browser_options.BrowserFinderOptions(
        fuchsia_interface.FUCHSIA_BROWSERS[0])
    with mock.patch('platform.system', return_value='not_Linux'):
      self.assertEqual(fuchsia_device.FindAllAvailableDevices(options), [])

  def testFindAllAvailableDevicesFailsNonx64(self):
    options = browser_options.BrowserFinderOptions(
        fuchsia_interface.FUCHSIA_BROWSERS[0])
    with mock.patch('platform.system', return_value='Linux'):
      with mock.patch('platform.machine', return_value='i386'):
        self.assertEqual(fuchsia_device.FindAllAvailableDevices(options), [])

class FuchsiaSDKUsageTest(unittest.TestCase):

  def setUp(self):
    system_mock = mock.patch('platform.system', return_value='Linux')
    system_mock.start()
    self.addCleanup(system_mock.stop)
    platform_mock = mock.patch('platform.machine', return_value='x86_64')
    platform_mock.start()
    self.addCleanup(platform_mock.stop)
    self._options = browser_options.BrowserFinderOptions(
        fuchsia_interface.FUCHSIA_BROWSERS[0])
    self._options.fuchsia_ssh_config = 'test/'
    self._options.fuchsia_ssh_port = None
    self._options.fuchsia_system_log_file = None
    self._options.fuchsia_repo = None
    self._options.fuchsia_device_address = None
    self._options.fuchsia_target_id = None

  def testSkipSDKUseIfSshPortExists(self):
    self._options.fuchsia_ssh_port = 22222
    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                    '._DownloadFuchsiaSDK') as get_mock:
      found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
      get_mock.assert_not_called()
      self.assertEqual(len(found_devices), 1)
      device = found_devices[0]
      self.assertEqual(device.port, 22222)
      self.assertEqual(device.host, 'localhost')

  def testUseFfxIfTargetIdExists(self):
    self._options.fuchsia_target_id = 'fuchsia-test-device'
    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                        '.fuchsia_interface.run_ffx_command',
                    return_value=argparse.Namespace(
                        stdout='1.2.3.4:22222')):
      found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
      self.assertEqual(len(found_devices), 1)
      device = found_devices[0]
      self.assertEqual(device.port, 22222)
      self.assertEqual(device.host, '1.2.3.4')

  def testRaiseValueErrorForInvalidInput(self):
    self._options.fuchsia_target_id = 'fuchsia-test-device'
    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                        '.fuchsia_interface.run_ffx_command',
                    return_value=argparse.Namespace(
                        stdout='1.2.3.4;22222')):
      with self.assertRaises(ValueError):
        fuchsia_device.FindAllAvailableDevices(self._options)

  def testDownloadSDKIfNotExists(self):
    with mock.patch('os.path.exists', return_value=False):
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                      '._DownloadFuchsiaSDK') as get_mock:
        with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                        return_value=None) as find_mock:
          self.assertEqual(
              fuchsia_device.FindAllAvailableDevices(self._options), [])
          self.assertEqual(get_mock.call_count, 1)
          self.assertEqual(find_mock.call_count, 1)

  def testDecompressSDK(self):
    test_file = 'testfile'
    def side_effect(cmd, stderr):
      if 'cp' in cmd:
        del stderr
        tar_file = cmd[-1]
        with tarfile.open(tar_file, 'w') as tar:
          temp_dir = tempfile.mkdtemp()
          try:
            os.makedirs(os.path.join(temp_dir, 'tools'))
            temp_file = os.path.join(temp_dir, test_file)
            with open(temp_file, 'w'):
              tar.add(temp_file, arcname=test_file)
          finally:
            shutil.rmtree(temp_dir)

    temp_dir = tempfile.mkdtemp()
    try:
      test_tar = os.path.join(temp_dir, 'test.tar')
      with mock.patch('subprocess.check_output') as cmd_mock:
        with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                        '._GetLatestSDKHash', return_value='hash'):
          cmd_mock.side_effect = side_effect
          fuchsia_device._DownloadFuchsiaSDK(test_tar, temp_dir)
          self.assertTrue(os.path.isfile(os.path.join(temp_dir, test_file)))
      self.assertFalse(os.path.isfile(os.path.join(temp_dir, test_tar)))
    finally:
      shutil.rmtree(temp_dir)

  def testSkipDownloadSDKIfExists(self):
    with mock.patch('os.path.exists', return_value=True):
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                      '._DownloadFuchsiaSDK') as get_mock:
        with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                        return_value=None) as find_mock:
          self.assertEqual(
              fuchsia_device.FindAllAvailableDevices(self._options), [])
          get_mock.assert_not_called()
          self.assertEqual(find_mock.call_count, 1)

  def testFoundZeroFuchsiaDevice(self):
    with mock.patch('os.path.exists', return_value=True):
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=None):
        self.assertEqual(fuchsia_device.FindAllAvailableDevices(self._options),
                         [])

  def testFoundOneFuchsiaDevice(self):
    with mock.patch('os.path.exists', return_value=True):
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=[{"addresses":["a0"], "nodename":"n0"}]):
        found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
        self.assertEqual(len(found_devices), 1)
        device = found_devices[0]
        self.assertEqual(device.host, 'a0')
        self.assertEqual(device.target_id, 'n0')

  def testFoundMultipleFuchsiaDevices(self):
    with mock.patch('os.path.exists', return_value=True):
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=[
                          {"addresses":["a0"], "nodename":"n0"},
                          {"addresses":["a1"], "nodename":"n1"}]):
        found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
        self.assertEqual(len(found_devices), 1)
        device = found_devices[0]
        self.assertEqual(device.host, 'a0')
        self.assertEqual(device.target_id, 'n0')

  def testSkipUsingSDKIfFuchsiaSshPortFlagUsed(self):

    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                    '._DownloadFuchsiaSDK') as get_mock:
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=None) as find_mock:
        self._options.fuchsia_ssh_port = 8222
        found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
        self.assertEqual(len(found_devices), 1)
        device = found_devices[0]
        self.assertEqual(device.host, 'localhost')
        get_mock.assert_not_called()
        find_mock.assert_not_called()

  def testSkipUsingSDKIfFuchsiaHostFlagUsed(self):

    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                    '._DownloadFuchsiaSDK') as get_mock:
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=None) as find_mock:
        self._options.fuchsia_device_address = '1.2.3.4'
        found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
        self.assertEqual(len(found_devices), 1)
        device = found_devices[0]
        self.assertEqual(device.host, '1.2.3.4')
        get_mock.assert_not_called()
        find_mock.assert_not_called()

  def testSkipUsingFuchsiaHostFlagIfFuchsiaSshPortFlagUsed(self):

    with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH +
                    '._DownloadFuchsiaSDK') as get_mock:
      with mock.patch(_FUCHSIA_DEVICE_IMPORT_PATH + '._FindFuchsiaDevice',
                      return_value=None) as find_mock:
        self._options.fuchsia_device_address = 'fuchsia_device'
        self._options.fuchsia_ssh_port = 8222
        found_devices = fuchsia_device.FindAllAvailableDevices(self._options)
        self.assertEqual(len(found_devices), 1)
        device = found_devices[0]
        self.assertEqual(device.host, 'localhost')
        get_mock.assert_not_called()
        find_mock.assert_not_called()


def convert_to_grakel_graph( graph, label_request ):
    """
    Convert an igraph graph object to GraKeL format

    :param graph: The igraph object to convert
    :param label_request: A dict describing which attributes to use as vertex
                          and edge labels respectively
    :returns: A list of items satisfying GraKeL's graph format
    :raises:
    """

    if label_request is not None and label_request["vertex"] == "logical_tick":
        graph = add_logical_tick_labels(graph)

    # Set edge list
    edge_list = []
    for e in graph.es[:]:
        edge_list.append( ( e.source, e.target ) )

    # Set vertex labels if requested
    vid_to_label = {}
    if label_request is not None:
        for v in graph.vs[:]:
            if label_request["vertex"] is not None:
                # If the requested label is a vertex attribute, apply it
                try:
                    vid_to_label[ v.index ] = v[label_request["vertex"]]
                # If it's not a vertex attribute, just apply a dummy label
                except:
                    print("Vertex label: {} not available".format(label_request["vertex"]))
                    vid_to_label[ v.index ] = 0

    # Set edge labels if requested
    eid_to_label = {}
    if label_request is not None:
        for e in graph.es[:]:
            if label_request["edge"] is not None:
                # If the requested label is an edge attribute, apply it
                try:
                    eid_to_label[ e.index ] = e[label_request["edge"]]
                # If it's not an existing edge attribute, compute it if possible,
                # or if not, just apply a dummy label
                except:
                    if label_request["edge"] == "logical_time_latency":
                        eid_to_label[ e.index ] = get_edge_latency( graph, e, clock="logical" )
                    elif label_request["edge"] == "wall_time_latency":
                        eid_to_label[ e.index ] = get_edge_latency( graph, e, clock="wall" )
                    else:
                        eid_to_label[ e.index ] = 0

    vid_to_attributes = {}
    eid_to_attributes = {}

    return [ edge_list, vid_to_label, eid_to_label ]

def add_logical_tick_labels(graph):
    for v in graph.vs[:]:
        preds = v.predecessors()
        if len(preds) > 0:
            pred_logical_times = [ p["logical_time"] for p in preds ]
            tick = max([v["logical_time"] - lts for lts in pred_logical_times])
            v["logical_tick"] = tick
        else:
            v["logical_tick"] = 0
    return graph

def preprocess( graphs, base_kernel_defs, kernels, labelings ):
    labeling_to_graphs =  { "unlabeled" : [ convert_to_grakel_graph(g, None) for g in graphs ] }
    # First check if we need labels at all
    need_labels = False
    for k in kernels:
        constraints = base_kernel_defs[k]["constraints"]
        if constraints["vertex_label"] == "needs":
            need_labels = True
            break
    if not need_labels:
        return labeling_to_graphs
    else:
        for lab in labelings:
            key = (lab["vertex"], lab["edge"])
            labeling_to_graphs[key] = [ convert_to_grakel_graph(g, lab) for g in graphs ]
        return labeling_to_graphs

    ## First determine if we need to add logical tick labels.
    ## TODO: Move this functionality into dumpi_to_graph
    #graphs = [ add_logical_tick_labels(g) for g in graphs ]
    #
    ## Create mapping between labelings and sets of correspondingly labeled graphs
    #labeling_to_graphs = { l:[ convert_to_grakel_graph(g, l) for g in graphs ] for l in labelings }

    #return labeling_to_graphs


depth = horizontal = 0
f = open("input_day2.txt", "r")
for line in f:
    movement = line.split(" ")
    direction = movement[0]
    distance = int(movement[1])
    if direction == "forward":
        horizontal += distance
    elif direction == "down":
        depth += distance
    else:
        depth -= distance
f.close()
print(depth * horizontal)


#!/usr/bin/env python

import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Pose, Twist, Transform, TransformStamped
from geometry_msgs.msg import PoseWithCovarianceStamped
from std_msgs.msg import Header
import numpy as np
import math

def talker():
    pub1 = rospy.Publisher('initialpose', PoseWithCovarianceStamped, queue_size=1)
    pub2 = rospy.Publisher('base_pose_ground_truth', Odometry, queue_size=1)

    rospy.init_node('initialpose_groundtruth', anonymous=True)

    rate = rospy.Rate(10)
    initial_pose = PoseWithCovarianceStamped()
    ground_truth = Odometry()

    initial_pose.pose.pose.position.x = -0.5
    initial_pose.pose.pose.position.y = 0
    initial_pose.pose.pose.position.z = 0
    initial_pose.pose.pose.orientation.x = 0
    initial_pose.pose.pose.orientation.y = 0
    initial_pose.pose.pose.orientation.z = 0
    initial_pose.pose.pose.orientation.w = 1

    ground_truth.pose.pose.position.x = -0.5
    ground_truth.pose.pose.position.y = 0
    ground_truth.pose.pose.position.z = 0
    ground_truth.pose.pose.orientation.x = 0
    ground_truth.pose.pose.orientation.y = 0
    ground_truth.pose.pose.orientation.z = 0
    ground_truth.pose.pose.orientation.w = 1
    while not rospy.is_shutdown():

        pub1.publish(initial_pose)
        pub2.publish(ground_truth)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass


import cv2
import numpy as np

def velo2depth(velo, calib, IMG_H, IMG_W):
    # velo point to cam0
    velo = velo[:, 0: 3]  # x,y,z
    velo = np.insert(velo, 3, 1, axis=1).T  # change to 4*n
    cam = np.dot(calib.T_velo2cam0, velo)

    # Filter z < 0 points
    cam = np.delete(cam, np.where(cam[2, :] < 0)[0], axis=1)
    # get u,v,z
    cam[:2] /= cam[2, :]
    cam[2, :] = cam[2, :] * 1000
    cam = cam.astype(np.uint16)  # to int
    # filter point out of canvas
    u, v, _ = cam
    u_out = np.logical_or(u < 0, u >= IMG_W)
    v_out = np.logical_or(v < 0, v >= IMG_H)
    outlier = np.logical_or(u_out, v_out)
    cam = np.delete(cam, np.where(outlier), axis=1)
    u, v, z = cam
    # the depth image data
    img = np.zeros([IMG_H, IMG_W], dtype=np.int16)
    for i in range(len(z)):
        img[v[i], u[i]] = z[i]
    return img.astype(np.uint16)

# Full kernels
FULL_KERNEL_3 = np.ones((3, 3), np.uint8)
FULL_KERNEL_5 = np.ones((5, 5), np.uint8)
FULL_KERNEL_7 = np.ones((7, 7), np.uint8)
FULL_KERNEL_9 = np.ones((9, 9), np.uint8)
FULL_KERNEL_31 = np.ones((31, 31), np.uint8)

# 3x3 cross kernel
CROSS_KERNEL_3 = np.asarray(
    [
        [0, 1, 0],
        [1, 1, 1],
        [0, 1, 0],
    ], dtype=np.uint8)

# 5x5 cross kernel
CROSS_KERNEL_5 = np.asarray(
    [
        [0, 0, 1, 0, 0],
        [0, 0, 1, 0, 0],
        [1, 1, 1, 1, 1],
        [0, 0, 1, 0, 0],
        [0, 0, 1, 0, 0],
    ], dtype=np.uint8)

# 5x5 diamond kernel
DIAMOND_KERNEL_5 = np.array(
    [
        [0, 0, 1, 0, 0],
        [0, 1, 1, 1, 0],
        [1, 1, 1, 1, 1],
        [0, 1, 1, 1, 0],
        [0, 0, 1, 0, 0],
    ], dtype=np.uint8)

# 7x7 cross kernel
CROSS_KERNEL_7 = np.asarray(
    [
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
    ], dtype=np.uint8)

# 7x7 diamond kernel
DIAMOND_KERNEL_7 = np.asarray(
    [
        [0, 0, 0, 1, 0, 0, 0],
        [0, 0, 1, 1, 1, 0, 0],
        [0, 1, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 1, 1],
        [0, 1, 1, 1, 1, 1, 0],
        [0, 0, 1, 1, 1, 0, 0],
        [0, 0, 0, 1, 0, 0, 0],
    ], dtype=np.uint8)

def fill_in_fast(depth_map, max_depth=100.0, custom_kernel=DIAMOND_KERNEL_5,
                 extrapolate=False, blur_type='bilateral'):
    """Fast, in-place depth completion.

    Args:
        depth_map: projected depths
        max_depth: max depth value for inversion
        custom_kernel: kernel to apply initial dilation
        extrapolate: whether to extrapolate by extending depths to top of
            the frame, and applying a 31x31 full kernel dilation
        blur_type:
            'bilateral' - preserves local structure (recommended)
            'gaussian' - provides lower RMSE

    Returns:
        depth_map: dense depth map
    """

    # Invert
    valid_pixels = (depth_map > 0.1)
    depth_map[valid_pixels] = max_depth - depth_map[valid_pixels]

    # Dilate
    depth_map = cv2.dilate(depth_map, custom_kernel)

    # Hole closing
    depth_map = cv2.morphologyEx(depth_map, cv2.MORPH_CLOSE, FULL_KERNEL_5)

    # Fill empty spaces with dilated values
    empty_pixels = (depth_map < 0.1)
    dilated = cv2.dilate(depth_map, FULL_KERNEL_7)
    depth_map[empty_pixels] = dilated[empty_pixels]

    # Extend the highest pixel to top of image
    if extrapolate:
        top_row_pixels = np.argmax(depth_map > 0.1, axis=0)
        top_pixel_values = depth_map[top_row_pixels, range(depth_map.shape[1])]

        for pixel_col_idx in range(depth_map.shape[1]):
            depth_map[0:top_row_pixels[pixel_col_idx], pixel_col_idx] = \
                top_pixel_values[pixel_col_idx]

        # Large Fill
        empty_pixels = depth_map < 0.1
        dilated = cv2.dilate(depth_map, FULL_KERNEL_31)
        depth_map[empty_pixels] = dilated[empty_pixels]

    # Median blur
    depth_map = cv2.medianBlur(depth_map, 5)

    # Bilateral or Gaussian blur
    if blur_type == 'bilateral':
        # Bilateral blur
        depth_map = cv2.bilateralFilter(depth_map, 5, 1.5, 2.0)
    elif blur_type == 'gaussian':
        # Gaussian blur
        valid_pixels = (depth_map > 0.1)
        blurred = cv2.GaussianBlur(depth_map, (5, 5), 0)
        depth_map[valid_pixels] = blurred[valid_pixels]

    # Invert
    valid_pixels = (depth_map > 0.1)
    depth_map[valid_pixels] = max_depth - depth_map[valid_pixels]
    return depth_map


from unittest.mock import patch

from django.test import TestCase
from users.models import User
from django.core import mail
from http import HTTPStatus as status

class UserTests(TestCase):
    def test_get_absolute_url_method(self):
        user = User(username='Mohammed', email='mr-m@yahoo.com')
        user.save()
        response = self.client.get(user.get_absolute_url())
        self.assertEqual(response.status_code, status.OK)

    @patch('django.core.mail.message.DNS_NAME', 'www.volla.co')
    def test_email_user(self):
        user = User(username='Missy Elliot', email='missy@gmail.com')
        user.save()
        self.assertEqual(len(mail.outbox), 0)
        user.email_user('Yo', 'Keep it real girl')
        self.assertEqual(len(mail.outbox), 1)
        email = mail.outbox[0]
        self.assertEqual(email.to, ['missy@gmail.com'])
        self.assertEqual(email.from_email, 'support@volla.co')


from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.contrib import admin
from app import views

from app.views import LatestEntriesFeed

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'legalsuff.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$', 'app.views.home', name='home'),
    url(r'^rss/$', LatestEntriesFeed()),
    url(r'^view/$', 'app.views.view_documents', name='view_documents'),
    url(r'^view/(?P<pk>[\w|-]+)/$', 'app.views.print_documents', name='print_documents'),
    url(r'^published/$', 'app.views.published_query', name='published_query'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^search/$', 'app.views.search', name='search'),
    url(r'^document/$', 'app.views.new_document', name='new_document'),
    url(r'^document/(?P<pk>[\w|-]+)/$', login_required(views.DocumentUpdate.as_view()), name='document-detail'),
    url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'redirect_field_name':'/'}),
    url(r'^logout/$', 'django.contrib.auth.views.logout',
                          {'next_page': '/'}),
    url(r'^redactor/', include('redactor.urls')),
)


import numpy as np
import pandas as pd
import pickle
import streamlit as st

print('Pandas {}'.format(pd.__version__))
print('Numpy {}'.format(np.__version__))
print('Streamlit {}'.format(st.__version__))
class_names = ['saudável', 'pesticidas', 'outros']

# load model
load_model = pickle.load(open('xgb_clf.pkl', 'rb'))

# main menu
def menu():

    st.sidebar.header('Home')
    page = st.sidebar.radio("", ('SciCrop',
                                 'Plataforma ML',
                                 'Safra Predição',
                                 'Contato'))
    # hide the menu
    hide_streamlit_style = """
                <style>
                # MainMenu {visibility: hidden;}
                footer {visibility: hidden;}
                </style>
                """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)

    if page == 'SciCrop':
        scicrop()

    if page == 'Plataforma ML':
        plataform()

    if page == 'Safra Predição':
        safra()

    if page == 'Contato':
        contato()

# ScriCrop page
def scicrop():
    st.title('SciCrop')
    st.write('A SciCrop é uma startup no segmento de soluções de Big Data e hoje oferece soluções de processamento de dados mais rápidas, eficientes e flexíveis para fornecer informações estratégicas por meio de algoritmos para a gestão de seus negócios.')
    st.image(
        'https://agevolution.canalrural.com.br/wp-content/uploads/2019/06/Scicrop.jpg',
        width=700,
        height=700,
        caption='SciCrop Logo')

# SciCrop ML
def plataform():
    st.title('Machine learning Plataform')
    st.write('Apesar do agro gerar muito lucro, a vida dos agricultores não é fácil, mas sim um verdadeiro teste de resistência e determinação. Uma vez que tenhamos semeado as sementes, o agricultor precisa trabalhar dia e noite para garantir uma boa safra no final da estação. Uma boa colheita depende de diversos fatores \
             como disponibilidade de água, fertilidade do solo, proteção das culturas, uso oportuno de pesticidas, outros fatores químicos úteis e da natureza. Muitos desses dados são quase impossíveis de se controlar, mas a quantidade e a frequência de pesticidas é algo que o agricultor pode administrar. Os pesticidas podem protegem a colheita com a dosagem certa. Mas, se adicionados em quantidade inadequada, podem prejudicar toda a safra.')
    st.write('\n')
    st.image('https://www.sulinfoco.com.br/wp-content/uploads/2019/05/Agricultura-Giro-Rural-1.jpg',
             width=600,
             height=300)
    st.write('\n')
    st.write('Essa plataforma de Machine learning foi desenvolvida para resolver está dor do Agricultor brasileiro, na plataforma ele consegue fazer a previsão da colheita da Safra.  \
             A plataforma é armazenada na nuvem e está disponível para uso do agricultor, permitindo que ele tenha acesso apenas entrando neste aplicativo web e  através do preenchimento dos dados, \
             em segundos a inferência é feita ao modelo de machine learning,  e ele terá a previsão em mãos sobre o resultado da colheita de safra.')

# Safra Prediction
def safra():
    st.image(
        'https://agevolution.canalrural.com.br/wp-content/uploads/2019/06/Scicrop.jpg',
        width=500,
        height=200)
    st.title('Safra Prediction')
    st.write('\n')
    st.write('\n')
    st.write('\n')

    # estimativa de insetos
    numero_insetos = st.number_input(
        'Estimativa_de_Insetos', min_value=0, max_value=100000, value=0)

    # tipo de cultivo
    tipo_cultivo = st.selectbox('Tipo_de_Cultivo', [0, 1])

    # tipo de solo
    tipo_solo = st.selectbox('Tipo_de_Solo', [0, 1])

    # categoria pesticidas
    cat_pesticidas = st.selectbox('Categoria_Pesticida', [0, 1, 2])

    # doses semana
    doses_semana = st.number_input(
        'Doses_Semana', min_value=0, max_value=10000000, value=0)

    # semanas utilizando
    semanas_utlizando = st.number_input(
        'Semanas_Utilizando', min_value=0, max_value=10000000, value=0)
    # semanas sem uso
    semanas_sem_uso = st.number_input(
        'Semanas_Sem_Uso', min_value=0, max_value=1000000, value=0)

    # temporada climática
    temporada = st.selectbox('Temporada', [1, 2, 3])

    input_dict = {'Estimativa_de_Insetos': [numero_insetos], 'Tipo_de_Cultivo': [tipo_cultivo],
                  'Tipo_de_Solo': [tipo_solo], 'Categoria_Pesticida': [cat_pesticidas],
                  'Doses_Semana': [doses_semana], 'Semanas_Utilizando': [semanas_utlizando],
                  'Semanas_Sem_Uso': [semanas_sem_uso], 'Temporada': [temporada]}

    input_df = pd.DataFrame(input_dict)
    load_model = pickle.load(open('xgb_clf.pkl', 'rb'))

    if st.button('Predição'):
        output = load_model.predict(input_df)
        if output == 0:
            st.success('Colheita de Safra:  {}'.format('Sem danos'))
        elif output == 1:
            st.success('Colheita de Safra:  {}'.format(
                'Danos por outros motivos'))
        else:
            st.success('Colheita de Safra:  {}'.format(
                'Danos gerados por pesticidas'))

# contato
def contato():
    st.title('Contato')
    st.image('https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSh8_BbTxZSsHWdLsSVjvVGVjASl3WynpmbMg&usqp=CAU',
             width=100, height=100)
    st.write('\n')
    st.write('\n')
    st.write('Este projeto foi desenvolvido por Felipe Oliveira, \
             Dúvidas ou sugestões podem me encaminhar um e-mail ou uma mensagem no LinkedIn.')
    st.write('\n')
    st.markdown(
        '[LinkedIn](https://www.linkedin.com/in/felipe-oliveira-18a573189/)')
    st.write('\n')
    st.write('E-mail: felipe.oliveiras2000@gmail.com')

if __name__ == '__main__':
    menu()


import re
import tempfile
import textwrap
from unittest import mock

import click
import pytest
import yaml

from atacac import _utils

@pytest.mark.parametrize(
    "level, fatal",
    [
        pytest.param("info", True, id="level='info', fatal"),
        pytest.param("INFO", True, id="level='INFO', fatal"),
        pytest.param("info", False, id="level='info'"),
        pytest.param("INFO", False, id="level='INFO'"),

        pytest.param("warn", True, id="level='warn', fatal"),
        pytest.param("WARN", True, id="level='WARN', fatal"),
        pytest.param("warn", False, id="level='warn'"),
        pytest.param("WARN", False, id="level='WARN'"),

        pytest.param("warning", True, id="level='warning', fatal"),
        pytest.param("WARNING", True, id="level='WARNING', fatal"),
        pytest.param("warning", False, id="level='warning'"),
        pytest.param("WARNING", False, id="level='WARNING'"),

        pytest.param("error", True, id="level='error', fatal"),
        pytest.param("ERROR", True, id="level='ERROR', fatal"),
        pytest.param("error", False, id="level='error'"),
        pytest.param("ERROR", False, id="level='ERROR'"),

        pytest.param("debug", True, id="level='debug', fatal"),
        pytest.param("DEBUG", True, id="level='DEBUG', fatal"),
        pytest.param("debug", False, id="level='debug'"),
        pytest.param("DEBUG", False, id="level='DEBUG'"),
    ]
)
@mock.patch("atacac._utils.textwrap")
@mock.patch("atacac._utils.click")
def test_log(mock_click, mock_textwrap, level, fatal):
    message = "This is a message."

    mock_click.Abort = click.Abort
    mock_click.style.return_value = level
    mock_textwrap.indent.return_value = f"{level} {message}"

    try:
        _utils.log(level, message, fatal=fatal)
        mock_click.echo.assert_called_once()
        mock_click.echo.assert_called_with(f"{level} {message}")
    except click.Abort:
        assert fatal is True

@pytest.mark.parametrize(
    "error, asset_type, query",
    [
        pytest.param(None, "user", ("label", 1), id="user"),
        pytest.param(None, "organization", ("label", 1), id="organization"),
        pytest.param(None, "team", ("label", 1), id="team"),
        pytest.param(None, "credential_type", ("label", 1), id="credential_type"),
        pytest.param(None, "credential", ("label", 1), id="credential"),
        pytest.param(None, "notification_template", ("label", 1), id="notification_template"),
        pytest.param(None, "inventory_script", ("label", 1), id="inventory_script"),
        pytest.param(None, "project", ("label", 1), id="project"),
        pytest.param(None, "inventory", ("label", 1), id="inventory"),
        pytest.param(None, "job_template", ("label", 1), id="job_template"),
        pytest.param(None, "workflow", ("label", 1), id="workflow"),
        pytest.param("Unsupported asset type 'ABC123XYZ'!",
                     "ABC123XYZ", ("label", 1), id="unsupported asset type")
    ]
)
@mock.patch("tower_cli.get_resource")
def test_tower_list(mock_get_resource, error, asset_type, query):
    result_assets = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}]

    mock_instance = mock_get_resource.return_value
    mock_instance.list.return_value = {"results": result_assets}

    try:
        retval = _utils.tower_list(asset_type, query)
    except _utils.Error as e:
        assert str(e) == error
        assert e.error_code == 1
    else:
        mock_get_resource.assert_called_once()
        mock_get_resource.assert_called_with(asset_type)

        mock_instance.list.assert_called_once()
        mock_instance.list.assert_called_with(all_pages=True, query=("label", 1))

        assert retval == result_assets

@mock.patch("atacac._utils.tower_receive")
@mock.patch("atacac._utils.tower_list")
def test_tower_list_all(mock_tower_list, mock_tower_receive):
    def tower_list(asset_type, query):
        return [{'id': 1, 'name': f'Example {asset_type}'}]

    mock_tower_list.side_effect = tower_list
    mock_tower_receive.return_value = [
        {
            'project': 'Example project',
            'inventory': 'Example inventory',
        },
    ]

    result = _utils.tower_list_all([('label', 1)])

    assert list(sorted(result, key=lambda i: i['name'])) == [
        {'id': 1, 'type': 'inventory', 'name': 'Example inventory'},
        {'id': 1, 'type': 'job_template', 'name': 'Example job_template'},
        {'id': 1, 'type': 'project', 'name': 'Example project'},
    ]

    mock_tower_list.assert_has_calls([
        mock.call('job_template', [('label', 1)]),
        mock.call('project', [('name', 'Example project')]),
        mock.call('inventory', [('name', 'Example inventory')]),
    ])

@pytest.mark.parametrize(
    "error, asset_type, asset_name",
    [
        pytest.param(None, "user", "file", id="user"),
        pytest.param(None, "organization", "file", id="organization"),
        pytest.param(None, "team", "file", id="team"),
        pytest.param(None, "credential_type", "file", id="credential_type"),
        pytest.param(None, "credential", "file", id="credential"),
        pytest.param(None, "notification_template", "file", id="notification_template"),
        pytest.param(None, "inventory_script", "file", id="inventory_script"),
        pytest.param(None, "project", "file", id="project"),
        pytest.param(None, "inventory", "file", id="inventory"),
        pytest.param(None, "job_template", "file", id="job_template"),
        pytest.param(None, "workflow", "file", id="workflow"),
        pytest.param("Unsupported asset type 'ABC123XYZ'!",
                     "ABC123XYZ", "file", id="unsupported asset type")
    ]
)
@mock.patch("atacac._utils.Receiver")
def test_tower_receive(mock_Receiver, error, asset_type, asset_name):
    dictionary = {"dictA": {"key_1": "value_1"}, "dictB": {"key_2": "value_2"}}

    mock_instance = mock_Receiver.return_value
    mock_instance.export_assets.return_value = dictionary

    try:
        assert _utils.tower_receive(asset_type, asset_name) == dictionary
    except _utils.Error as e:
        assert str(e) == error
        assert e.error_code == 1
    else:
        mock_Receiver.assert_called_once()

        mock_instance.export_assets.assert_called_once()
        mock_instance.export_assets.assert_called_with(all=False, asset_input={asset_type: [asset_name]})

@pytest.mark.parametrize(
    "assets",
    [
        pytest.param("foo", id="file"),
        pytest.param(["foo", "bar"], id="file list"),
    ]
)
@mock.patch("atacac._utils.Sender")
def test_tower_send(mock_Sender, assets):
    mock_instance = mock_Sender.return_value

    _utils.tower_send(assets)

    mock_Sender.assert_called_once()
    mock_Sender.assert_called_with(False)

    mock_instance.send.assert_called_once()
    mock_instance.send.assert_called_with(
        assets if isinstance(assets, list) else [assets], None, None, "default")

def test_load_asset_valid_path():
    file_data = textwrap.dedent(
        """\
        ---
        key_a:
          key_i: foo
          key_j: 111
        key_b:
          key_x: bar
          key_y: 222
        """
    )

    with tempfile.NamedTemporaryFile() as tmpfile:
        tmpfile.write(bytes(file_data, encoding="utf-8"))
        tmpfile.seek(0)

        result = _utils.load_asset(tmpfile.name)

        assert result == yaml.safe_load(file_data)

def test_load_asset_invalid_path():
    try:
        _utils.load_asset("./a/b/c/d/e/f/g/h/i/file")
    except _utils.Error as e:
        assert re.match(r"^Failed to read content of '\./a/b/c/d/e/f/g/h/i/file'$", str(e))
        assert e.error_code == 1

@pytest.mark.parametrize(
    "value, sanitized",
    [
        pytest.param('foo_bar.yml', 'foo_bar.yml'),
        pytest.param('foo/bar.yml', 'foo_bar.yml'),
        pytest.param('foo///bar.yml', 'foo_bar.yml'),
        pytest.param('foo.bar.yml', 'foo.bar.yml'),
        pytest.param('foo-bar.yml', 'foo-bar.yml'),
        pytest.param('foo bar baz foo bar.job.yml', 'foo_bar_baz_foo_bar.job.yml'),
    ]
)
def test_sanitize(value, sanitized):
    assert _utils.sanitize_filename(value) == sanitized


def sum(a, b):
    if a == 0:
        return print(b)
    sum(a - 1, b + 1)

a = int(input())
b = int(input())
if a > b:
    (a, b) = (b, a)
sum(a, b)


# 2669번 직사각형 네개의 합집합의 면적 구하기
# https://www.acmicpc.net/problem/2669

# 모든 x, y 좌표는 1 이상 100 이하의 정수
# 이에 맞는 그래프 정의 (0은 좌표에 없더라도 x,y 좌표를 생각하지 않기 위해 추가)
graph = [[False for _ in range(101)] for _ in range(101)]

# 중복되는 면적을 제외하기 위해 이미 True 라면 의미없게 만들어 줌
for _ in range(4):
    ldx, ldy, rux, ruy = map(int, input().split())
    for ey in range(ldy, ruy):
        for ex in range(ldx, rux):
            graph[ey][ex] = True

area = 0
for y in range(101):
    for x in range(101):
        if graph[y][x]:
            area += 1

print(area)


for _ in range(int(input())):
    tc = int(input())
    cnt = [0] * 101
    nums = list(map(int, input().split()))
    for num in nums:
        cnt[num] += 1
    m, ans = 0, 0
    for i in range(100, -1, -1):
        if cnt[i] > m:
            m = cnt[i]
            ans = i
    print(f'#{tc} {ans}')


# Clone a repo from Github
# 12f23eddde <rzhe@pku.edu.cn> - Apr 12 2021
import git
import os
import pandas as pd
import numpy as np
import requests

def clone_project_from_github(owner: str, repo: str, branch='master',REPOS_DIR='repos/', proxy=None):
    path = os.path.abspath(f'{REPOS_DIR}/{owner}/{repo}/{branch}')

    if not os.path.exists(path):
        os.makedirs(path)

    git_config=f"http.proxy={proxy}" if proxy else None
    git.Repo.clone_from(f'http://github.com/{owner}/{repo}.git', to_path=path, branch=branch,
        config=git_config)

def download_file_from_github(owner:str, repo: str, branch='master', file='requirements.txt', overwrite=True, proxy=None, REPOS_DIR='repos/') -> bool:
    requests_proxies = {
        "http": f"{proxy}",
        'https': f"{proxy}"
    } if proxy else None

    url = f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/{file}"

    try:
        r = requests.get(url=url, proxies=requests_proxies)
    except FileNotFoundError:
        return False

    # create folder, place file owner/repo/branch/file
    if not os.path.exists(f"{REPOS_DIR}/{owner}/{repo}/{branch}"):
        os.makedirs(f"{REPOS_DIR}/{owner}/{repo}/{branch}")

    # do not overwrite if file exists
    if not overwrite and os.path.exists(f"{REPOS_DIR}/{owner}/{repo}/{branch}/{file}"):
        return False

    if r.status_code != 200:
        return False

    with open(f"{REPOS_DIR}/{owner}/{repo}/{branch}/{file}", 'w+') as f:
        f.write(r.text)

    return True

if __name__ == '__main__':
    clone_project_from_github('requests', 'requests-oauthlib', REPOS_DIR='./tests/', proxy='socks5://10.128.188.189:1081')
    download_file_from_github('requests', 'requests-oauthlib', REPOS_DIR='./tests/', proxy='socks5://10.128.188.189:1081')


import requests

# Replace this with the base URL of your Flask application
BASE_URL = 'http://localhost:5000'

# Function to send a GET request and print the response
def print_response(response):
    print(f"Status code: {response.status_code}")
    try:
        print("Response:")
        print(response.json())
    except Exception as e:
        print(f"Error reading response JSON: {e}")
    print("\n")

# Test creating a new Bairro
def test_create_bairro():
    data = {
        'nome_bairro': 'Test Bairro',
        'regiao': 'Test Region',
        'cep': '12345678',
        'id_cidade': 1  # Replace with the ID of the associated Cidade
    }
    response = requests.post(f"{BASE_URL}/bairro", json=data)
    print_response(response)

# Test getting all Bairros
def test_get_bairros():
    response = requests.get(f"{BASE_URL}/bairros")
    print_response(response)

# Test getting a specific Bairro by ID
def test_get_bairro_by_id(id):
    response = requests.get(f"{BASE_URL}/bairro/{id}")
    print_response(response)

# Test updating an existing Bairro by ID
def test_update_bairro(id):
    data = {
        'nome_bairro': 'Updated Bairro',
        'regiao': 'Updated Region',
        'cep': '87654321',
        'id_cidade': 2  # Replace with the new ID of the associated Cidade
    }
    response = requests.put(f"{BASE_URL}/bairro/{id}", json=data)
    print_response(response)

# Test deleting a specific Bairro by ID
def test_delete_bairro(id):
    response = requests.delete(f"{BASE_URL}/bairro/{id}")
    print_response(response)

# Test creating a new Logradouro
def test_create_logradouro():
    data = {
        'nome_rua': 'Test Street',
        'numero': 123,
        'complemento': 'Test Complement',
        'id_bairro': 1  # Replace with the ID of the associated Bairro
    }
    response = requests.post(f"{BASE_URL}/logradouro", json=data)
    print_response(response)

# Test getting all Logradouros
def test_get_logradouros():
    response = requests.get(f"{BASE_URL}/logradouros")
    print_response(response)

# Test getting a specific Logradouro by ID
def test_get_logradouro_by_id(id):
    response = requests.get(f"{BASE_URL}/logradouro/{id}")
    print_response(response)

# Test updating an existing Logradouro by ID
def test_update_logradouro(id):
    data = {
        'nome_rua': 'Updated Street',
        'numero': 456,
        'complemento': 'Updated Complement',
        'id_bairro': 2  # Replace with the new ID of the associated Bairro
    }
    response = requests.put(f"{BASE_URL}/logradouro/{id}", json=data)
    print_response(response)

# Test deleting a specific Logradouro by ID
def test_delete_logradouro(id):
    response = requests.delete(f"{BASE_URL}/logradouro/{id}")
    print_response(response)

if __name__ == '__main__':
    # Test all CRUD operations for Bairro
    test_create_bairro()

    test_get_bairros()

    test_get_bairro_by_id(1)  # Replace 1 with the ID of the Bairro you want to retrieve

    test_update_bairro(1)  # Replace 1 with the ID of the Bairro you want to update

    test_delete_bairro(1)  # Replace 1 with the ID of the Bairro you want to delete

    # Test all CRUD operations for Logradouro
    test_create_logradouro()

    test_get_logradouros()

    test_get_logradouro_by_id(1)  # Replace 1 with the ID of the Logradouro you want to retrieve

    test_update_logradouro(1)  # Replace 1 with the ID of the Logradouro you want to update

    test_delete_logradouro(1)  # Replace 1 with the ID of the Logradouro you want to delete


import os
from pickletools import string1
import shutil
import numpy as np
import cv2
import math
# import pytesseract
# from pytesseract import Output
from scipy import ndimage
from genericpath import isdir
from scipy import misc
from PIL import Image
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
import time
import string
import keras_ocr
reg = keras_ocr.detection.Detector()
image_folder = "./enhanced_images/inverse_law/test_dataset.mp4"
files = os.listdir(image_folder)
print(files)
path = files[0]
p = image_folder + "/" + path
print(p)
image = keras_ocr.tools.read(p)
img_det = reg.detect([image])
# print(img_det[0])
img_tup = []
for i in range(len(img_det[0])):
    st = 'roi'+str(i+1)
    img_tup.append((st, img_det[0][i]))
# print(img_tup)
img = keras_ocr.tools.drawBoxes(image, img_det[0], color=(
    36, 255, 12), thickness=2, boxes_format='boxes')
# print(img)
# img = keras_ocr.tools.drawAnnotations(image=image, predictions=img_tup,ax=None)
# print(img)
# fig, axs = plt.subplots(nrows=1, figsize=(20, 20))
# keras_ocr.tools.drawAnnotations(
#         image=image, predictions=img_tup, ax=axs)
# plt.show()
# print(img_tup[0][1])
# print(img_tup[0][1][0])
# print(img_tup[0][1][0][0])
for i in img_tup:
    x=int(i[1][0][0])
    y = int(i[1][0][1])
    # print(f"{x}   -  {y}")
    cv2.putText(img, i[0], (x, y-10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 49, 49), 2)
cv2.imshow('window_name', img)
r=input("Please select the ROIs on which you want OCR to be done by entering them with comma as a separator:")
rl=r.split(",")
rm=list(map(lambda x:"roi"+x,rl))
rf=tuple(filter(lambda x:x[0] in rm,img_tup))
print(rf)
ROIs = cv2.selectROIs(
    "Select ROIs and press Enter to move further, Press Esc to exit, Press c to clear selection", img)
# print rectangle points of selected roi
# ROIs.append(img_det)
print(ROIs)
# names = []
ROI_tup=[]
for i in ROIs:
    name = input(
        'Please enter the attribute name for the selected ROIS:')
    # names.append(name)
    ROI_tup.append((name,i))
ROI_tup.extend(rf)
# print(ROI_tup)
for name,coords in ROI_tup:
    print(f'{name} --- {coords}  {type(coords)} {coords.shape}')
# waits for user to press any key
# (this is necessary to avoid Python kernel form crashing)
cv2.waitKey(0)

# # closing all open windows
cv2.destroyAllWindows()


#!/usr/bin/python
import pandas as pd
import numpy as np
import sys
import math
import argparse
import os.path

parser = argparse.ArgumentParser()
parser.add_argument('--path', help= 'Path to csv file (_edited.csv)')
args = parser.parse_args()

if args.path is not None:
    DATASET = args.path
else:
    DATASET = '../datasets/analysis_test_data/cvi_identified_edited.csv'

print('Generating data from csv dataset: "' + DATASET + '"\n')

if os.path.isdir("./histogram/"):
    OUTPUT_DIR = './histogram/'
elif os.path.isdir("../histogram/"):
    OUTPUT_DIR = '../histogram/'
else:
    OUTPUT_DIR = './'
OUTPUT = OUTPUT_DIR + 'data_input.sc'
ROW_LIMIT = 1000

def main():
    df=pd.read_csv(DATASET,sep=',')
    A = np.array(df)
    N = A.shape[0]
    N = min(N,ROW_LIMIT)
    M = A.shape[1]
    with open(OUTPUT,'w') as output:
        output.write('/* Rows: ' + str(N) + ' */' + '\n')
        output.write('/* Attributes (' + str(M) + ') */' + '\n')
        output.write('/**' + '\n')
        for i in range(len(df.columns)):
            col = df.columns[i]
            output.write(' * '+ col + ' (' + str(i) + ') : ' + str(df[col].dtype) + '\n')
        output.write('**/' + '\n')
        array = '{'
        for i in range(N):
            for j in range(M):
                array += str(A[i,j]) + ','
        array = array[:-1]
        array += '}'
        var = 'pd_shared3p ' + str(df[col].dtype) + '[[2]] imported_array'
        command = 'reshape('+ array +', '+ str(N) +', '+ str(M) +');'
        output.write(var + ' = ' + command + '\n')
        mins = [str(min([A[i,j] for i in range(N)])) for j in range(M)]
        mins = '{' + ','.join(mins) + '}'
        maxs = [str(max([A[i,j] for i in range(N)])) for j in range(M)]
        maxs = '{' + ','.join(maxs) + '}'
        output.write('pd_shared3p ' + str(df[col].dtype) + '[[1]] imported_mins(' + str(M) + ') = ' + mins + ';\n')
        output.write('pd_shared3p ' + str(df[col].dtype) + '[[1]] imported_maxs(' + str(M) + ') = ' + maxs + ';\n')
    print('\nOutput SecreC file: "' + OUTPUT + '"')

if __name__ == '__main__':
    main()


import os
import logging

import torch
from bistiming import Stopwatch
from mkdir_p import mkdir_p
import numpy as np
from sklearn.preprocessing import OneHotEncoder, StandardScaler

from .utils import set_random_seed
from lolip.utils import estimate_local_lip_v2
from lolip.variables import get_file_name

logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
                    level=logging.WARNING, datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)

def run_experiment01(auto_var):
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    _ = set_random_seed(auto_var)
    norm = auto_var.get_var("norm")
    trnX, trny, tstX, tsty = auto_var.get_var("dataset")
    lbl_enc = OneHotEncoder(categories=[np.sort(np.unique(trny))], sparse=False).fit(trny.reshape(-1, 1))
    auto_var.set_intermidiate_variable("lbl_enc", lbl_enc)
    n_classes = len(np.unique(trny))
    n_channels = trnX.shape[-1]

    #trnX -= 0.5
    #tstX -= 0.5
    #img_shape = trnX.shape[1:]
    #scaler = StandardScaler(with_std=False)
    #trnX = scaler.fit_transform(trnX.reshape(len(trnX), -1)).reshape((len(trnX), ) + img_shape)
    #tstX = scaler.transform(tstX.reshape(len(tstX), -1)).reshape((len(tstX), ) + img_shape)

    result = {}
    #multigpu = True if len(trnX) > 90000 and torch.cuda.device_count() > 1 else False
    multigpu = False
    model = auto_var.get_var("model", trnX=trnX, trny=trny, multigpu=multigpu,
            n_channels=n_channels, device=device)
    model.tst_ds = (tstX, tsty)
    result['model_path'] = os.path.join('./models/experiment01', get_file_name(auto_var) + '-ep%04d.pt')
    if None:
        result['model_path'] = result['model_path'] % model.epochs
        model.load(result['model_path'])
        model.model.to(device)
    else:
        with Stopwatch("Fitting Model", logger=logger):
            history = model.fit(trnX, trny)
        mkdir_p("./models/experment01")
        model.save(result['model_path'])
        result['model_path'] = result['model_path'] % model.epochs
        result['history'] = history

    result['trn_acc'] = (model.predict(trnX) == trny).mean()
    result['tst_acc'] = (model.predict(tstX) == tsty).mean()
    print(f"train acc: {result['trn_acc']}")
    print(f"test acc: {result['tst_acc']}")

    attack_model = auto_var.get_var("attack", model=model, n_classes=n_classes)
    with Stopwatch("Attacking Train", logger=logger):
        adv_trnX = attack_model.perturb(trnX, trny)
    with Stopwatch("Attacking Test", logger=logger):
        adv_tstX = attack_model.perturb(tstX, tsty)
    result['adv_trn_acc'] = (model.predict(adv_trnX) == trny).mean()
    result['adv_tst_acc'] = (model.predict(adv_tstX) == tsty).mean()
    print(f"adv trn acc: {result['adv_trn_acc']}")
    print(f"adv tst acc: {result['adv_tst_acc']}")
    del attack_model

    with Stopwatch("Estimating trn Lip", logger=logger):
        trn_lip, _ = estimate_local_lip_v2(model.model, trnX, top_norm=1, btm_norm=norm,
                                    epsilon=auto_var.get_var("eps"), device=device)
    result['avg_trn_lip'] = trn_lip
    with Stopwatch("Estimating tst Lip", logger=logger):
        tst_lip, _ = estimate_local_lip_v2(model.model, tstX, top_norm=1, btm_norm=norm,
                                     epsilon=auto_var.get_var("eps"), device=device)
    result['avg_tst_lip'] = tst_lip
    print(f"avg trn lip: {result['avg_trn_lip']}")
    print(f"avg tst lip: {result['avg_tst_lip']}")

    print(result)
    return result


from flask import Flask, render_template, request, redirect
import main
import sqlite3
import plotly as py
import plotly.graph_objs as go
from plotly.offline import plot
from markupsafe import Markup

app = Flask(__name__)
most_popular_list = ['Arts', 'Automobiles', 'Blogs', 'Books', 'Business Day',
    'Education', 'Fashion & Style', 'Food', 'Health', 'Job Market', 'Magazine',
    'membercenter', 'Movies', 'Multimedia', 'NYT Now', 'Obituaries', 'Open',
    'Opinion', 'Public Editor', 'Real Estate', 'Science', 'Sports', 'Style',
    'Sunday Review', 'T Magazine', 'Technology', 'The Upshot', 'Theater',
    'Times Insider', 'Today’s Paper', 'Travel', 'U.S.', 'World', 'Your Money',
    'all-sections']

class Nearby:
    def __init__(self, init_tuple):
        self.name = init_tuple[0]
        self.address = init_tuple[1]
        # self.distance = format(init_tuple[2], '.2f')
        self.distance = init_tuple[2]
        self.price = init_tuple[3]
        self.rating = init_tuple[4]
        self.review_count = init_tuple[5]
        self.url = init_tuple[6]
        self.phone = init_tuple[7]
class BestSeller:
    def __init__(self, init_tuple):
        self.title = init_tuple[0]
        self.author = init_tuple[1]
        self.created_date = init_tuple[2]
        self.primary_isbn13 = init_tuple[3]
        self.age = init_tuple[4]
        self.description = init_tuple[5]
class MostPopular:
    def __init__(self, init_tuple):
        self.title = init_tuple[0]
        self.url = init_tuple[1]
        self.published_date = init_tuple[2]
        self.abstract = init_tuple[3]

@app.route('/')
def home():
    main.program_start()
    return render_template('home.html')

@app.route('/select', methods=['POST'])
def signup():
    search_type = request.form['search_type']
    return redirect('/' + search_type)

@app.route('/restaurantsearch')
def restaurant_search():
    return render_template('restaurant.html')

@app.route('/restaurantsearch/confirm', methods=['POST'])
def restaurant_search_confirm():
    location = request.form['location']
    main.map_nearby_search(location)
    return redirect('/restaurantsearch/results')

@app.route('/restaurantsearch/results')
def restaurant_search_nearby():
    conn = sqlite3.connect(main.DBNAME)
    cur = conn.cursor()
    statement = '''SELECT search_address FROM Gmap'''
    cur.execute(statement)
    search = ''
    for row in cur:
        if search == '':
            search = row[0]
    statement = '''
        SELECT GMap.name, GMap.address, distance, price, rating,
                review_count, url, phone
        FROM Gmap
        JOIN Yelp
        ON Yelp.name=GMap.name'''

    cur.execute(statement)
    search_result = []
    for row in cur:
        search_result.append(Nearby(row))

    trace0 = go.Bar(
        x=[x.name for x in search_result],
        y=[y.rating for y in search_result]
    )
    barLayout = go.Layout(title='Restaurant')

    my_plot_div = plot([trace0], output_type='div')
    #END OF ANSWER

    return render_template('restaurant_nearby.html', result=search_result, place=search, div_placeholder=Markup(my_plot_div))

@app.route('/bestsellers')
def best_sellers():
    return render_template('bestsellers.html')

@app.route('/bestsellers/confirm', methods=['POST'])
def bs_search():
    date = request.form['date']
    main.nyt_book_search(date)
    return redirect('/bestsellers/results')

@app.route('/bestsellers/results')
def best_sellers_result():
    conn = sqlite3.connect(main.DBNAME)
    cur = conn.cursor()
    statement = '''SELECT title, author, created_date, primary_isbn13,
                    age_group, description
                FROM Books'''
    cur.execute(statement)
    search_result = []
    for row in cur:
        search_result.append(BestSeller(row))
    return render_template('bestsellers_result.html', result=search_result)

@app.route('/mostpopular')
def most_popular():
    return render_template('mostpopular.html', list=most_popular_list)

@app.route('/mostpopular/confirm', methods=['POST'])
def mp_search():
    category = request.form['category']
    time = request.form['time']
    main.nyt_mostpopular_search(category, time)
    return redirect('/mostpopular/results')

@app.route('/mostpopular/results')
def most_popular_results():
    conn = sqlite3.connect(main.DBNAME)
    cur = conn.cursor()
    statement = 'SELECT title, url, published_date, abstract FROM Most_popular'
    cur.execute(statement)
    search_result = []
    for row in cur:
        search_result.append(MostPopular(row))
    return render_template('mostpopular_result.html', result=search_result)

if __name__ == '__main__':
    app.run(debug=True)


from typing import Dict, Optional

from boa3_test.test_drive.neoxp.command.neoexpresscommand.neoexpresscommand import NeoExpressCommand

__all__ = ['CreateCommand']

class CreateCommand(NeoExpressCommand):
    def __init__(self, config_output: Optional[str] = None,
                 node_count: int = None,
                 address_version: int = None,
                 force: bool = False):

        if node_count not in [1, 4, 7]:  # allowed values for node count
            node_count = None

        self.config_output = config_output
        self.node_count = node_count
        self.address_version = address_version
        self.force = force

        command_id = 'create'
        args = []
        if isinstance(config_output, str):
            args.append(config_output)

        super().__init__(command_id, args)

    def _get_options(self) -> Dict[str, str]:
        options = super()._get_options()

        if isinstance(self.address_version, int):
            options['--count'] = str(self.address_version)
        if isinstance(self.address_version, int):
            options['--address-version'] = str(self.address_version)
        if self.force:
            options['--force'] = ''

        return options


#!/usr/bin/env python
# mypy: ignore-errors
import aoc
import logging
import pprint

logger = logging.getLogger("Part")

class Part1(aoc.Part):
    @staticmethod
    def logic(inp):
        # parsing
        tiles = {}
        for line in inp:
            if "Tile" in line:
                current_tile_id = int(line[5:-1])
                tiles[current_tile_id] = {}
                y = 0
            else:
                for x, char in enumerate(line):
                    if char == "#":
                        tiles[current_tile_id][(x, y)] = 1
                    elif char == ".":
                        tiles[current_tile_id][(x, y)] = 0
                    else:
                        raise ValueError(f"Unexpected character {char}")
                y += 1

        # building edge list for each tile, moving in a clockwise direction
        # this includes reverse directions
        tile_edges = {}
        for tile_id, tile in tiles.items():
            edges = []
            edge = []

            # top edge
            for x in range(10):
                edge.append(tiles[tile_id][(x, 0)])
            edges.append(edge)
            edges.append(list(reversed(edge)))

            edge = []
            # bottom edge
            for x in range(9, -1, -1):
                edge.append(tiles[tile_id][(x, 9)])
            edges.append(edge)
            edges.append(list(reversed(edge)))

            edge = []
            # right edge
            for y in range(10):
                edge.append(tiles[tile_id][(9, y)])
            edges.append(edge)
            edges.append(list(reversed(edge)))

            edge = []
            # left edge
            for y in range(9, -1, -1):
                edge.append(tiles[tile_id][(0, y)])
            edges.append(edge)
            edges.append(list(reversed(edge)))

            tile_edges[tile_id] = edges

        # finding matched sides
        tile_matches = {}
        for tile_id, edges in tile_edges.items():
            matching_edges = 0
            for edge in edges:
                for match_tile_id, match_edges in tile_edges.items():
                    if edge in match_edges:
                        matching_edges += 1
            # logger.debug(f"Tile {tile_id} - Matching edges: {matching_edges}")
            tile_matches[tile_id] = matching_edges

        min_match_tile_ids = [
            tile_id
            for tile_id, match_number in tile_matches.items()
            if match_number == min(tile_matches.values())
        ]
        id_mult = 1
        # logger.debug(
        #     f"{len(min_match_tile_ids)} with match number of {min(tile_matches.values())}"
        # )
        for match_number in min_match_tile_ids:
            id_mult = id_mult * match_number
        return id_mult

def print_tile(tile_id, tile):
    print_str = f"Tile: {tile_id}\n"
    x_coords = [key[0] for key, value in tile.items()]
    y_coords = [key[1] for key, value in tile.items()]
    for y in range(min(y_coords), max(y_coords) + 1):
        for x in range(min(x_coords), max(x_coords) + 1):
            value = tile[(x, y)]
            if value == 1:
                print_str = print_str + "#"
            elif value == 0:
                print_str = print_str + "."
            else:
                raise ValueError(f"Unexpected value {value}")
        print_str = print_str + "\n"
    return print_str

class Part2(aoc.Part):
    @staticmethod
    def logic(inp):
        # parsing
        tiles = {}
        for line in inp:
            if "Tile" in line:
                current_tile_id = int(line[5:-1])
                tiles[current_tile_id] = {}
                y = 0
            else:
                for x, char in enumerate(line):
                    if char == "#":
                        tiles[current_tile_id][(x, y)] = 1
                    elif char == ".":
                        tiles[current_tile_id][(x, y)] = 0
                    else:
                        raise ValueError(f"Unexpected character {char}")
                y += 1

        # building edge list for each tile, moving in a clockwise direction
        # this includes reverse directions
        tile_edges = {}
        for tile_id, tile in tiles.items():
            edges = []

            # first letter is cardinal direction of edge (N, E, S, W)
            # second letter is normal or reverse (N, R)
            # top edge
            edge = []
            for x in range(10):
                edge.append(tiles[tile_id][(x, 0)])
            edges.append({"edge": edge, "orientation": 0, "flipped": False})
            flipped_edge = edge.copy()
            flipped_edge.reverse()
            edges.append({"edge": flipped_edge, "orientation": 0, "flipped": True})

            # bottom edge
            edge = []
            for x in range(9, -1, -1):
                edge.append(tiles[tile_id][(x, 9)])
            edges.append({"edge": edge, "orientation": 180, "flipped": False})
            flipped_edge = edge.copy()
            flipped_edge.reverse()
            edges.append({"edge": flipped_edge, "orientation": 180, "flipped": True})

            # right edge
            edge = []
            for y in range(10):
                edge.append(tiles[tile_id][(9, y)])
            edges.append({"edge": edge, "orientation": 90, "flipped": False})
            flipped_edge = edge.copy()
            flipped_edge.reverse()
            edges.append({"edge": flipped_edge, "orientation": 270, "flipped": True})

            # left edge
            edge = []
            for y in range(9, -1, -1):
                edge.append(tiles[tile_id][(0, y)])
            edges.append({"edge": edge, "orientation": 270, "flipped": False})
            flipped_edge = edge.copy()
            flipped_edge.reverse()
            edges.append({"edge": flipped_edge, "orientation": 90, "flipped": True})

            tile_edges[tile_id] = edges

        # Starting with the lowest ID tile and building orientation and location map
        tile_locations = {}
        starting_tile_id = min(tiles)
        unset_tile_ids = list(tile_edges.keys())
        unset_tile_ids.remove(starting_tile_id)
        set_tile_ids = [starting_tile_id]
        current_tile = {
            "coords": (0, 0),
            "orientation": 0,  # 0 is N, 90 is E, 180 is S
            "flipped": False,
        }
        tile_locations[starting_tile_id] = current_tile
        while len(unset_tile_ids) > 0:
            for index in range(len(set_tile_ids) - 1, -1, -1):
                current_tile_id = set_tile_ids[index]
                current_tile = tile_locations[current_tile_id]
                # logging.debug(f"Now matching {current_tile_id}")
                for edge in tile_edges[current_tile_id]:
                    if edge["flipped"] == current_tile["flipped"]:
                        for matching_tile_id in unset_tile_ids:
                            for matching_edge in tile_edges[matching_tile_id]:
                                if edge["edge"] == matching_edge["edge"]:
                                    # logger.debug(
                                    #     f"\nmatch {current_tile_id} ({edge})\n with {matching_tile_id} ({matching_edge})"
                                    # )

                                    orientation = (
                                        edge["orientation"]
                                        + matching_edge["orientation"]
                                        + current_tile["orientation"]
                                        + 180
                                    ) % 360

                                    if (
                                        edge["orientation"]
                                        + current_tile["orientation"]
                                    ) % 360 == 0:
                                        coords = (
                                            current_tile["coords"][0],
                                            current_tile["coords"][1] - 1,
                                        )
                                    elif (
                                        edge["orientation"]
                                        + current_tile["orientation"]
                                    ) % 360 == 90:
                                        coords = (
                                            current_tile["coords"][0] + 1,
                                            current_tile["coords"][1],
                                        )
                                    elif (
                                        edge["orientation"]
                                        + current_tile["orientation"]
                                    ) % 360 == 180:
                                        coords = (
                                            current_tile["coords"][0],
                                            current_tile["coords"][1] + 1,
                                        )
                                    elif (
                                        edge["orientation"]
                                        + current_tile["orientation"]
                                    ) % 360 == 270:
                                        coords = (
                                            current_tile["coords"][0] - 1,
                                            current_tile["coords"][1],
                                        )
                                    else:
                                        raise ValueError(current_tile["orientation"])

                                    flipped = not matching_edge["flipped"]
                                    tile_locations[matching_tile_id] = {
                                        "coords": coords,
                                        "orientation": orientation,
                                        "flipped": flipped,
                                    }
                                    set_tile_ids.append(matching_tile_id)
                                    unset_tile_ids.remove(matching_tile_id)
                del set_tile_ids[index]

        # Removing edges and building grid
        full_grid = {}
        mult = 8
        for tile_id, tile_info in tile_locations.items():
            tile = tiles[tile_id]
            if tile_info["flipped"]:
                tile = flip_tile_horizontal(tile)
            tile = rotate_tile_CW(tile, rotations=tile_info["orientation"] // 90)
            x_coords = [key[0] for key, value in tile.items()]
            y_coords = [key[1] for key, value in tile.items()]
            for y in range(min(y_coords) + 1, max(y_coords)):
                for x in range(min(x_coords) + 1, max(x_coords)):
                    x_val = x + tile_locations[tile_id]["coords"][0] * mult
                    y_val = y + tile_locations[tile_id]["coords"][1] * mult
                    full_grid[(x_val, y_val)] = tile[(x, y)]

        # normalizing grid to (0, 0) top left corner so rotations actually work
        x_shift = min([key[0] for key, value in full_grid.items()])
        y_shift = min([key[1] for key, value in full_grid.items()])
        full_grid = {
            (x - x_shift, y - y_shift): value for (x, y), value in full_grid.items()
        }

        # converting sea monster to dictionary coords
        # only need the # symbols
        sea_monster_str = [
            "                  # ",
            "#    ##    ##    ###",
            " #  #  #  #  #  #   ",
        ]
        sea_monster = {}
        for y, line in enumerate(sea_monster_str):
            for x, char in enumerate(line):
                if char == "#":
                    sea_monster[(x, y)] = 1

        # checking each orientation for sea monsters
        x_size = max([key[0] for key, value in full_grid.items()])
        y_size = max([key[1] for key, value in full_grid.items()])
        total_sea_monsters = 0
        for i in range(2):
            for j in range(4):
                for y in range(y_size + 1):
                    for x in range(x_size + 1):
                        monster = True
                        for monster_x, monster_y in sea_monster.keys():
                            value = full_grid.get((x + monster_x, y + monster_y), 0)
                            if value == 0:
                                monster = False
                        if monster:
                            total_sea_monsters += 1
                            logger.debug(
                                f"Found a sea monster in {i}, {j}. Total {total_sea_monsters}"
                            )

                # rotating for next round
                full_grid = rotate_tile_CW(full_grid)
            # flipping for next round
            full_grid = flip_tile_horizontal(full_grid)

        waves = sum(full_grid.values()) - total_sea_monsters * sum(sea_monster.values())
        return waves

def rotate_tile_CW(tile, rotations=1):
    rot_tile = tile.copy()
    temp_tile = tile.copy()
    for i in range(rotations):
        x_coords = [key[0] for key, value in temp_tile.items()]
        y_coords = [key[1] for key, value in temp_tile.items()]
        min_x = min(x_coords)
        max_x = max(x_coords)
        min_y = min(y_coords)
        max_y = max(y_coords)
        for y in range(min_y, max_y + 1):
            for x in range(min_x, max_x + 1):
                rot_tile[(max_y - y, x)] = temp_tile[(x, y)]
        temp_tile = rot_tile.copy()
    return rot_tile

def flip_tile_horizontal(tile):
    rot_tile = {}
    x_coords = [key[0] for key, value in tile.items()]
    y_coords = [key[1] for key, value in tile.items()]
    min_x = min(x_coords)
    max_x = max(x_coords)
    min_y = min(y_coords)
    max_y = max(y_coords)
    for y in range(min_y, max_y + 1):
        for x in range(min_x, max_x + 1):
            rot_tile[(max_x - x, y)] = tile[(x, y)]
    return rot_tile

if __name__ == "__main__":
    day_number = 20
    test_input = [
        "Tile 2311:",
        "..##.#..#.",
        "##..#.....",
        "#...##..#.",
        "####.#...#",
        "##.##.###.",
        "##...#.###",
        ".#.#.#..##",
        "..#....#..",
        "###...#.#.",
        "..###..###",
        "",
        "Tile 1951:",
        "#.##...##.",
        "#.####...#",
        ".....#..##",
        "#...######",
        ".##.#....#",
        ".###.#####",
        "###.##.##.",
        ".###....#.",
        "..#.#..#.#",
        "#...##.#..",
        "",
        "Tile 1171:",
        "####...##.",
        "#..##.#..#",
        "##.#..#.#.",
        ".###.####.",
        "..###.####",
        ".##....##.",
        ".#...####.",
        "#.##.####.",
        "####..#...",
        ".....##...",
        "",
        "Tile 1427:",
        "###.##.#..",
        ".#..#.##..",
        ".#.##.#..#",
        "#.#.#.##.#",
        "....#...##",
        "...##..##.",
        "...#.#####",
        ".#.####.#.",
        "..#..###.#",
        "..##.#..#.",
        "",
        "Tile 1489:",
        "##.#.#....",
        "..##...#..",
        ".##..##...",
        "..#...#...",
        "#####...#.",
        "#..#.#.#.#",
        "...#.#.#..",
        "##.#...##.",
        "..##.##.##",
        "###.##.#..",
        "",
        "Tile 2473:",
        "#....####.",
        "#..#.##...",
        "#.##..#...",
        "######.#.#",
        ".#...#.#.#",
        ".#########",
        ".###.#..#.",
        "########.#",
        "##...##.#.",
        "..###.#.#.",
        "",
        "Tile 2971:",
        "..#.#....#",
        "#...###...",
        "#.#.###...",
        "##.##..#..",
        ".#####..##",
        ".#..####.#",
        "#..#.#..#.",
        "..####.###",
        "..#.#.###.",
        "...#.#.#.#",
        "",
        "Tile 2729:",
        "...#.#.#.#",
        "####.#....",
        "..#.#.....",
        "....#..#.#",
        ".##..##.#.",
        ".#.####...",
        "####.#.#..",
        "##.####...",
        "##..#.##..",
        "#.##...##.",
        "",
        "Tile 3079:",
        "#.#.#####.",
        ".#..######",
        "..#.......",
        "######....",
        "####.#..#.",
        ".#...#.##.",
        "#.#####.##",
        "..#.###...",
        "..#.......",
        "..#.###...",
    ]

    part_1 = Part1(
        day_number=day_number,
        part=1,
        test_input=test_input,
        test_answer=20899048083289,
    )
    part_1.submit_answer()

    part_2 = Part2(
        day_number=day_number,
        part=2,
        test_input=test_input,
        test_answer=273,
    )
    part_2.submit_answer()


import re

def input() -> str:
    with open('input.txt', 'r') as f:
        return f.read()

def rockoff_map(input: str) -> int:
    return {
        "A": 1,
        "B": 2,
        "C": 3,
        "X": 1,
        "Y": 2,
        "Z": 3,
    }[input]

def compute_score(opponent: str, player: str) -> int:
    base = rockoff_map(player)
    if (opponent, player) in [("A", "Y"), ("B", "Z"), ("C", "X")]:
        return 6 + base
    if (opponent, player) in [("A", "X"), ("B", "Y"), ("C", "Z")]:
        return 3 + base
    if (opponent, player) in [("A", "Z"), ("B", "X"), ("C", "Y")]:
        return base

def main():
    input_str = input()
    total_score = 0
    r = re.compile(r'(?P<opponent>\w)\s(?P<player>\w)')
    for line in input_str.splitlines():
        if line:
            match = r.search(line)
            total_score += compute_score(match.group('opponent'), match.group('player'))
    return total_score

if __name__ == "__main__":
    print(main())


import logging
import os

from PySide2 import QtGui, QtWidgets

logger = logging.getLogger(__name__)

from hyo2.abc.app.tabs.info.info_tab import InfoTab
from hyo2.abc.lib.helper import Helper

from hyo2.qc.qctools import app_info
from hyo2.qc.common import lib_info
from hyo2.unccalc.mainwin import MainWin as UncCalcMainWin
from hyo2.rori.mainwin import MainWin as RorIMainWin

class InfoWidget(InfoTab):

    def __init__(self, main_win: QtWidgets.QMainWindow):
        super().__init__(lib_info=lib_info, app_info=app_info,
                         with_online_manual=True,
                         with_offline_manual=True,
                         with_bug_report=True,
                         with_hydroffice_link=True,
                         with_ccom_link=True,
                         with_noaa_link=True,
                         with_unh_link=True,
                         with_license=True,
                         with_noaa_57=True,
                         with_ocs_email=True,
                         main_win=main_win)

        # RorI
        self.rori = None
        self.rori_action = QtWidgets.QAction(QtGui.QIcon(os.path.join(app_info.app_media_path, 'rori.png')),
                                             'Rock or Islet oracle', self)
        # rori_action.setShortcut('Alt+R')
        # noinspection PyUnresolvedReferences
        self.rori_action.triggered.connect(self.show_rori)
        self.toolbar.insertAction(self.noaa_support_action, self.rori_action)

        # UNC calc
        self.unc_calc = None
        self.unc_calc_action = QtWidgets.QAction(QtGui.QIcon(os.path.join(app_info.app_media_path, 'unccalc.png')),
                                                 'Uncertainty Calculator', self)
        self.unc_calc_action.setShortcut('Alt+U')
        # noinspection PyUnresolvedReferences
        self.unc_calc_action.triggered.connect(self.show_unc_calc)
        self.toolbar.insertAction(self.rori_action, self.unc_calc_action)

    def show_unc_calc(self):
        self.change_url(Helper(lib_info=lib_info).web_url("unc_calc"))
        self.unc_calc = UncCalcMainWin(self)
        self.unc_calc.show()

    def show_rori(self):
        self.change_url(Helper(lib_info=lib_info).web_url("rori"))
        self.rori = RorIMainWin(self)
        self.rori.show()


#!/usr/bin/env python3

# source: https://github.com/orestisf1993/i3blocks/blob/master/blocks/playerctl-change.py
from gi.repository import Playerctl, GLib
import sys
import signal

PLAYER_NAME = sys.argv[1]
TIMEOUT = 2

def player_is_running(player_name):
    return Playerctl.Player(player_name=player_name).props.metadata is not None

def handler(signum, frame):
    raise TimeoutError

def on_metadata(player, e=None):
    e = player.props.metadata if e is None else e
    if player_is_running(PLAYER_NAME):
        print('{artist}\n{title}\n{icon}'.format(artist=e['xesam:artist'][0], title=e['xesam:title'], icon=e['mpris:artUrl']))
    sys.exit(0)

if not player_is_running(PLAYER_NAME):
    sys.exit()

#artist = player.props.metadata['xesam:artist']
#title = player.props.metadata['xesam:title']

player = Playerctl.Player(player_name=PLAYER_NAME)
player.on('metadata', on_metadata)

# wait for events
main = GLib.MainLoop()
#signal.signal(signal.SIGALRM, lambda n, f: main.quit())
#signal.alarm(1)
GLib.timeout_add_seconds(TIMEOUT, lambda: sys.exit(0))
main.run()


from accelerate import FullyShardedDataParallelPlugin, Accelerator
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
import torch
from datasets import load_dataset, Dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from sklearn.model_selection import train_test_split
import transformers
from datetime import datetime
from datasets import load_dataset

dataset = load_dataset("paultrust100/ura_summarization")
train_data = dataset["train"]

import pandas as pd
text_train = train_data['text']
label_train = train_data['label']

df_train = pd.DataFrame()
df_train['text'] = text_train
df_train['label'] =  label_train

train, test = train_test_split(df_train,test_size=0.1)

def create_fine_tuning_dataset(df):
    rows = []
    for i, row in df.iterrows():
      rows.append({"input":f"{row.text}", 'output':f"{row.label}"})

    return pd.DataFrame(rows)

df_json = create_fine_tuning_dataset(train)
test_json = create_fine_tuning_dataset(test)

df_json.to_json('/home/ptrust/experiments/hugging_data/train.jsonl', orient='records', lines=True)
test_json.to_json('/home/ptrust/experiments/hugging_data/test.jsonl', orient='records', lines=True)

train_dataset = load_dataset('json', data_files='/home/ptrust/experiments/hugging_data/train.jsonl', split='train')
eval_dataset = load_dataset('json', data_files='/home/ptrust/experiments/hugging_data/test.jsonl', split='train')
fsdp_plugin = FullyShardedDataParallelPlugin(
    state_dict_config=FullStateDictConfig(offload_to_cpu=True, rank0_only=False),
    optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=False),
)

accelerator = Accelerator(fsdp_plugin=fsdp_plugin)

def formatting_func(example):
    text = f"###  Summarize the following text\n\n Text: {example['input']}\n ### Summary: {example['output']}"
    return text

base_model_id = "mistralai/Mistral-7B-v0.1"
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)

model = AutoModelForCausalLM.from_pretrained(base_model_id, quantization_config=bnb_config)

tokenizer = AutoTokenizer.from_pretrained(
    base_model_id,
    padding_side="left",
    add_eos_token=True,
    add_bos_token=True,
)
tokenizer.pad_token = tokenizer.eos_token

max_length = 512 # This was an appropriate max length for my dataset

def generate_and_tokenize_prompt2(prompt):
    result = tokenizer(
        formatting_func(prompt),
        truncation=True,
        max_length=max_length,
        padding="max_length",
    )
    result["labels"] = result["input_ids"].copy()
    return result

tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt2)
tokenized_val_dataset = eval_dataset.map(generate_and_tokenize_prompt2)

from peft import prepare_model_for_kbit_training

model.gradient_checkpointing_enable()
model = prepare_model_for_kbit_training(model)

def print_trainable_parameters(model):
    """
    Prints the number of trainable parameters in the model.
    """
    trainable_params = 0
    all_param = 0
    for _, param in model.named_parameters():
        all_param += param.numel()
        if param.requires_grad:
            trainable_params += param.numel()
    print(
        f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
    )

print(model)

from peft import LoraConfig, get_peft_model

config = LoraConfig(
    r=32,
    lora_alpha=64,
    target_modules=[
        "q_proj",
        "k_proj",
        "v_proj",
        "o_proj",
        "gate_proj",
        "up_proj",
        "down_proj",
        "lm_head",
    ],
    bias="none",
    lora_dropout=0.05,  # Conventional
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, config)
print_trainable_parameters(model)

# Apply the accelerator. You can comment this out to remove the accelerator.
model = accelerator.prepare_model(model)

if torch.cuda.device_count() > 1: # If more than 1 GPU
    model.is_parallelizable = True
    model.model_parallel = True

project = "journal-finetune"
base_model_name = "llama2-7b"
run_name = base_model_name + "-" + project
output_dir = "./" + run_name

tokenizer.pad_token = tokenizer.eos_token

trainer = transformers.Trainer(
    model=model,
    train_dataset=tokenized_train_dataset,
    eval_dataset=tokenized_val_dataset,
    args=transformers.TrainingArguments(
        output_dir=output_dir,
        per_device_train_batch_size=24,
        gradient_accumulation_steps=24,
        num_train_epochs=5,
        learning_rate=2.5e-5, # Want a small lr for finetuning
        bf16=True,
        logging_dir="./logs",        # Directory for storing logs             # Evaluate and save checkpoints every 50 steps
        do_eval=True,                # Perform evaluation at the end of training
        report_to="none",           # Comment this out if you don't want to use weights & baises
        run_name=f"{run_name}-{datetime.now().strftime('%Y-%m-%d-%H-%M')}"          # Name of the W&B run (optional)
    ),
    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),
)

model.config.use_cache = False  # silence the warnings. Please re-enable for inference!
trainer.train()

def prepare_prompts(example):
    texts = example["text"]
    labels = example["text_label"]

    example[
        "prompts"
    ] = f"""
   "###  Summarize the following text\n\n Text: {texts}\n ### Summary: """
    return example
#data = load_dataset("Abirate/english_quotes")
#data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
dataset = load_dataset("paultrust100/ura_summarization")
train_data = dataset["test"]

import pandas as pd
text_train = train_data['text']
label_train = train_data['label']

df_train = pd.DataFrame()
df_train['text'] = text_train
df_train['text_label'] =  label_train

texts = df_train['text'].tolist()
labels =  df_train['text_label'].tolist()
#df_train = sample_dataset( df_train, samples_per_class=100)
#df_train  =  df_train.sample(frac=1).reset_index(drop=True)

dataset_split = Dataset.from_pandas(df_train)
#dataset_split = dataset_blogs.train_test_split(test_size=0.00001, seed=1234)

data =  dataset_split.map(
  prepare_prompts
)
texts = data['prompts']
labels = data['text_label']
pred_summary = []

model.config.use_cache = False  # silence the warnings. Please re-enable for inference!
model.eval()
for i in texts:
    with torch.cuda.amp.autocast():
        batch = tokenizer(i, return_tensors="pt")
        output_tokens = model.generate(**batch, max_new_tokens=20)

    summary =  tokenizer.decode(output_tokens[0], skip_special_tokens=True)
    print(summary)
    pred_summary.append( summary)

df_results_summary = pd.DataFrame()
df_results_summary['text'] = texts
df_results_summary['human_summary'] = labels
df_results_summary['generated_summary'] = pred_summary

df_results_summary.to_csv('/home/ptrust/experiments/hugging_data/ura_summary.csv')


"""`get_data_dir`, `clear_data_dir`, `fetch_url`"""
import sys
from os import environ, makedirs
from os.path import exists, expanduser, join
from shutil import rmtree
import hashlib
import ssl
from urllib.request import urlretrieve

def get_data_dir(data_dir=None):
    """Return the path of the pulse2percept data directory

    This directory is used to store the datasets retrieved by the data fetch
    utility functions to avoid downloading the data several times.

    By default, this is set to a directory called 'pulse2percept_data' in the
    user home directory.
    Alternatively, it can be set by a ``PULSE2PERCEPT_DATA`` environment
    variable or set programmatically by specifying a path.

    If the directory does not already exist, it is automatically created.

    .. versionadded:: 0.6

    Parameters
    ----------
    data_dir : str or None
        The path to the pulse2percept data directory.

    """
    if data_dir is None:
        data_dir = environ.get('PULSE2PERCEPT_DATA',
                               join('~', 'pulse2percept_data'))
    data_dir = expanduser(data_dir)
    if not exists(data_dir):
        makedirs(data_dir)
    return data_dir

def clear_data_dir(data_dir=None):
    """Delete all content in the data directory

    By default, this is set to a directory called 'pulse2percept_data' in the
    user home directory.
    Alternatively, it can be set by a ``PULSE2PERCEPT_DATA`` environment
    variable or set programmatically by specifying a path.

    .. versionadded:: 0.6

    Parameters
    ----------
    data_dir : str or None
        The path to the pulse2percept data directory.

    """
    data_dir = get_data_dir(data_dir)
    rmtree(data_dir)

def _sha256(path):
    """Calculate the sha256 hash of the file at path."""
    sha256hash = hashlib.sha256()
    chunk_size = 8192
    with open(path, "rb") as f:
        while True:
            buffer = f.read(chunk_size)
            if not buffer:
                break
            sha256hash.update(buffer)
    return sha256hash.hexdigest()

def _report_hook(count, block_size, total_size):
    """Display a progress bar for ``urlretrieve``"""
    progress_size = int(count * block_size)
    percent = min(100, int(count * block_size * 100 / total_size))
    sys.stdout.write(f"\rDownloading {progress_size / (1024 * 1024):.1f}"
                     f"/{total_size / (1024 * 1024):.1f} MB ({percent}%)")
    sys.stdout.flush()

def fetch_url(url, file_path, progress_bar=_report_hook, remote_checksum=None):
    """Download a remote file

    Fetch a dataset pointed to by ``url``, check its SHA-256 checksum for
    integrity, and save it to ``file_path``.

    .. versionadded:: 0.6

    Parameters
    ----------
    url : string
        URL of file to download
    file_path: string
        Path to the local file that will be created
    progress_bar : func callback, optional
        A callback to a function ``func(count, block_size, total_size)`` that
        will display a progress bar.
    remote_checksum : str, optional
        The expected SHA-256 checksum of the file.

    """
    # Hacky way to keep using ulretrieve without SSL verification:
    ssl._create_default_https_context = ssl._create_unverified_context
    urlretrieve(url, file_path, progress_bar)
    checksum = _sha256(file_path)
    if remote_checksum != None and remote_checksum != checksum:
        raise IOError(f"{file_path} has an SHA256 checksum ({checksum}) "
                      f"differing from expected ({remote_checksum}), "
                      f"file may be corrupted.")


from datetime import datetime, time
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from django.utils import timezone
from typing import Any
from django.db.models.query import QuerySet
from django.shortcuts import render, redirect, HttpResponse, get_object_or_404
from django.contrib import messages
from django.shortcuts import render
from django.views.generic import ListView, FormView, View, DeleteView
from django.urls import reverse, reverse_lazy

from hotel.room_status import RoomStatus
from .forms import AvailabilityForm

from bookings.booking_functions.availability import check_availability
from bookings.booking_functions.get_available_rooms import get_available_rooms
from bookings.booking_functions.book_room import book_room

from hotel.room_functions.get_room_type import get_room_type

from bookings.models import Booking
from hotel.models import CheckedInState, CheckedOutState, Room

from django.views.generic import DeleteView

# Create your views here.
class CheckInView(View):
    def get(self, request, room_id):
        room = get_object_or_404(Room, id=room_id)
        return render(request, 'check_in_success.html', {'room': room})

    def post(self, request, room_id):
        room = get_object_or_404(Room, id=room_id)

        room_bookings = Booking.objects.filter(room=room)

        if not room_bookings:
            return HttpResponseBadRequest("No bookings found for this room.")

        current_date = timezone.now().date()
        current_time = timezone.now().time()
        check_in_time = time(16, 0, 0)  # 4 PM set check-in time

        matching_booking = room_bookings.filter(check_in_date__date=current_date).first()

        if not matching_booking:
            return HttpResponseBadRequest("Cannot check in: This booking is not for today.")
        elif matching_booking.check_in_date.time() < check_in_time:
            return HttpResponseBadRequest("Cannot check in: Check-in time is before 4 PM.")

        if room.room_status != RoomStatus.CLEANED.value:
            return HttpResponseBadRequest("Cannot check in: Room is not clean. Please contact a staff member.")

        if room.room_status == RoomStatus.CHECKED_IN.value:
            return HttpResponseBadRequest("You've already checked in!")

        # Perform the check-in state transition
        checked_in_state = CheckedInState()
        points_earned = checked_in_state.handle(room)

        if points_earned is not None:
            # Assuming successful check-in scenario where points are earned
            room.save()
            return render(request, 'check_in_success.html', {'room': room, 'points_earned': points_earned})
        else:
            # Handle error scenario where no booking is found for today
            return HttpResponseBadRequest("Error: No booking found for today.")

# check out view
class CheckOutView(View):
    def get(self, request, room_id):
        room = get_object_or_404(Room, id=room_id)
        return render(request, 'check_out_success.html', {'room': room})

    def post(self, request, room_id):
        room = get_object_or_404(Room, id=room_id)

        checked_out_state = CheckedOutState()
        checked_out_state.handle(room)

        room.save()
        return render(request, 'check_out_success.html', {'room': room})

# booking list view. shows bookings
class BookingListView(ListView):
    model = Booking
    template_name = 'booking_list_view.html'

    def get_queryset(self, *args, **kwargs):
        if self.request.user.is_staff:
            booking_list = Booking.objects.all()
            return booking_list
        else:
            booking_list = Booking.objects.filter(user=self.request.user)
            return booking_list

#     actual room view
class RoomDetailView(View):
    def get(self, request, *args, **kwargs):
        room_type = self.kwargs.get('type', None)
        room_type_name = get_room_type(room_type)
        form = AvailabilityForm()

        if room_type_name is not None:
            context = {
                'room_type': room_type_name,
                'form': form,
            }
            return render(request, 'room_detail_view.html', context)
        else:
            return HttpResponse('Invalid room type')

    def post(self, request, *args, **kwargs):
        room_type = self.kwargs.get('type', None)
        form = AvailabilityForm(request.POST)

        if form.is_valid():
            data = form.cleaned_data
            check_in_time = data['check_in_date']
            check_out_time = data['check_out_date']

            # Set the time to 4:00 PM for both check-in and check-out
            check_in_time = check_in_time.replace(hour=16, minute=0, second=0)
            check_out_time = check_out_time.replace(hour=16, minute=0, second=0)

            if check_in_time.date() < timezone.now().date():
                return HttpResponse('Check-in date cannot be in the past.')

            if check_out_time <= check_in_time:
                return HttpResponse('Check-out date should be after the check-in date.')

            available_rooms = get_available_rooms(room_type, check_in_time, check_out_time)

            if available_rooms:
                booking = book_room(request, available_rooms[0], check_in_time, check_out_time)

                formatted_check_in = check_in_time.strftime("%Y-%m-%d %H:%M:%S")
                formatted_check_out = check_out_time.strftime("%Y-%m-%d %H:%M:%S")

                context = {
                    'room_type': room_type,
                    'check_in': formatted_check_in,
                    'check_out': formatted_check_out,
                    'nights_stay': booking.nights_of_stay(),
                    'total_price': booking.apply_discount(),
                    'points_earned': booking.calculate_points_earned(),
                    'points_used': booking.calculate_points_deducted(),
                }

                # messages.success(
                #     self.request,
                #     f'Your booking for a {room_type} room from {formatted_check_in} to {formatted_check_out} has been confirmed! Thank you for choosing us.'
                # )

                # Fetch the hotel ID dynamically from the booked room or replace it with the correct logic
                hotel_id = None
                if booking and booking.room and booking.room.hotel:
                    hotel_id = booking.room.hotel.id

                if hotel_id:
                    room_list_url = reverse('hotel:RoomListView', args=[hotel_id])
                    return redirect('paypal-payment', booking_id=booking.id)
                    # return HttpResponseRedirect(room_list_url)
                else:
                    return HttpResponse('Hotel not found!')
            else:
                return HttpResponse('No rooms available for the selected dates. Please try a different room or date.')
        else:
            return HttpResponse('Form data is not valid.')

# booking confirmation view

class BookingConfirmationView(View):
    def get(self, request, room_id):
        booking = Booking.objects.get(pk=room_id)

        context = {
            'room_type': booking.get_room_type(),
            'check_in': booking.check_in_date,
            'check_out': booking.check_out_date,
            'nights_stay': booking.nights_of_stay(),
            'total_price': booking.calculate_price(),
            'points_earned': booking.calculate_points_earned(),
            'points_used': booking.calculate_points_deducted(),
        }

        print(context)
        print(booking.__dict__)

        return render(request, 'booking_confirmation.html', context)

# booking cancel view
class CancelBookingView(DeleteView):
    model = Booking
    template_name = 'booking_cancel_view.html'
    success_url = reverse_lazy('bookings:BookingListView')


import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage.filters.thresholding import threshold_isodata
from skimage.measure import regionprops, label
from pathlib import Path

total_pencil_number = 0

for image_path in sorted(Path.cwd().glob("./pencils/images/*.jpg")):
    image = plt.imread(image_path)

    # since sometimes there is a high consrast on the edges of the image
    # the easiest way to remove it is just to crop it
    image = image[40:-40, 40:-40]

    gray_img = rgb2gray(image)

    thresh = threshold_isodata(gray_img)
    binary = gray_img.copy() <= thresh

    labeled = label(binary)
    regions = regionprops(labeled)

    pencil_cnt = 0

    # just the magic numbers which make this thing work
    for i in range(len(regions)):
        if regions[i].eccentricity < 0.98 or \
        regions[i].equivalent_diameter <= 55.0:
            labeled[labeled == regions[i].label] = 0
        else:
            pencil_cnt += 1

    total_pencil_number += pencil_cnt

    # to see number of pencils for the current image
    # print(f"Number of pencils for {image_path.relative_to(Path.cwd())}: {pencil_cnt}")

print(f"Total number of pencils: {total_pencil_number}")


from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from employees.models import Employees
from employees.forms import EmployeeForm, DepartmentForm
from django.contrib.auth import logout
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required

# Create your views here.
def hello(request):
    return HttpResponse("Hello World")

def list(request):
    return HttpResponse("Employees list")

'''
def create(request):
    return HttpResponse("Create an employee")
'''

'''
def update(request, id):
    return HttpResponse("Update an employee with id="+ id)
'''

def view(request):
    name = request.GET.get('name') or "n/a"
    return HttpResponse("Viewing the employee by username=" + name)

@csrf_exempt
def api(request):
    name = request.POST.get("name") or "n/a"
    email = request.POST.get("email") or "n/a"
    return JsonResponse(
        {'name':name,
        'email' :email}
        )

def welcome(request):
    data = {'pagetitle' : 'wfTutorials', 'header' : "Welcome to wftutorials"}
    return render(request, 'employees/index.html', data)

def faq(request):
    myDogs = ["bobby", "pepper", "sugar"]
    data = {'show': None, 'dogs': myDogs}
    return render(request, 'employees/faq.html', data)

def help(request):
    return render(request, 'employees/help.html')

def saveemployee(request):
    emp = Employees()
    emp.firstname = "Wynton"
    emp.lastname = "frannklin"
    emp.email = "wf@gmail.com"
    emp.department = "IT"
    emp.age = "25"
    emp.employeeid = "005"
    try:
        emp.save()
        return HttpResponse("Employee saved")
    except Exception as e:
        return HttpResponse(e)

''' Object by primary key
def display(request):
    emp = Employees.objects.get(pk=1)
    return HttpResponse("Employee name is: " + emp.firstname +  " " + emp.lastname)
'''

def display(request):
    emp = Employees.objects.get(email="james@gmail.com")
    return HttpResponse("Employee name is: " + emp.firstname +  " " + emp.lastname)

def remove(request):
    emp = Employees.objects.get(email="james@gmail.com")
    try:
        emp.delete()
        return HttpResponse("object deleted")
    except Exception as e:
        return HttpResponse(e)

'''
def update(request):
    emp = Employees.objects.get(pk=1)
    emp.age = "27"
    try:
        emp.save()
        return HttpResponse("object age updated to " + emp.age)
    except Exception as e:
        return HttpResponse(e)
'''

@login_required
def create(request):
    if request.method == "POST":
        empForm = EmployeeForm(data=request.POST)
        if empForm.is_valid():
            empForm.save()
        return HttpResponse("Employee saved")
    else:
        empForm = EmployeeForm()
        return render(request,'employees/create.html', {'form':empForm})

def update(request, id):
    if request.method == "POST":
        emp = Employees.objects.get(pk=id)
        empForm = EmployeeForm(request.POST, instance=emp)
        if empForm.is_valid():
            empForm.save()
            return redirect(request.path)
    else:
        emp = Employees.objects.get(pk=id)
        empForm =  EmployeeForm(instance=emp)
        return render(request, 'employees/update.html',{'form':empForm})

def logout_view(request):
    logout(request)
    return HttpResponse("User logged out")

def profile(request):
    return render(request,'employees/profile.html',{'model':request.user})