# -*- coding: utf-8 -*-

import json
from base import Endpoint

__all__ = ['ServerEndpoint']

class ServerEndpoint( Endpoint ):

    @classmethod
    def servers( cls, client ):
        r = client.get('api/servers.json')
        return r['response']['servers']

    @classmethod
    def attach_volume( cls, client, server_list, volume_name,
            access_type='NFS', readonly='NO', force='NO' ):
        if 1 > len( server_list ):
            raise ValueError( 'empty server_list not allowed' )

        data = { 'id': '%s' % ','.join( server_list ),
                'volume_name': volume_name,
                'access_type': access_type,
                'readonly': readonly,
                'force': force }

        r = client.post( 'api/servers/{0}/volumes.json'.format( server_list[0] ),
                params=data )
        return server_list


import re

import six

from sevenbridges.meta.resource import Resource
from sevenbridges.meta.transformer import Transform
from sevenbridges.meta.fields import (
    HrefField, StringField, IntegerField, DictField
)

class App(Resource):
    """
    Central resource for managing apps.
    """
    _URL = {
        'query': '/apps',
        'get': '/apps/{id}',
        'get_revision': '/apps/{id}/{revision}',
        'create_revision': '/apps/{id}/{revision}/raw',
        'copy': '/apps/{id}/actions/copy',
        'raw': '/apps/{id}/raw'
    }
    href = HrefField()
    _id = StringField(read_only=True, name='id')
    project = StringField(read_only=True)
    name = StringField(read_only=True)
    revision = IntegerField(read_only=True)
    raw = DictField(read_only=False)

    @property
    def id(self):
        _id, _rev = self._id.rsplit('/', 1)
        if re.match('^\d*$', _rev):
            return _id
        else:
            return self._id

    def __str__(self):
        return six.text_type('<App: id={id}>'.format(id=self.id))

    @classmethod
    def query(cls, project=None, visibility=None, offset=None, limit=None,
              api=None):
        """
        Query (List) apps.
        :param visibility:
        :param project:
        :param offset: Pagination offset.
        :param limit: Pagination limit.
        :param api: Api instance.
        :return: collection object
        """
        if project:
            project = Transform.to_project(project)
        api = api or cls._API
        return super(App, cls)._query(url=cls._URL['query'], project=project,
                                      visibility=visibility,
                                      offset=offset, limit=limit, api=api)

    @classmethod
    def get_revision(cls, id, revision, api=None):
        """
        Get app revision.
        :param id: App identifier.
        :param revision: App revision
        :param api: Api instance.
        :return: App object.
        """
        api = api if api else cls._API
        app = api.get(url=cls._URL['get_revision'].format(
            id=id, revision=revision)).json()
        return App(api=api, **app)

    @classmethod
    def install_app(cls, id, raw, api=None):
        """
        Installs and app.
        :param id:  App identifier.
        :param raw: Raw cwl data.
        :param api: Api instance.
        :return: App object.
        """
        api = api if api else cls._API
        app = api.post(url=cls._URL['raw'].format(id=id), data=raw).json()
        app_wrapper = api.get(url=cls._URL['get'].format(
            id=app['sbg:id'])).json()
        return App(api=api, **app_wrapper)

    @classmethod
    def create_revision(cls, id, revision, raw, api=None):
        """
        Create a new app revision.
        :param id:  App identifier.
        :param revision: App revision.
        :param raw: Raw cwl object.
        :param api: Api instance.
        :return: App object.
        """

        api = api if api else cls._API
        app = api.post(url=cls._URL['create_revision'].format(
            id=id, revision=revision), data=raw).json()
        app_wrapper = api.get(
            url=cls._URL['get'].format(id=app['sbg:id'])).json()
        return App(api=api, **app_wrapper)

    def copy(self, project, name=None):
        """
        Copies the current app.
        :param project: Destination project.
        :param name: Destination app name.
        :return: Copied App object.
        """

        project = Transform.to_project(project)
        data = {
            'project': project
        }
        if name:
            data['name'] = name

        app = self._api.post(url=self._URL['copy'].format(id=self.id),
                             data=data).json()
        return App(api=self._api, **app)


import pytest
from medinify.scrapers import EverydayHealthScraper

def test_default_initialization():
    """
    Tests that when the new scraper object is initialized, the correct
    attributes are set (empty list[dict] 'reviews') and the attribute
    collect_urls (boolean) is false by default
    """
    scraper = EverydayHealthScraper()
    assert len(scraper.reviews) == 0
    assert not scraper.collect_urls

def test_initialization_parameters():
    """
    Tests that when a new EverydayHealth scraper object is initialized with a
    non default argument the correct attributes are set (empty list[dict] 'reviews')
    and that the collect_urls attribute (boolean) is set to true
    """
    scraper = EverydayHealthScraper(collect_urls=True)
    assert scraper.collect_urls

def test_incorrect_url():
    """
    Tests that the scrape_page function raises and assertion error when a url is
    entered with an incorrect domain name (not 'https://everydayhealth.com...')
    """
    scraper = EverydayHealthScraper()
    with pytest.raises(AssertionError):
        scraper.scrape_page('https://www.drugs.com/comments/aripiprazole/abilify.html?page=1')

def test_no_reviews():
    """
    Tests that the scrape page function returns 'None' when no reviews are
    found on the page
    """
    scraper = EverydayHealthScraper()
    returned = scraper.scrape_page('https://www.everydayhealth.com/drugs/triprolidine/reviews')
    assert not returned

def test_scrape_correct_review_data():
    """
    Tests to make sure that the last review in the scraped reviews list has
    the correct data when the scrape function is called
    (this data is from the oldest review of the drug)
    """
    scraper = EverydayHealthScraper(collect_urls=True)
    scraper.scrape('https://www.everydayhealth.com/drugs/ciclopirox-topical/reviews')
    assert scraper.reviews[-1]['comment'][:10] == 'After OVER'
    assert scraper.reviews[-1]['comment'][-10:] == 'inally hav'
    assert scraper.reviews[-1]['rating'] == 5
    assert scraper.reviews[-1]['date'] == '5/22/2015 4:18:19 AM'

def test_scrape_page_default_parameters():
    """
    Tests to make sure that calling the scrape_page function on a scraper object
    with a default parameter collects the correct types of data ('comment', 'rating',
    'date', and 'drug') and that the correct number of reviews were collected (20)
    """
    scraper = EverydayHealthScraper()
    scraper.scrape_page('https://www.everydayhealth.com/drugs/allegra/reviews')
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 4
    assert 'comment' in data_collected
    assert 'rating' in data_collected
    assert 'date' in data_collected
    assert 'drug' in data_collected
    assert len(scraper.reviews) == 20

def test_scrape_page_with_parameters():
    """
    Tests to make sure that calling the scrape_page function on a scraper object with a
    non-default parameter (collect_url true) collects the correct types of data
    ('comment', 'rating, 'date', 'drug', and 'url')
    """
    scraper = EverydayHealthScraper(collect_urls=True)
    scraper.scrape_page('https://www.everydayhealth.com/drugs/hydroxyzine/reviews')
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 5
    assert 'url' in data_collected

def test_scrape_empty_reviews():
    """
    Tests to make sure that the scrape function would discard the reviews
    of a scraper object that already has data collected in 'reviews'
    """
    scraper = EverydayHealthScraper()
    scraper.scrape('https://www.everydayhealth.com/drugs/phenadoz/reviews')
    num_reviews = len(scraper.reviews)
    scraper.scrape('https://www.everydayhealth.com/drugs/phenadoz/reviews')
    assert num_reviews == len(scraper.reviews)

def test_scrape_invalid_url_no_title():
    """
    Tests that when the scrape function is called on a url that lacks a title
    (invalid url), it raises an AttributeError and returns 0
    """
    scraper = EverydayHealthScraper()
    returned = scraper.scrape('https://www.everydayhealth.com/drugs/')
    assert returned == 0

def test_scrape_default_parameter():
    """
    Tests that, when calling the scrape function with a scraper with default parameters,
    the correct types of data are stored in the 'reviews' attribute and that the
    correct number of reviews are collected (more than 20, this proves that it's
    scraping multiple pages)
    """
    scraper = EverydayHealthScraper()
    scraper.scrape('https://www.everydayhealth.com/drugs/gabapentin/reviews')
    assert len(scraper.reviews) > 20
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 4
    assert 'comment' in data_collected
    assert 'rating' in data_collected
    assert 'date' in data_collected
    assert 'drug' in data_collected

def test_scrape_with_parameters():
    """
    Tests that, when calling the scrape function with a scraper of non-default parameters, the
    correct types of data are stored in the 'reviews' attribute
    """
    scraper = EverydayHealthScraper(collect_urls=True)
    scraper.scrape('https://www.everydayhealth.com/drugs/gabapentin/reviews')
    assert len(scraper.reviews) > 20
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 5
    assert 'url' in data_collected

def test_scrape_assert_title_error():
    """
    Tests that when the scrape function is called with an invalid url that does have a
    title, but the title is wrong (doesn't have the phrase 'Drug Reviews') that an AssertionError
    is raised and the function returns 0
    """
    scraper = EverydayHealthScraper()
    returned = scraper.scrape('https://www.everydayhealth.com/drugs/')
    assert returned == 0

def test_scrape_no_reviews():
    """
    Tests that the scrape function works for page with no reviews
    """
    scraper = EverydayHealthScraper()
    scraper.scrape('https://www.everydayhealth.com/drugs/triprolidine/reviews')
    assert len(scraper.reviews) == 0

def test_get_url_real_drug_name():
    """
    Tests that the get_url function returns the correct url for a standard drug name ('dupixent')
    """
    scraper = EverydayHealthScraper()
    url = scraper.get_url('dupixent')
    assert url == 'https://www.everydayhealth.com/drugs/dupixent/reviews'

def test_url_fake_drug_name():
    """
    Tests tha the get_url function returns 'None' for a drug name that does not have a review
    page
    """
    scraper = EverydayHealthScraper()
    url = scraper.get_url('garbage')
    assert not url

def test_drug_name_with_space():
    """
    Tests that the get_url function returns the correct url for a drug name
    that includes a space
    """
    scraper = EverydayHealthScraper()
    url = scraper.get_url('Mucinex Allergy')
    assert url == 'https://www.everydayhealth.com/drugs/mucinex-allergy/reviews'

def test_short_drug_name():
    """
    Tests that the get_url function does not search for drug names shorter than 4 characters
    """
    scraper = EverydayHealthScraper()
    url = scraper.get_url('ACE')
    assert not url


from ..users.endpoint import createCustomer, getCustomerToken
from auth.middleware import VerifyTokenRoute
from datetime import datetime
from db.usersDAO import UsersDAO
from fastapi import APIRouter, Depends
from fastapi.requests import Request
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBearer
from logs.setup import logger
from models.users.model import Customer
import json

router = APIRouter(route_class=VerifyTokenRoute)
token_auth_scheme = HTTPBearer()

@router.post("/login")
async def login(authorization: str = Depends(token_auth_scheme), request: Request = None):
    logger.info(
        "INFO    - ["
        + str(datetime.now())
        + "]: "
        + str(request.client.host)
        + ":"
        + str(request.client.port)
        + " - "
        + str(request.method)
        + " - "
        + str(request.url.path)
        + " - Doing loging..."
    )
    requestData = await request.json()
    customer = json.loads(request.headers["customer"])
    customer = Customer(**customer)

    magento_token = request.headers.get("api-authorization")
    username = customer.username

    user = UsersDAO.get_user_data_by_username(username)
    if user is None:
        customerId = createCustomer(customer, requestData["password"], request)["id"]

    else:
        customerId = user[0]

    try:
        moodle_token = getCustomerToken(customer, requestData["password"], request)
    except:
        moodle_token = ""
        logger.info(
            "ERROR   - ["
            + str(datetime.now())
            + "]: "
            + str(request.client.host)
            + ":"
            + str(request.client.port)
            + " - "
            + str(request.method)
            + " - "
            + str(request.url.path)
            + " - Error generating moodle token"
        )

    UsersDAO.create_and_update_user(customerId, username, magento_token, moodle_token)
    logger.info(
        "INFO    - ["
        + str(datetime.now())
        + "]: "
        + str(request.client.host)
        + ":"
        + str(request.client.port)
        + " - "
        + str(request.method)
        + " - "
        + str(request.url.path)
        + " - New user created successfully"
    )
    return JSONResponse({"message": "Login successfully"})

@router.post("/logout")
async def logout(authorization: str = Depends(token_auth_scheme), request: Request = None):
    logger.info(
        "INFO    - ["
        + str(datetime.now())
        + "]: "
        + str(request.client.host)
        + ":"
        + str(request.client.port)
        + " - "
        + str(request.method)
        + " - "
        + str(request.url.path)
        + " - Doing logout..."
    )
    token = request.headers.get("api-authorization")
    UsersDAO.remove_token_by_token(token)
    logger.info(
        "INFO    - ["
        + str(datetime.now())
        + "]: "
        + str(request.client.host)
        + ":"
        + str(request.client.port)
        + " - "
        + str(request.method)
        + " - "
        + str(request.url.path)
        + " - User logged out successfully"
    )
    return JSONResponse({"message": "Logout successfully"})


# Bell Numbers - Dynamic Programming

"""
    Bell numbers count the possible partitions of a set.
    example set {1, 2} -> possible partitions { {1}, {2} }, { {1, 2} }
    Bell number = 2
"""

def bell(n):
    p = [set([i for i in range(1, n + 1)])]
    count = 0
    for i in range(1, n + 1):
        s = set()
        for j in range(1, i + 1):
            if i != j:
                s.add(j)
        p.append(s)
        print(p)
        count += 1

if __name__ == '__main__':
    n_ = 4
    bell(n_)


import numpy as np
import openravepy as orpy
import toppra as ta
import matplotlib.pyplot as plt
import os, argparse
import logging
import following
logger = logging.getLogger(__name__)

def main(env=None, verbose=False, savefig=False):
    # Setup Logging
    if verbose:
        logging.basicConfig(level="DEBUG")
    else:
        logging.basicConfig(level="WARN")

    # Setup the robot, the geometric path and the torque bounds
    print("Loading the environment")
    if env is None:
        env = orpy.Environment()
    else:
        env.Reset()
    following.try_load_denso(env)
    robot = env.GetRobots()[0]
    np.random.seed(11)
    waypoints = np.random.randn(5, 6) * 0.4
    path = ta.SplineInterpolator(np.linspace(0, 1, 5), waypoints)
    tau_max = np.r_[30., 50., 20., 20., 10., 10.]
    robot.SetDOFTorqueLimits(tau_max)

    # Nominal case
    print("Computing controllable sets for the ideal case.")
    cnst = ta.create_rave_torque_path_constraint(robot, 1)
    pp = ta.algorithm.TOPPRA([cnst], path)
    Ks = pp.compute_controllable_sets(0, 0)

    robust_Ks_dict = {}
    ellipsoid_axes = ([1, 1, 1], [3, 3, 3], [7, 7, 7])
    for vs in ellipsoid_axes:
        print("Computing controllable sets for perturbation ellipsoid={:}".format(vs))
        robust_cnst = ta.constraint.RobustCanonicalLinearConstraint(cnst, vs)
        robust_pp = ta.algorithm.TOPPRA([robust_cnst], path)
        robust_Ks = robust_pp.compute_controllable_sets(0, 1e-3)
        robust_Ks_dict[vs[0]] = robust_Ks

    plt.plot([0, 100], [0, 0], '--', c='black')
    plt.plot(Ks[:, 1], '--', c='blue', label="ideal case")
    plt.plot(robust_Ks_dict[1][:, 1], '--', c='green', label="low perturbation level")
    plt.plot(robust_Ks_dict[3][:, 1], '--', c='orange', label="medium perturbation level")
    plt.plot(robust_Ks_dict[7][:, 1], '--', c='red', label="high perturbation level")
    plt.legend()
    plt.title("Controllable set for different levels of perturbations.")
    plt.tight_layout()
    if savefig:
        plt.savefig("icra18-compare-robust-controllable-sets.pdf")
    plt.show()

if __name__ == '__main__':
    main()


'''This program will do the functions mentioned in Lab 10'''
import unittest
import typing
from typing import Any,List,Iterator, Optional, DefaultDict, Tuple, IO, Dict
from collections import Counter, defaultdict
from datetime import datetime, timedelta
from prettytable import PrettyTable
from HW08_Harishkumar_M import file_reader
import os
import sqlite3

class University:
    """
    Holds all records of students,instructors and grades
    of a particular university
    """

    def __init__(self,directory:str)-> None:
        "perform initalization and call file reader"
        self._directory = directory
        self._students:Dict[str,Student] = dict()
        self._instructor:Dict[str,Instructor] = dict()
        self._majors:Dict[str,_Major] = dict()
        self.read_major(os.path.join(self._directory,'majors.txt'))
        self.read_student(os.path.join(self._directory,'students.txt'))
        self.read_instructor(os.path.join(self._directory,'instructors.txt'))
        self.read_grades(os.path.join(self._directory,'grades.txt'))
        self._query:str = """
                            select s.Name as Student,s.CWID,g.Course,g.Grade,i.Name as Instructor
                            from grades g join students s
                            on g.StudentCWID = s.CWID
                            join instructors i on g.InstructorCWID = i.CWID
                            order by Student
                            """

    def read_student(self,path:str)-> None:
        "this method gives call to the file Reader method in HW08 to fill student info "
        try:
            for cwid, name, major in file_reader(path, 3, sep='\t', header=True):
                if major in self._majors:
                    self._students[cwid] = Student(cwid,name,major,self._majors[major].get_required(),
                                                    self._majors[major].get_electives())
                else:
                    print('Major for this student not found: Major name ',major)
        except (ValueError,FileNotFoundError) as e:
            print(e)

    def read_instructor(self,path:str)-> None:
        "this method gives call to the file Reader to fill instructor info "
        try:
            for cwid, name, dept in file_reader(path, 3, sep='\t', header=True):
                self._instructor[cwid] = Instructor(cwid,name,dept)
        except (ValueError,FileNotFoundError) as e:
            print(e)

    def read_grades(self,path:str)-> None:
        "this method gives call to the file Reader to update course and grade "
        try:
            for std_cwid, course, grade, inst_cwid in file_reader(path, 4, sep='\t', header=True):
                try:
                    self._students[std_cwid].add_courses(course,grade)
                except KeyError as e:
                    print('Student with ID ',e,' not found')
                try:
                    self._instructor[inst_cwid].add_courses_info(course,std_cwid)
                except KeyError as e:
                    print('Instructor with ID ',e,' not found')
        except (ValueError,FileNotFoundError) as e:
            print(e)

    def read_major(self,path:str)-> None:
        "this method gives call to the file Reader method in HW08 to fill student info "
        try:
            for major, flag, course in file_reader(path, 3, sep='\t', header=True):
                if major not in self._majors:
                    self._majors[major] = _Major()
                    self._majors[major].store_major(flag,course)
                else:
                    self._majors[major].store_major(flag,course)
        except (ValueError,FileNotFoundError) as e:
            print(e)

    def table_student(self)->None:
        "this method will print the pretty Table for students"
        print("Student Summary")
        pt: PrettyTable = PrettyTable(field_names=['CWID','Name','Major','Completed Courses','Remaining Required',
        'Remaining Electives','GPA'])
        for key in self._students.keys():
            pt.add_row((self._students[key].Student_table_data()))
        print(pt)
        print()

    def table_instructor(self)->None:
        "this method will print the pretty Table for Instructors"
        print("Instructor Summary")
        pt: PrettyTable = PrettyTable(field_names=['CWID','Name','Dept','Course','Students'])
        for key in self._instructor.keys():
            for record in self._instructor[key].Instructor_table_data():
                pt.add_row(record)
        print(pt)
        print()

    def table_major(self) -> None:
        """this method will print the pretty Table for Majors"""
        print("Majors Summary")
        pt: PrettyTable = PrettyTable(field_names=["Major", "Required Courses", "Electives"])
        for majorName in self._majors.keys():
            pt.add_row([majorName, sorted(self._majors[majorName].get_required()),
            sorted(self._majors[majorName].get_electives())])
        print(pt)
        print()

    def table_student_grade(self,db_path)-> None:
        """this method willprint the pretty Table for Studen and Grade Join data"""
        print("Student Grade Summary")
        try:
            db: sqlite3.Connection = sqlite3.connect(db_path)
        except sqlite3.OperationalError as e:
            print(e)
        else:
            pt: PrettyTable = PrettyTable(field_names=["Name", "CWID", "Course", "Grade", "Instructor"])
            try:
                for row in db.execute(self._query):
                    pt.add_row(row)
                db.close()
                print(pt)
            except sqlite3.OperationalError as e:
                print(e)

    def table_student_grades_db_test(self, db_path) -> Tuple:
        """Generator to test sql query"""
        try:
            db: sqlite3.Connection = sqlite3.connect(db_path)
        except sqlite3.OperationalError as e:
            print(e)
        else:
            try:
                for row in db.execute(self._query):
                    yield row
                db.close()
            except sqlite3.OperationalError as e:
                print(e)

class Student:
    'Holds the student records'

    GPA_map:Dict[str,float] = {'A':4.0,'A-':3.75,'B+':3.25,'B':3.0,'B-':2.75,'C+':2.25,'C':2.0,'C-':0,'D+':0,
                                'D':0,'D-':0,'F':0}

    def __init__(self,cwid:str,name:str,major:str,required:List,electives:List) -> None:
        'Creating instances for students'
        self.cwid = cwid
        self.name = name
        self.major = major
        self.courses = dict()
        self._completed_courses = dict()
        self._remaining_required: List[str] = required.copy()
        self._remaining_electives: List[str] = electives.copy()
        self.GPA: float = 0.0

    def add_courses(self,course:str,grade:str)->None:
        "this method will add the courses from grades file if the student exist"

        course_GPA = Student.GPA_map.get(grade)
        if(course_GPA != 0):
            self.courses[course] = grade
            self._completed_courses[course] = grade
            if course in self._remaining_required:
                self._remaining_required.remove(course)
            elif course in self._remaining_electives:
                self._remaining_electives.clear()
        else:
            self.courses[course] = grade

    def calculate_GPA(self)->None:
        "this method will calculate the GPA for the student"

        total_GP:float = 0.0
        course_count:int = 0
        for key,value in self.courses.items():
            total_GP+= Student.GPA_map.get(value,0)
            course_count+=1
        if(course_count != 0):
            self.GPA = round(total_GP / course_count,2)

    def Student_table_data(self)->None:
        "this method will provide the data for each student which is required for the pretty table"

        self.calculate_GPA()
        return [self.cwid,self.name,self.major,sorted(self._completed_courses.keys()),self._remaining_required,
        self._remaining_electives,self.GPA]

class Instructor:
    'Holds the instructor records'
    def __init__(self,cwid:str,name:str,dept:str)-> None:
        'Creating instances for instructor'
        self.cwid = cwid
        self.name = name
        self.dept = dept
        self.courses:DefaultDict[list] = defaultdict(list)

    def add_courses_info(self,course:str,std_cwid:str)->None:
        "this method will add the courses from grades file if the student exist"
        self.courses[course].append(std_cwid)

    def Instructor_table_data(self)->None:
        "this method will provide the data for each student which is required for the pretty table"
        instructor_data: List = list()
        for key, value in self.courses.items():
            instructor_data.append([self.cwid, self.name, self.dept, key, len(value)])
        return instructor_data

class _Major:
    """Store data of each Major"""
    def __init__(self):
        """ Initialization for Majors class """
        self._required: List = list()
        self._electives: List = list()

    def store_major(self, flag: str, course: str) -> None:
        """ stores the course for major according to required and elective courses """
        if flag == "R":
            self._required.append(course)
        else:
            self._electives.append(course)

    def get_required(self):
        """return list of required courses"""
        return self._required

    def get_electives(self):
        """return list of elective courses"""
        return self._electives

def main() -> None:
    """
    This is the main method for the program
    here repository of different Universities can be added
    """

    stevens_univ:University = University('Stevens_University_Repository')
    stevens_univ.table_major()
    stevens_univ.table_student()
    stevens_univ.table_instructor()
    stevens_univ.table_student_grade("Student_Repository.sqlite")

if __name__ == "__main__":
    main()


# Escreva um programa que leia números inteiros do teclado. O programa deve ler os números até que o usuário digite 0 (zero).
# No final da execução, exiba a quantidade de números digitados, assim como a soma e a média aritmética

n = 1
c = soma = 0
while n != 0:
    n = int(input('Digite um número (0 para parar): '))
    if n == 0:
        break
    c += 1
    soma += n

media = soma / c

print(f'Números digitados: {c}.')
print(f'Soma: {soma}.')
print(f'Média: {media}.')

Python/FATEC/2° Semestre - Linguagem de Programação/04 - Lista de Exercicios - Estrutura de Repetição/ex-14.py


GLOBAL = {
    "continual_split_to_tags": None,
    "continual_tag_to_split": None,
    "infer_model": None,
}

def get_epoch_map(big_model: bool):
    if big_model:
        return {
            'fewnerd': 10,
            'ontonotes': 10,
            'bbn': 10,
            'fewrel': 10,
            'tacred': 20,
            'ace': 20,
            'chent': 10,
        }
    else:
        return {
            'fewnerd': 10,
            'ontonotes': 20,
            'bbn': 20,
            'fewrel': 10,
            'tacred': 20,
            'ace': 20,
            'chent': 20,
        }

def get_batch_limit(dataset_name: str):
    return {
        'fewnerd': 2500,
        'ontonotes': 1250,
        'bbn': 500,
        'fewrel': 400,
        'tacred': 100,
        'ace': 100,
        'chent': 1250,
    }[dataset_name]

def get_batch_size_map(big_model: bool):
    if big_model:
        return {
            'fewnerd': 8,
            'ontonotes': 8,
            'bbn': 8,
            'fewrel': 8,
            'tacred': 8,
            'ace': 8,
            'chent': 8,
        }
    else:
        return {
            'fewnerd': 16,
            'ontonotes': 16,
            'bbn': 16,
            'fewrel': 16,
            'tacred': 16,
            'ace': 16,
            'chent': 16,
        }

def get_learning_rate(big_model: bool, dataset_name: str, split_id: int, method: str, is_adapter=False):
    if big_model:
        if dataset_name == 'fewnerd':
            if method not in ['emr', 'emar', 'eaemr', 'our_abl', 'emr_abl']:
                if is_adapter:
                    return 0.0001
                else:
                    return 0.0005 if split_id <= 2 else 0.0001
            else:
                return 1.0e-5 if is_adapter else 2.0e-5
        elif dataset_name == 'ontonotes':
            return 0.0005 if split_id <= 3 else 0.0001
        elif dataset_name == 'bbn':
            return 0.0002
        elif dataset_name == 'fewrel':
            return 0.0002
        elif dataset_name == 'tacred':
            return 0.0002
        elif dataset_name == 'ace':
            return 0.0002
        else:
            raise NotImplementedError(f'invalid dataset_name: {dataset_name}')
    else:
        return {
            'fewnerd': 0.00002,
            'ontonotes': 0.0001,
            'bbn': 0.00005,
            'fewrel': 0.001,
            'tacred': 0.001,
            'ace': 0.002,
            'chent': 0.0001,
        }[dataset_name]


# Performs maze generation algorithms

from random import randint, choice, shuffle, random
'''
Aldous-Broder: breaks down walls between unvisited cells until all the cells
in the grid are visited
'''

def aldousBroder(grid):
  cell = grid.getRandom()
  unvisited = grid.getSize() - 1
  while unvisited > 0:
    neighbor = choice(cell.getNeighbors())
    if not neighbor.getLinks():  # checks if neighbor has no links
      cell.link(neighbor)
      unvisited -= 1
    cell = neighbor
  return grid

'''
Growing Tree: implements both simplified and true Prim's algorithms
proportionally based on input from 0 (random selection, Prim's) to 1 (last
selection, recursive backtracking). The Default is set to 0.5, meaning the
two options are equiprobable.
'''

def growingTree(grid, slider=0.5):
  isAvailable = lambda n: True if not n.getLinks() else False
  active = []
  active.append(grid.getRandom())
  while active:
    randomly = (lambda l: choice(l))(active)  # Prim's (simplified)
    last = (lambda l: l[-1])(active)  # Recursive backtracker
    cell = [randomly, last][random() < slider]
    neighbors = list(filter(isAvailable, cell.getNeighbors()))
    if neighbors:
      neighbor = choice(neighbors)
      cell.link(neighbor)
      active.append(neighbor)
    else:
      active.remove(cell)
  return grid

'''
Hunt and Kill: a random-walk based algorithm similar to Aldous-Broder except
it only allows steps into unvisited cells only
'''

def hunt_and_kill(grid):
  current = grid.getRandom()
  while current:
    neighbors = current.getNeighbors()
    unvisited_neighbors = [n for n in neighbors if not n.getLinks()]
    if unvisited_neighbors:
      neighbor = choice(unvisited_neighbors)
      current.link(neighbor)
      current = neighbor
    else:
      current = None  # to break out while loop if all visited
      for cell in grid.each_cell():
        neighbors = cell.getNeighbors()
        visited_neighbors = [n for n in neighbors if n.getLinks()]
        # if visited neighbors exist and cell has no links
        if visited_neighbors and not cell.getLinks():
          current = cell
          neighbor = choice(visited_neighbors)
          current.link(neighbor)
          break
  return grid

'''
Wilson's: draws multiple paths from unvisited cells to a visited one until
there are no more unvisited cells.
'''

def wilsons(grid):
  unvisited = list(grid.each_cell())
  shuffle(unvisited)
  unvisited.pop()  # set first goal cell
  while unvisited:
    path = unvisited[0:1]
    cell = path[0]
    while cell in unvisited:  # create path
      cell = choice(cell.getNeighbors())
      if cell in path:  # remove loops
        path = path[:path.index(cell) + 1]
      else:
        path.append(cell)
    for index, cell in enumerate(path):
      if index < len(path) - 1:
        cell.link(path[index + 1])  # link the cells in path
        unvisited.remove(cell)  # set path as visited
    path.clear()  # clear path
  return grid


import random

p = input('Enter a value for p: ')
p = float(p)

#p = 0.7

Cardinality = 10
NumberTrials = 100
suc_range = int(p * Cardinality)
tempSum = 0

#print(p)
#print(Cardinality)
#print(suc_range)

TrialSequence = []
for TrialIndex in range(0, NumberTrials):
    TrialSequence.append(random.randrange(Cardinality))

#print(TrialSequence)

#EmpiricalDistribution = []
#for OutcomeIndex in range(0, Cardinality):
#    EmpiricalDistribution.append(TrialSequence.count(OutcomeIndex))

BernoulliDist = []

for OutcomeIndex in range(0, suc_range):
    tempSum = tempSum + TrialSequence.count(OutcomeIndex)

BernoulliDist.append(tempSum/NumberTrials)
tempSum = 0

for OutcomeIndex in range(suc_range, Cardinality):
    tempSum = tempSum + TrialSequence.count(OutcomeIndex)

BernoulliDist.append(tempSum/NumberTrials)

#print(EmpiricalDistribution)
print(BernoulliDist)

#print(EmpiricalDistribution)
#print(BernoulliDist)


from __future__ import print_function

import argparse
import csv
import os

import numpy as np
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets

import torchvision.models as models
from utils import progress_bar
from torchvision.utils import save_image
from tensorboardX import SummaryWriter
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')

parser.add_argument("--train_dir", required=True, type=str, help="Path to train data parent directory.")
parser.add_argument("--test_dir", required=True, type=str, help="Path to test data parent directory.")
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--resume', '-r', action='store_true',
                    help='resume from checkpoint')
parser.add_argument('--model', default="ResNet18", type=str,
                    help='model type (default: ResNet50)')
parser.add_argument('--name', default='0', type=str, help='name of run')
parser.add_argument('--seed', default=0, type=int, help='random seed')
parser.add_argument('--batch_size', default=128, type=int, help='batch size')
parser.add_argument('--epoch', default=200, type=int,
                    help='total epochs to run')
parser.add_argument('--no-augment', dest='augment', action='store_false',
                    help='use standard augmentation (default: True)')
parser.add_argument('--decay', default=1e-4, type=float, help='weight decay')
parser.add_argument('--alpha', default=1., type=float,
                    help='mixup interpolation coefficient (default: 1)')
args = parser.parse_args()

use_cuda = torch.cuda.is_available()

writer = SummaryWriter()

best_acc = 0  # best test accuracy
start_epoch = 0  # start from epoch 0 or last checkpoint epoch
save_dir = "results"

if args.seed != 0:
    torch.manual_seed(args.seed)

# Data
print('==> Preparing data..')
if args.augment:
    transform_train = transforms.Compose([
        transforms.Resize((128,128)),
        #transforms.RandomCrop(32, padding=4),
        #transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])
else:
    transform_train = transforms.Compose([
        transforms.Resize((128,128)),
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])

transform_test = transforms.Compose([
    transforms.Resize((128,128)),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])

trainset = datasets.ImageFolder(os.path.abspath(args.train_dir), transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset,
                                          batch_size=args.batch_size,
                                          shuffle=True, num_workers=3)

testset = datasets.ImageFolder(os.path.abspath(args.test_dir), transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size,
                                         shuffle=False, num_workers=3)

print('==> Building model..')
device = 'cuda' if torch.cuda.is_available() else 'cpu'
#net = models.resnet50(pretrained=True)
net = models.resnet50(weights='ResNet50_Weights.DEFAULT')
modules = list(net.children())[:-1]
modules.append(nn.Flatten())
modules.append(nn.Linear(net.fc.in_features,4))
net = nn.Sequential(*modules)
net = net.to(device)

if device == 'cuda':
    net = torch.nn.DataParallel(net)
    cudnn.benchmark = True

"""

# Model
if args.resume:
    # Load checkpoint.
    print('==> Resuming from checkpoint..')
    assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'
    checkpoint = torch.load('./checkpoint/ckpt.t7' + args.name + '_'
                            + str(args.seed))
    net = checkpoint['net']
    best_acc = checkpoint['acc']
    start_epoch = checkpoint['epoch'] + 1
    rng_state = checkpoint['rng_state']
    torch.set_rng_state(rng_state)
else:
    print('==> Building model..')
    net = models.__dict__[args.model]()

if not os.path.isdir('results'):
    os.mkdir('results')
logname = ('results/log_' + net.__class__.__name__ + '_' + args.name + '_'
           + str(args.seed) + '.csv')

if use_cuda:
    net.cuda()
    net = torch.nn.DataParallel(net)
    print(torch.cuda.device_count())
    cudnn.benchmark = True
    print('Using CUDA..')
"""

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=args.decay)

def save_model(model):
    torch.save(model.state_dict(), save_dir + "/"+str(args.seed)+"model.pt")

def CreateDir(path):
        try:
                os.mkdir(path)
        except OSError as error:
                print(error)

CreateDir(save_dir)

def mixup_data(x, y, alpha=1.0, use_cuda=True):
    '''Returns mixed inputs, pairs of targets, and lambda'''
    if alpha > 0:
        lam = np.random.beta(alpha, alpha)
    else:
        lam = 1

    batch_size = x.size()[0]
    if use_cuda:
        index = torch.randperm(batch_size).cuda()
    else:
        index = torch.randperm(batch_size)

    mixed_x = lam * x + (1 - lam) * x[index, :]
    y_a, y_b = y, y[index]
    return mixed_x, y_a, y_b, lam

def mixup_criterion(criterion, pred, y_a, y_b, lam):
    return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)

def train(epoch):
    print('\nEpoch: %d' % epoch)
    net.train()
    train_loss = 0
    reg_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(trainloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()

        inputs_mixup, targets_a, targets_b, lam = mixup_data(inputs, targets,
                                                       args.alpha, use_cuda)
        inputs_mixup, targets_a, targets_b = map(Variable, (inputs_mixup,
                                                      targets_a, targets_b))

        outputs = net(inputs_mixup)

        loss = mixup_criterion(criterion, outputs, targets_a, targets_b, lam)
        train_loss += loss
        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += (lam * predicted.eq(targets_a.data).sum().float()
                    + (1 - lam) * predicted.eq(targets_b.data).sum().float())

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

        progress_bar(batch_idx, len(trainloader),
                     'Loss: %.3f | Reg: %.5f | Acc: %.3f%% (%d/%d)'
                     % (train_loss/(batch_idx+1), reg_loss/(batch_idx+1),
                        100.*correct/total, correct, total))
        writer.add_scalar('Training/ACC',100.*correct/total, (epoch*len(trainloader.dataset)/args.batch_size)+batch_idx)
        writer.add_scalar('Training/loss',train_loss/(batch_idx+1),(epoch*len(trainloader.dataset)/args.batch_size)+batch_idx)
    return (train_loss/batch_idx, reg_loss/batch_idx, 100.*correct/total)

def test(epoch):
    global best_acc
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(testloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=False), Variable(targets)
        outputs = net(inputs)

        _, predicted = torch.max(outputs.data, 1)
        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()

        progress_bar(batch_idx, len(testloader),
                     'Loss: %.3f | Acc: %.3f%% (%d/%d)'
                     % (test_loss/(batch_idx+1), 100.*correct/total,
                        correct, total))
    acc = 100.*correct/total
    writer.add_scalar('Test/ACC',acc, (epoch*len(testloader.dataset)/args.batch_size)+batch_idx)
    if epoch == start_epoch + args.epoch - 1 or acc > best_acc:
        checkpoint(acc, epoch)
    if acc > best_acc:
        best_acc = acc
    return (test_loss/batch_idx, 100.*correct/total)

def val(epoch):
    global best_acc
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    pred_ = []
    label_ = []
    for batch_idx, (inputs, targets) in enumerate(testloader):
        if use_cuda:
            inputs, targets = inputs.cuda(), targets.cuda()
        inputs, targets = Variable(inputs, volatile=False), Variable(targets)
        outputs = net(inputs)

        _, predicted = torch.max(outputs.data, 1)

        pred_.append(predicted.data.cpu().numpy())
        label_.append(targets.data.cpu().numpy())

        total += targets.size(0)
        correct += predicted.eq(targets.data).cpu().sum()

        progress_bar(batch_idx, len(testloader),
                     'Loss: %.3f | Acc: %.3f%% (%d/%d)'
                     % (test_loss/(batch_idx+1), 100.*correct/total,
                        correct, total))
    acc = 100.*correct/total
    if epoch == start_epoch + args.epoch - 1 or acc > best_acc:
        checkpoint(acc, epoch)
    if acc > best_acc:
        best_acc = acc
    return pred_, label_, (test_loss/batch_idx), (100.*correct/total)

def convert_label_(pred_y,true_l,list_label):
  y_true = []
  y_pred = []
  for i in range(len(pred_y)):
    for j in range(len(pred_y[i])):
      y_pred.append(list_label[pred_y[i][j].item()])
      y_true.append(list_label[true_l[i][j].item()])
  return np.array(y_true),np.array(y_pred)

def plot_confusion_matrix(cm,
                          target_names,
                          title='Confusion matrix',
                          titleG='Confusion matrix',
                          cmap=None,
                          normalize=True):
    """
    given a sklearn confusion matrix (cm), make a nice plot

    Arguments
    ---------
    cm:           confusion matrix from sklearn.metrics.confusion_matrix

    target_names: given classification classes such as [0, 1, 2]
                  the class names, for example: ['high', 'medium', 'low']

    title:        the text to display at the top of the matrix

    cmap:         the gradient of the values displayed from matplotlib.pyplot.cm
                  see http://matplotlib.org/examples/color/colormaps_reference.html
                  plt.get_cmap('jet') or plt.cm.Blues

    normalize:    If False, plot the raw numbers
                  If True, plot the proportions

    Usage
    -----
    plot_confusion_matrix(cm           = cm,                  # confusion matrix created by
                                                              # sklearn.metrics.confusion_matrix
                          normalize    = True,                # show proportions
                          target_names = y_labels_vals,       # list of names of the classes
                          title        = best_estimator_name) # title of graph

    Citiation
    ---------
    http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

    """
    import matplotlib.pyplot as plt_
    import numpy as np
    import itertools

    accuracy = np.trace(cm) / float(np.sum(cm))
    misclass = 1 - accuracy

    if cmap is None:
        cmap = plt_.get_cmap('Blues')

    plt_.figure()
    plt_.imshow(cm, interpolation='nearest', cmap=cmap)
    plt_.title(titleG)
    plt_.colorbar()

    if target_names is not None:
        tick_marks = np.arange(len(target_names))
        plt_.xticks(tick_marks, target_names, rotation=45)
        plt_.yticks(tick_marks, target_names)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    thresh = cm.max() / 1.5 if normalize else cm.max() / 2
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        if normalize:
            plt_.text(j, i, "{:0.4f}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")
        else:
            plt_.text(j, i, "{:,}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")

    plt_.tight_layout()
    plt_.ylabel('Verdade do label')
    plt_.xlabel('Predicted label')
    plt_.xlabel('Predição do  label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
    plt_.savefig(title+'-confusion_matrix.png', dpi=120)
    plt_.close()
    #plt.show()

def checkpoint(acc, epoch):
    # Save checkpoint.
    print('Saving..')
    state = {
        'net': net,
        'acc': acc,
        'epoch': epoch,
        'rng_state': torch.get_rng_state()
    }
    if not os.path.isdir('checkpoint'):
        os.mkdir('checkpoint')
    torch.save(state, './checkpoint/ckpt.t7' + args.name + '_'
               + str(args.seed))

def adjust_learning_rate(optimizer, epoch):
    """decrease the learning rate at 100 and 150 epoch"""
    lr = args.lr
    if epoch >= 100:
        lr /= 10
    if epoch >= 150:
        lr /= 10
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

"""
if not os.path.exists(logname):
    with open(logname, 'w') as logfile:
        logwriter = csv.writer(logfile, delimiter=',')
        logwriter.writerow(['epoch', 'train loss', 'reg loss', 'train acc',
                            'test loss', 'test acc'])
"""
for epoch in range(start_epoch, args.epoch):
    train_loss, reg_loss, train_acc = train(epoch)
    test_loss, test_acc = test(epoch)
    adjust_learning_rate(optimizer, epoch)
    #with open(logname, 'a') as logfile:
        #logwriter = csv.writer(logfile, delimiter=',')
        #logwriter.writerow([epoch, train_loss, reg_loss, train_acc, test_loss,
                            #test_acc])

save_model(net)

pred, label, test_loss, test_acc = val(epoch)

print(test_acc)
print(testset.classes)

y_pred, y_true = convert_label_(pred,label,testset.classes)
confusion = confusion_matrix(y_true, y_pred, labels = testset.classes)

print(confusion)
plot_confusion_matrix(cm = np.array(confusion),normalize = False, target_names = testset.classes, title =' Test', titleG = ' Test')


load("//closure/private:java_import_external.bzl", "java_import_external")
load("//closure/private:platform_http_file.bzl", "platform_http_file")

def closure_repositories(
    omit_aopalliance=False,
    omit_args4j=False,
    omit_clang=False,
    omit_com_google_auto_common=False,
    omit_com_google_auto_factory=False,
    omit_com_google_auto_value=False,
    omit_com_google_closure_stylesheets=False,
    omit_com_google_code_findbugs_jsr305=False,
    omit_com_google_code_gson=False,
    omit_com_google_common_html_types=False,
    omit_com_google_common_html_types_html_proto=False,
    omit_com_google_dagger=False,
    omit_com_google_dagger_compiler=False,
    omit_com_google_dagger_producers=False,
    omit_com_google_errorprone_error_prone_annotations=False,
    omit_com_google_guava=False,
    omit_com_google_inject_extensions_guice_assistedinject=False,
    omit_com_google_inject_extensions_guice_multibindings=False,
    omit_com_google_inject_guice=False,
    omit_com_google_javascript_closure_compiler=False,
    omit_com_google_javascript_closure_library=False,
    omit_com_google_javascript_incremental_dom=False,
    omit_com_google_protobuf_java=False,
    omit_com_google_protobuf_js=False,
    omit_com_google_protobuf_protoc_linux_x86_64=False,
    omit_com_google_protobuf_protoc_macosx=False,
    omit_com_google_template_soy=False,
    omit_com_google_template_soy_jssrc=False,
    omit_com_ibm_icu_icu4j=False,
    omit_com_squareup_javawriter=False,
    omit_fonts_noto_hinted_deb=False,
    omit_fonts_noto_mono_deb=False,
    omit_javax_inject=False,
    omit_libexpat_amd64_deb=False,
    omit_libfontconfig_amd64_deb=False,
    omit_libfreetype_amd64_deb=False,
    omit_libpng_amd64_deb=False,
    omit_org_json=False,
    omit_org_jsoup=False,
    omit_org_ow2_asm=False,
    omit_org_ow2_asm_analysis=False,
    omit_org_ow2_asm_commons=False,
    omit_org_ow2_asm_tree=False,
    omit_org_ow2_asm_util=False,
    omit_phantomjs=False):
  """Imports dependencies for Closure Rules."""
  _check_bazel_version("Closure Rules", "0.4.5")
  if not omit_aopalliance:
    aopalliance()
  if not omit_args4j:
    args4j()
  if not omit_clang:
    clang()
  if not omit_com_google_auto_common:
    com_google_auto_common()
  if not omit_com_google_auto_common:
    com_google_auto_factory()
  if not omit_com_google_auto_factory:
    com_google_auto_value()
  if not omit_com_google_closure_stylesheets:
    com_google_closure_stylesheets()
  if not omit_com_google_code_findbugs_jsr305:
    com_google_code_findbugs_jsr305()
  if not omit_com_google_code_gson:
    com_google_code_gson()
  if not omit_com_google_common_html_types:
    com_google_common_html_types()
  if not omit_com_google_common_html_types_html_proto:
    com_google_common_html_types_html_proto()
  if not omit_com_google_dagger:
    com_google_dagger()
  if not omit_com_google_dagger_compiler:
    com_google_dagger_compiler()
  if not omit_com_google_dagger_producers:
    com_google_dagger_producers()
  if not omit_com_google_errorprone_error_prone_annotations:
    com_google_errorprone_error_prone_annotations()
  if not omit_com_google_guava:
    com_google_guava()
  if not omit_com_google_inject_extensions_guice_assistedinject:
    com_google_inject_extensions_guice_assistedinject()
  if not omit_com_google_inject_extensions_guice_multibindings:
    com_google_inject_extensions_guice_multibindings()
  if not omit_com_google_inject_guice:
    com_google_inject_guice()
  if not omit_com_google_javascript_closure_compiler:
    com_google_javascript_closure_compiler()
  if not omit_com_google_javascript_closure_library:
    com_google_javascript_closure_library()
  if not omit_com_google_javascript_incremental_dom:
    com_google_javascript_incremental_dom()
  if not omit_com_google_protobuf_java:
    com_google_protobuf_java()
  if not omit_com_google_protobuf_js:
    com_google_protobuf_js()
  if not omit_com_google_protobuf_protoc_linux_x86_64:
    com_google_protobuf_protoc_linux_x86_64()
  if not omit_com_google_protobuf_protoc_macosx:
    com_google_protobuf_protoc_macosx()
  if not omit_com_google_template_soy:
    com_google_template_soy()
  if not omit_com_google_template_soy_jssrc:
    com_google_template_soy_jssrc()
  if not omit_com_ibm_icu_icu4j:
    com_ibm_icu_icu4j()
  if not omit_com_squareup_javawriter:
    com_squareup_javawriter()
  if not omit_fonts_noto_hinted_deb:
    fonts_noto_hinted_deb()
  if not omit_fonts_noto_mono_deb:
    fonts_noto_mono_deb()
  if not omit_javax_inject:
    javax_inject()
  if not omit_libexpat_amd64_deb:
    libexpat_amd64_deb()
  if not omit_libfontconfig_amd64_deb:
    libfontconfig_amd64_deb()
  if not omit_libfreetype_amd64_deb:
    libfreetype_amd64_deb()
  if not omit_libpng_amd64_deb:
    libpng_amd64_deb()
  if not omit_org_json:
    org_json()
  if not omit_org_jsoup:
    org_jsoup()
  if not omit_org_ow2_asm:
    org_ow2_asm()
  if not omit_org_ow2_asm_analysis:
    org_ow2_asm_analysis()
  if not omit_org_ow2_asm_commons:
    org_ow2_asm_commons()
  if not omit_org_ow2_asm_tree:
    org_ow2_asm_tree()
  if not omit_org_ow2_asm_util:
    org_ow2_asm_util()
  if not omit_phantomjs:
    phantomjs()

def _check_bazel_version(project, bazel_version):
  if "bazel_version" not in dir(native):
    fail("%s requires Bazel >=%s but was <0.2.1" % (project, bazel_version))
  elif not native.bazel_version:
    pass  # user probably compiled Bazel from scratch
  else:
    current_bazel_version = _parse_bazel_version(native.bazel_version)
    minimum_bazel_version = _parse_bazel_version(bazel_version)
    if minimum_bazel_version > current_bazel_version:
      fail("%s requires Bazel >=%s but was %s" % (
          project, bazel_version, native.bazel_version))

def _parse_bazel_version(bazel_version):
  # Remove commit from version.
  version = bazel_version.split(" ", 1)[0]
  # Split into (release, date) parts and only return the release
  # as a tuple of integers.
  parts = version.split("-", 1)
  # Turn "release" into a tuple of strings
  version_tuple = ()
  for number in parts[0].split("."):
    version_tuple += (str(number),)
  return version_tuple

# MAINTAINERS
#
# 1. Please sort everything in this file.
#
# 2. Every external rule must have a SHA checksum.
#
# 3. Use http:// URLs since we're relying on the checksum for security.
#
# 4. Files must be mirrored to servers operated by Google SREs. This minimizes
#    the points of failure. It also minimizes the probability failure. For
#    example, if we assumed all external download servers were equal, had 99.9%
#    availability, and uniformly distributed downtime, that would put the
#    probability of an install working at 97.0% (0.999^30). Google static
#    content servers should have 99.999% availability, which *in theory* means
#    Closure Rules will install without any requests failing 99.9% of the time.
#
#    To get files mirrored, email the new artifacts or URLs to jart@google.com
#    so she can run:
#
#      bzmirror() {
#        local url="${1:?url}"
#        if [[ "${url}" =~ ^([^:]+):([^:]+):([^:]+)$ ]]; then
#          url="https://repo1.maven.org/maven2/${BASH_REMATCH[1]//.//}/${BASH_REMATCH[2]}/${BASH_REMATCH[3]}/${BASH_REMATCH[2]}-${BASH_REMATCH[3]}.jar"
#        fi
#        local dest="gs://bazel-mirror/${url#http*//}"
#        local desturl="http://bazel-mirror.storage.googleapis.com/${url#http*//}"
#        local name="$(basename "${dest}")"
#        wget -O "/tmp/${name}" "${url}" || return 1
#        gsutil cp -a public-read "/tmp/${name}" "${dest}" || return 1
#        gsutil setmeta -h 'Cache-Control:public, max-age=31536000' "${dest}" || return 1
#        curl -I "${desturl}"
#        echo
#        sha1sum "/tmp/${name}"
#        sha256sum "/tmp/${name}"
#        echo "${desturl}"
#        rm "/tmp/${name}" || return 1
#      }

def aopalliance():
  java_import_external(
      name = "aopalliance",
      jar_sha256 = "0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar",
          "http://repo1.maven.org/maven2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar",
          "http://maven.ibiblio.org/maven2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar",
      ],
      licenses = ["unencumbered"],  # public domain
  )

def args4j():
  java_import_external(
      name = "args4j",
      jar_sha256 = "989bda2321ea073a03686e9d4437ea4928c72c99f993f9ca6fab24615f0771a4",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/args4j/args4j/2.0.26/args4j-2.0.26.jar",
          "http://repo1.maven.org/maven2/args4j/args4j/2.0.26/args4j-2.0.26.jar",
          "http://maven.ibiblio.org/maven2/args4j/args4j/2.0.26/args4j-2.0.26.jar",
      ],
      licenses = ["notice"],  # MIT License
  )

def clang():
  platform_http_file(
      name = "clang",
      amd64_urls = [
          "http://bazel-mirror.storage.googleapis.com/llvm.org/releases/3.8.0/clang+llvm-3.8.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz",
          "http://llvm.org/releases/3.8.0/clang+llvm-3.8.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz",
      ],
      amd64_sha256 = "3120c3055ea78bbbb6848510a2af70c68538b990cb0545bac8dad01df8ff69d7",
      macos_urls = [
          "http://bazel-mirror.storage.googleapis.com/llvm.org/releases/3.8.0/clang+llvm-3.8.0-x86_64-apple-darwin.tar.xz",
          "http://llvm.org/releases/3.8.0/clang+llvm-3.8.0-x86_64-apple-darwin.tar.xz",
      ],
      macos_sha256 = "e5a961e04b0e1738bbb5b824886a34932dc13b0af699d1fe16519d814d7b776f",
  )

def com_google_auto_common():
  java_import_external(
      name = "com_google_auto_common",
      jar_sha256 = "eee75e0d1b1b8f31584dcbe25e7c30752545001b46673d007d468d75cf6b2c52",
      jar_urls = [
          "http://domain-registry-maven.storage.googleapis.com/repo1.maven.org/maven2/com/google/auto/auto-common/0.7/auto-common-0.7.jar",
          "http://repo1.maven.org/maven2/com/google/auto/auto-common/0.7/auto-common-0.7.jar",
          "http://maven.ibiblio.org/maven2/com/google/auto/auto-common/0.7/auto-common-0.7.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
      deps = ["@com_google_guava"],
  )

def com_google_auto_factory():
  java_import_external(
      name = "com_google_auto_factory",
      licenses = ["notice"],  # Apache 2.0
      jar_sha256 = "a038e409da90b9e065ec537cce2375b0bb0b07548dca0f9448671b0befb83439",
      jar_urls = [
          "http://domain-registry-maven.storage.googleapis.com/repo1.maven.org/maven2/com/google/auto/factory/auto-factory/1.0-beta3/auto-factory-1.0-beta3.jar",
          "http://maven.ibiblio.org/maven2/com/google/auto/factory/auto-factory/1.0-beta3/auto-factory-1.0-beta3.jar",
          "http://repo1.maven.org/maven2/com/google/auto/factory/auto-factory/1.0-beta3/auto-factory-1.0-beta3.jar",
      ],
      # Auto Factory ships its annotations, runtime, and processor in the same
      # jar. The generated code must link against this jar at runtime. So our
      # goal is to introduce as little bloat as possible.The only class we need
      # at runtime is com.google.auto.factory.internal.Preconditions. So we're
      # not going to specify the deps of this jar as part of the java_import().
      generated_rule_name = "jar",
      extra_build_file_content = "\n".join([
          "java_library(",
          "    name = \"processor\",",
          "    exports = [\":jar\"],",
          "    runtime_deps = [",
          "        \"@com_google_auto_common\",",
          "        \"@com_google_guava\",",
          "        \"@com_squareup_javawriter\",",
          "        \"@javax_inject\",",
          "    ],",
          ")",
          "",
          "java_plugin(",
          "    name = \"AutoFactoryProcessor\",",
          "    output_licenses = [\"unencumbered\"],",
          "    processor_class = \"com.google.auto.factory.processor.AutoFactoryProcessor\",",
          "    generates_api = 1,",
          "    tags = [\"annotation=com.google.auto.factory.AutoFactory;genclass=${package}.${outerclasses}@{className|${classname}Factory}\"],",
          "    deps = [\":processor\"],",
          ")",
          "",
          "java_library(",
          "    name = \"com_google_auto_factory\",",
          "    exported_plugins = [\":AutoFactoryProcessor\"],",
          "    exports = [",
          "        \":jar\",",
          "        \"@com_google_code_findbugs_jsr305\",",
          "        \"@javax_inject\",",
          "    ],",
          ")",
      ]),
  )

def com_google_auto_value():
  java_import_external(
      name = "com_google_auto_value",
      jar_sha256 = "ea26f99150825f61752efc8784739cf50dd25d7956774573f8cdc3b948b23086",
      jar_urls = [
          "http://domain-registry-maven.storage.googleapis.com/repo1.maven.org/maven2/com/google/auto/value/auto-value/1.4-rc2/auto-value-1.4-rc2.jar",
          "http://repo1.maven.org/maven2/com/google/auto/value/auto-value/1.4-rc2/auto-value-1.4-rc2.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
      neverlink = True,
      generated_rule_name = "compile",
      generated_linkable_rule_name = "processor",
      deps = [
          "@com_google_auto_common",
          "@com_google_code_findbugs_jsr305",
          "@com_google_guava",
      ],
      extra_build_file_content = "\n".join([
          "java_plugin(",
          "    name = \"AutoAnnotationProcessor\",",
          "    output_licenses = [\"unencumbered\"],",
          "    processor_class = \"com.google.auto.value.processor.AutoAnnotationProcessor\",",
          "    tags = [\"annotation=com.google.auto.value.AutoAnnotation;genclass=${package}.AutoAnnotation_${outerclasses}${classname}_${methodname}\"],",
          "    deps = [\":processor\"],",
          ")",
          "",
          "java_plugin(",
          "    name = \"AutoValueProcessor\",",
          "    output_licenses = [\"unencumbered\"],",
          "    processor_class = \"com.google.auto.value.processor.AutoValueProcessor\",",
          "    tags = [\"annotation=com.google.auto.value.AutoValue;genclass=${package}.AutoValue_${outerclasses}${classname}\"],",
          "    deps = [\":processor\"],",
          ")",
          "",
          "java_library(",
          "    name = \"com_google_auto_value\",",
          "    exported_plugins = [",
          "        \":AutoAnnotationProcessor\",",
          "        \":AutoValueProcessor\",",
          "    ],",
          "    exports = [",
          "        \":compile\",",
          "        \"@com_google_code_findbugs_jsr305\",",
          "    ],",
          ")",
      ]),
  )

def com_google_closure_stylesheets():
  java_import_external(
      name = "com_google_closure_stylesheets",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/closure-stylesheets/closure-stylesheets/1.4.0/closure-stylesheets-1.4.0.jar",
          "http://repo1.maven.org/maven2/com/google/closure-stylesheets/closure-stylesheets/1.4.0/closure-stylesheets-1.4.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/closure-stylesheets/closure-stylesheets/1.4.0/closure-stylesheets-1.4.0.jar",
      ],
      jar_sha256 = "4038c17fa38a90983fe4030a63ff8a644ed53a48187f55f3c4c3487fe9ad9f97",
      deps = [
          "@args4j",
          "@com_google_javascript_closure_compiler",
          "@com_google_code_gson",
          "@com_google_guava",
          "@com_google_code_findbugs_jsr305",
      ],
      extra_build_file_content = "\n".join([
          "java_binary(",
          "    name = \"ClosureCommandLineCompiler\",",
          "    jvm_flags = [\"-client\"],",
          "    main_class = \"com.google.common.css.compiler.commandline.ClosureCommandLineCompiler\",",
          "    output_licenses = [\"unencumbered\"],",
          "    runtime_deps = [\":com_google_closure_stylesheets\"],",
          ")",
      ]),
  )

def com_google_code_findbugs_jsr305():
  java_import_external(
      name = "com_google_code_findbugs_jsr305",
      licenses = ["notice"],  # BSD 3-clause
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/code/findbugs/jsr305/2.0.3/jsr305-2.0.3.jar",
          "http://repo1.maven.org/maven2/com/google/code/findbugs/jsr305/2.0.3/jsr305-2.0.3.jar",
          "http://maven.ibiblio.org/maven2/com/google/code/findbugs/jsr305/2.0.3/jsr305-2.0.3.jar",
      ],
      jar_sha256 = "bec0b24dcb23f9670172724826584802b80ae6cbdaba03bdebdef9327b962f6a",
  )

def com_google_code_gson():
  java_import_external(
      name = "com_google_code_gson",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/code/gson/gson/2.7/gson-2.7.jar",
          "http://repo1.maven.org/maven2/com/google/code/gson/gson/2.7/gson-2.7.jar",
          "http://maven.ibiblio.org/maven2/com/google/code/gson/gson/2.7/gson-2.7.jar",
      ],
      jar_sha256 = "2d43eb5ea9e133d2ee2405cc14f5ee08951b8361302fdd93494a3a997b508d32",
      deps = ["@com_google_code_findbugs_jsr305"],
  )

def com_google_common_html_types():
  java_import_external(
      name = "com_google_common_html_types",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/common/html/types/types/1.0.5/types-1.0.5.jar",
          "http://repo1.maven.org/maven2/com/google/common/html/types/types/1.0.5/types-1.0.5.jar",
          "http://maven.ibiblio.org/maven2/com/google/common/html/types/types/1.0.5/types-1.0.5.jar",
      ],
      jar_sha256 = "bf62fc3bf994ab1e043f3884b19cba6156181118eb7fbb6fbf7ff398a21170b2",
      deps = [
          "@com_google_guava",
          "@com_google_code_findbugs_jsr305",
          "@com_google_protobuf_java",
      ],
  )

def com_google_common_html_types_html_proto():
  native.http_file(
      name = "com_google_common_html_types_html_proto",
      sha256 = "6ece202f11574e37d0c31d9cf2e9e11a0dbc9218766d50d211059ebd495b49c3",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/raw.githubusercontent.com/google/safe-html-types/release-1.0.5/proto/src/main/protobuf/webutil/html/types/proto/html.proto",
          "https://raw.githubusercontent.com/google/safe-html-types/release-1.0.5/proto/src/main/protobuf/webutil/html/types/proto/html.proto",
      ],
  )

def com_google_dagger():
  java_import_external(
      name = "com_google_dagger",
      jar_sha256 = "8b7806518bed270950002158934fbd8281725ee09909442f2f22b58520b667a7",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/dagger/dagger/2.9/dagger-2.9.jar",
          "http://repo1.maven.org/maven2/com/google/dagger/dagger/2.9/dagger-2.9.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
      deps = ["@javax_inject"],
      generated_rule_name = "runtime",
      extra_build_file_content = "\n".join([
          "java_library(",
          "    name = \"com_google_dagger\",",
          "    exported_plugins = [\"@com_google_dagger_compiler//:ComponentProcessor\"],",
          "    exports = [",
          "        \":runtime\",",
          "        \"@javax_inject\",",
          "    ],",
          ")",
      ]),
  )

def com_google_dagger_compiler():
  java_import_external(
      name = "com_google_dagger_compiler",
      jar_sha256 = "afe356def27710db5b60cad8e7a6c06510dc3d3b854f30397749cbf0d0e71315",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/dagger/dagger-compiler/2.9/dagger-compiler-2.9.jar",
          "http://repo1.maven.org/maven2/com/google/dagger/dagger-compiler/2.9/dagger-compiler-2.9.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
      deps = [
          "@com_google_code_findbugs_jsr305",
          "@com_google_dagger//:runtime",
          "@com_google_dagger_producers//:runtime",
          "@com_google_guava",
      ],
      extra_build_file_content = "\n".join([
          "java_plugin(",
          "    name = \"ComponentProcessor\",",
          "    output_licenses = [\"unencumbered\"],",
          "    processor_class = \"dagger.internal.codegen.ComponentProcessor\",",
          "    generates_api = 1,",
          "    tags = [",
          "        \"annotation=dagger.Component;genclass=${package}.Dagger${outerclasses}${classname}\",",
          "        \"annotation=dagger.producers.ProductionComponent;genclass=${package}.Dagger${outerclasses}${classname}\",",
          "    ],",
          "    deps = [\":com_google_dagger_compiler\"],",
          ")",
      ]),
  )

def com_google_dagger_producers():
  java_import_external(
      name = "com_google_dagger_producers",
      jar_sha256 = "b452dc1b95dd02f6272e97b15d1bd35d92b5f484a7d69bb73887b6c6699d8843",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/dagger/dagger-producers/2.9/dagger-producers-2.9.jar",
          "http://repo1.maven.org/maven2/com/google/dagger/dagger-producers/2.9/dagger-producers-2.9.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
      deps = [
          "@com_google_dagger//:runtime",
          "@com_google_guava",
      ],
      generated_rule_name = "runtime",
      extra_build_file_content = "\n".join([
          "java_library(",
          "    name = \"com_google_dagger_producers\",",
          "    exported_plugins = [\"@com_google_dagger_compiler//:ComponentProcessor\"],",
          "    exports = [",
          "        \":runtime\",",
          "        \"@com_google_dagger//:runtime\",",
          "        \"@javax_inject\",",
          "    ],",
          ")",
      ]),
  )

def com_google_errorprone_error_prone_annotations():
  java_import_external(
      name = "com_google_errorprone_error_prone_annotations",
      licenses = ["notice"],  # Apache 2.0
      jar_sha256 = "cde78ace21e46398299d0d9c6be9f47b7f971c7f045d40c78f95be9a638cbf7e",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.0.19/error_prone_annotations-2.0.19.jar",
          "http://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.0.19/error_prone_annotations-2.0.19.jar",
      ],
  )

def com_google_guava():
  java_import_external(
      name = "com_google_guava",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/guava/guava/20.0/guava-20.0.jar",
          "http://repo1.maven.org/maven2/com/google/guava/guava/20.0/guava-20.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/guava/guava/20.0/guava-20.0.jar",
      ],
      jar_sha256 = "36a666e3b71ae7f0f0dca23654b67e086e6c93d192f60ba5dfd5519db6c288c8",
      exports = [
          "@com_google_code_findbugs_jsr305",
          "@com_google_errorprone_error_prone_annotations",
      ],
  )

def com_google_inject_extensions_guice_assistedinject():
  java_import_external(
      name = "com_google_inject_extensions_guice_assistedinject",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/inject/extensions/guice-assistedinject/4.1.0/guice-assistedinject-4.1.0.jar",
          "http://repo1.maven.org/maven2/com/google/inject/extensions/guice-assistedinject/4.1.0/guice-assistedinject-4.1.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/inject/extensions/guice-assistedinject/4.1.0/guice-assistedinject-4.1.0.jar",
      ],
      jar_sha256 = "663728123fb9a6b79ea39ae289e5d56b4113e1b8e9413eb792f91e53a6dd5868",
      deps = [
          "@com_google_guava",
          "@com_google_inject_guice",
          "@javax_inject",
      ],
  )

def com_google_inject_extensions_guice_multibindings():
  java_import_external(
      name = "com_google_inject_extensions_guice_multibindings",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/inject/extensions/guice-multibindings/4.1.0/guice-multibindings-4.1.0.jar",
          "http://repo1.maven.org/maven2/com/google/inject/extensions/guice-multibindings/4.1.0/guice-multibindings-4.1.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/inject/extensions/guice-multibindings/4.1.0/guice-multibindings-4.1.0.jar",
      ],
      jar_sha256 = "592773a4c745cc87ba37fa0647fed8126c7e474349c603c9f229aa25d3ef5448",
      deps = [
          "@com_google_guava",
          "@com_google_inject_guice",
          "@javax_inject",
      ],
  )

def com_google_inject_guice():
  java_import_external(
      name = "com_google_inject_guice",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/inject/guice/4.1.0/guice-4.1.0.jar",
          "http://repo1.maven.org/maven2/com/google/inject/guice/4.1.0/guice-4.1.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/inject/guice/4.1.0/guice-4.1.0.jar",
      ],
      jar_sha256 = "9b9df27a5b8c7864112b4137fd92b36c3f1395bfe57be42fedf2f520ead1a93e",
      deps = [
          "@aopalliance",
          "@org_ow2_asm",
          "@com_google_guava",
          "@com_google_code_findbugs_jsr305",
          "@javax_inject",
      ],
  )

def com_google_javascript_closure_compiler():
  java_import_external(
      name = "com_google_javascript_closure_compiler",
      licenses = ["reciprocal"],  # MPL v1.1 (Rhino AST), Apache 2.0 (JSCompiler)
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/javascript/closure-compiler-unshaded/v20170423/closure-compiler-unshaded-v20170423.jar",
          "http://repo1.maven.org/maven2/com/google/javascript/closure-compiler-unshaded/v20170423/closure-compiler-unshaded-v20170423.jar",
      ],
      jar_sha256 = "13950cb2b039ba2d0be54ad4575df6c5e6a9ee5582e31cd341ae18d099943383",
      deps = [
          "@com_google_code_gson",
          "@com_google_guava",
          "@com_google_code_findbugs_jsr305",
          "@com_google_protobuf_java",
      ],
      extra_build_file_content = "\n".join([
          "java_binary(",
          "    name = \"main\",",
          "    main_class = \"com.google.javascript.jscomp.CommandLineRunner\",",
          "    output_licenses = [\"unencumbered\"],",
          "    runtime_deps = [",
          "        \":com_google_javascript_closure_compiler\",",
          "        \"@args4j\",",
          "    ],",
          ")",
      ]),
  )

def com_google_javascript_closure_library():
  # To update Closure Library, one needs to uncomment and run the
  # js_library_files_maker and js_testing_files_maker genrules in
  # closure_library.BUILD.
  native.new_http_archive(
      name = "com_google_javascript_closure_library",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/github.com/google/closure-library/archive/0e309e9c5fb611a70a47736a2eb1204ae48ab989.tar.gz",
          "https://github.com/google/closure-library/archive/0e309e9c5fb611a70a47736a2eb1204ae48ab989.tar.gz",
      ],
      sha256 = "08b34d8efe3026f106c1ae2901a2cd1c7106be0c4173681c1fc57415e8532be9",
      strip_prefix = "closure-library-0e309e9c5fb611a70a47736a2eb1204ae48ab989",
      build_file = str(Label("//closure/library:closure_library.BUILD")),
  )

def com_google_javascript_incremental_dom():
  # To update Incremental DOM, one needs to update
  # third_party/javascript/incremental_dom/build.sh to remain compatible with
  # the upstream "js-closure" gulpfile.js target.
  # https://github.com/google/incremental-dom/blob/master/gulpfile.js
  native.http_file(
      name = "com_google_javascript_incremental_dom",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/github.com/google/incremental-dom/archive/0.5.2.tar.gz",
          "https://github.com/google/incremental-dom/archive/0.5.2.tar.gz",
      ],
      sha256 = "554a778dff5cba561a98619b2f3de5061848744644c870f718e2cdcf9bf0dccf",
  )

def com_google_protobuf_java():
  java_import_external(
      name = "com_google_protobuf_java",
      jar_sha256 = "8d7ec605ca105747653e002bfe67bddba90ab964da697aaa5daa1060923585db",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/protobuf/protobuf-java/3.1.0/protobuf-java-3.1.0.jar",
          "http://repo1.maven.org/maven2/com/google/protobuf/protobuf-java/3.1.0/protobuf-java-3.1.0.jar",
          "http://maven.ibiblio.org/maven2/com/google/protobuf/protobuf-java/3.1.0/protobuf-java-3.1.0.jar",
      ],
      licenses = ["notice"],  # New BSD and Apache 2.0
  )

def com_google_protobuf_js():
  native.new_http_archive(
      name = "com_google_protobuf_js",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/github.com/google/protobuf/releases/download/v3.1.0/protobuf-js-3.1.0.zip",
          "https://github.com/google/protobuf/releases/download/v3.1.0/protobuf-js-3.1.0.zip",
      ],
      sha256 = "b257641b1f151e91f2e159c26b015bd43c1b57fa8053e541dcd2dc9408e82a3e",
      strip_prefix = "protobuf-3.1.0",
      build_file = str(Label("//closure/protobuf:protobuf_js.BUILD")),
  )

def com_google_protobuf_protoc_linux_x86_64():
  native.http_file(
      name = "com_google_protobuf_protoc_linux_x86_64",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/github.com/google/protobuf/releases/download/v3.1.0/protoc-3.1.0-linux-x86_64.zip",
          "https://github.com/google/protobuf/releases/download/v3.1.0/protoc-3.1.0-linux-x86_64.zip",
      ],
      sha256 = "7c98f9e8a3d77e49a072861b7a9b18ffb22c98e37d2a80650264661bfaad5b3a",
  )

def com_google_protobuf_protoc_macosx():
  native.http_file(
      name = "com_google_protobuf_protoc_macosx",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/github.com/google/protobuf/releases/download/v3.1.0/protoc-3.1.0-osx-x86_64.zip",
          "https://github.com/google/protobuf/releases/download/v3.1.0/protoc-3.1.0-osx-x86_64.zip",
      ],
      sha256 = "2cea7b1acb86671362f7aa554a21b907d18de70b15ad1f68e72ad2b50502920e",
  )

def com_google_template_soy():
  java_import_external(
      name = "com_google_template_soy",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/template/soy/2017-02-01/soy-2017-02-01.jar",
          "http://repo1.maven.org/maven2/com/google/template/soy/2017-02-01/soy-2017-02-01.jar",
      ],
      jar_sha256 = "b4baa7eaa2dc00fd949d7a0a4a95ab1818876877734468f1b2a9495d7e528218",
      deps = [
          "@args4j",
          "@org_ow2_asm",
          "@org_ow2_asm_analysis",
          "@org_ow2_asm_commons",
          "@org_ow2_asm_util",
          "@com_google_guava",
          "@com_google_inject_guice",
          "@com_google_inject_extensions_guice_assistedinject",
          "@com_google_inject_extensions_guice_multibindings",
          "@com_ibm_icu_icu4j",
          "@org_json",
          "@com_google_code_findbugs_jsr305",
          "@javax_inject",
          "@com_google_common_html_types",
      ],
      extra_build_file_content = "\n".join([
          ("java_binary(\n" +
           "    name = \"%s\",\n" +
           "    jvm_flags = [\"-client\"],\n" +
           "    main_class = \"com.google.template.soy.%s\",\n" +
           "    output_licenses = [\"unencumbered\"],\n" +
           "    runtime_deps = [\":com_google_template_soy\"],\n" +
           ")\n") % (name, name)
          for name in ("SoyParseInfoGenerator",
                       "SoyToJbcSrcCompiler",
                       "SoyToJsSrcCompiler",
                       "SoyToPySrcCompiler",
                       "SoyToIncrementalDomSrcCompiler")
      ]),
  )

def com_google_template_soy_jssrc():
  native.new_http_archive(
      name = "com_google_template_soy_jssrc",
      sha256 = "ed0be8195f5a05eea82099d234dab074ca80d7c1f2e54928e0fb2ee0a7ba666d",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/google/template/soy/2017-02-01/soy-2017-02-01-jssrc_js.jar",
          "http://repo1.maven.org/maven2/com/google/template/soy/2017-02-01/soy-2017-02-01-jssrc_js.jar",
      ],
      build_file = str(Label("//closure/templates:soy_jssrc.BUILD")),
      type = "zip",
  )

def com_ibm_icu_icu4j():
  java_import_external(
      name = "com_ibm_icu_icu4j",
      licenses = ["notice"],  # ICU License (old X License)
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/com/ibm/icu/icu4j/57.1/icu4j-57.1.jar",
          "http://repo1.maven.org/maven2/com/ibm/icu/icu4j/57.1/icu4j-57.1.jar",
          "http://maven.ibiblio.org/maven2/com/ibm/icu/icu4j/57.1/icu4j-57.1.jar",
      ],
      jar_sha256 = "759d89ed2f8c6a6b627ab954be5913fbdc464f62254a513294e52260f28591ee",
  )

def com_squareup_javawriter():
  java_import_external(
      name = "com_squareup_javawriter",
      jar_sha256 = "39b054910ff212d4379129a89070fb7dbb1f341371c925e9e99904f154a22d93",
      jar_urls = [
          "http://domain-registry-maven.storage.googleapis.com/repo1.maven.org/maven2/com/squareup/javawriter/2.5.1/javawriter-2.5.1.jar",
          "http://maven.ibiblio.org/maven2/com/squareup/javawriter/2.5.1/javawriter-2.5.1.jar",
          "http://repo1.maven.org/maven2/com/squareup/javawriter/2.5.1/javawriter-2.5.1.jar",
      ],
      licenses = ["notice"],  # Apache 2.0
  )

def fonts_noto_hinted_deb():
  native.http_file(
      name = "fonts_noto_hinted_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/f/fonts-noto/fonts-noto-hinted_20161116-1_all.deb",
          "http://http.us.debian.org/debian/pool/main/f/fonts-noto/fonts-noto-hinted_20161116-1_all.deb",
      ],
      sha256 = "a71fcee2bc7820fc4e0c780bb9c7c6db8364fd2c5bac20867c5c33eed470dc51",
  )

def fonts_noto_mono_deb():
  native.http_file(
      name = "fonts_noto_mono_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/f/fonts-noto/fonts-noto-mono_20161116-1_all.deb",
          "http://http.us.debian.org/debian/pool/main/f/fonts-noto/fonts-noto-mono_20161116-1_all.deb",
      ],
      sha256 = "71ff715cf50a74a8cc11b02e7c906b69a242d3d677e739e0b2d18cd23b7de375",
  )

def javax_inject():
  java_import_external(
      name = "javax_inject",
      licenses = ["notice"],  # Apache 2.0
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",
          "http://repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",
          "http://maven.ibiblio.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",
      ],
      jar_sha256 = "91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff",
  )

def libexpat_amd64_deb():
  native.http_file(
      name = "libexpat_amd64_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/e/expat/libexpat1_2.1.0-6+deb8u3_amd64.deb",
          "http://http.us.debian.org/debian/pool/main/e/expat/libexpat1_2.1.0-6+deb8u3_amd64.deb",
      ],
      sha256 = "682d2321297c56dec327770efa986d4bef43a5acb1a5528b3098e05652998fae",
  )

def libfontconfig_amd64_deb():
  native.http_file(
      name = "libfontconfig_amd64_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/f/fontconfig/libfontconfig1_2.11.0-6.3+deb8u1_amd64.deb",
          "http://http.us.debian.org/debian/pool/main/f/fontconfig/libfontconfig1_2.11.0-6.3+deb8u1_amd64.deb",
      ],
      sha256 = "0bb54d61c13aa5b5253cb5e08aaca0dfc4c626a05ee30f51d0e3002cda166fec",
  )

def libfreetype_amd64_deb():
  native.http_file(
      name = "libfreetype_amd64_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/f/freetype/libfreetype6_2.5.2-3+deb8u1_amd64.deb",
          "http://http.us.debian.org/debian/pool/main/f/freetype/libfreetype6_2.5.2-3+deb8u1_amd64.deb",
      ],
      sha256 = "80184d932f9b0acc130af081c60a2da114c7b1e7531c18c63174498fae47d862",
  )

def libpng_amd64_deb():
  native.http_file(
      name = "libpng_amd64_deb",
      urls = [
          "http://bazel-mirror.storage.googleapis.com/http.us.debian.org/debian/pool/main/libp/libpng/libpng12-0_1.2.50-2+deb8u2_amd64.deb",
          "http://http.us.debian.org/debian/pool/main/libp/libpng/libpng12-0_1.2.50-2+deb8u2_amd64.deb",
      ],
      sha256 = "a57b6d53169c67a7754719f4b742c96554a18f931ca5b9e0408fb6502bb77e80",
  )

def org_json():
  java_import_external(
      name = "org_json",
      licenses = ["notice"],  # MIT-style license
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/json/json/20160212/json-20160212.jar",
          "http://repo1.maven.org/maven2/org/json/json/20160212/json-20160212.jar",
          "http://maven.ibiblio.org/maven2/org/json/json/20160212/json-20160212.jar",
      ],
      jar_sha256 = "0aaf0e7e286ece88fb60b9ba14dd45c05a48e55618876efb7d1b6f19c25e7a29",
  )

def org_jsoup():
  java_import_external(
      name = "org_jsoup",
      licenses = ["notice"],  # The MIT License
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/jsoup/jsoup/1.10.2/jsoup-1.10.2.jar",
          "http://repo1.maven.org/maven2/org/jsoup/jsoup/1.10.2/jsoup-1.10.2.jar",
      ],
      jar_sha256 = "6ebe6abd7775c10a49407ae22db45c840cd2cdaf715866a5b0b5af70941c3f4a",
  )

def org_ow2_asm():
  java_import_external(
      name = "org_ow2_asm",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/ow2/asm/asm/5.0.3/asm-5.0.3.jar",
          "http://repo1.maven.org/maven2/org/ow2/asm/asm/5.0.3/asm-5.0.3.jar",
          "http://maven.ibiblio.org/maven2/org/ow2/asm/asm/5.0.3/asm-5.0.3.jar",
      ],
      jar_sha256 = "71c4f78e437b8fdcd9cc0dfd2abea8c089eb677005a6a5cff320206cc52b46cc",
      licenses = ["notice"],  # BSD 3-clause
  )

def org_ow2_asm_analysis():
  java_import_external(
      name = "org_ow2_asm_analysis",
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/ow2/asm/asm-analysis/5.0.3/asm-analysis-5.0.3.jar",
          "http://repo1.maven.org/maven2/org/ow2/asm/asm-analysis/5.0.3/asm-analysis-5.0.3.jar",
          "http://maven.ibiblio.org/maven2/org/ow2/asm/asm-analysis/5.0.3/asm-analysis-5.0.3.jar",
      ],
      jar_sha256 = "e8fa2a63462c96557dcd36c25525e1264b77366ff851cf0b94eb7592b290849d",
      licenses = ["notice"],  # BSD 3-clause
      exports = [
          "@org_ow2_asm",
          "@org_ow2_asm_tree",
      ],
  )

def org_ow2_asm_commons():
  java_import_external(
      name = "org_ow2_asm_commons",
      licenses = ["notice"],  # BSD 3-clause
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/ow2/asm/asm-commons/5.0.3/asm-commons-5.0.3.jar",
          "http://repo1.maven.org/maven2/org/ow2/asm/asm-commons/5.0.3/asm-commons-5.0.3.jar",
          "http://maven.ibiblio.org/maven2/org/ow2/asm/asm-commons/5.0.3/asm-commons-5.0.3.jar",
      ],
      jar_sha256 = "18c1e092230233c9d29e46f21943d769bdb48130cc279e4b0e663f423948c2da",
      exports = ["@org_ow2_asm_tree"],
  )

def org_ow2_asm_tree():
  java_import_external(
      name = "org_ow2_asm_tree",
      licenses = ["notice"],  # BSD 3-clause
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/ow2/asm/asm-tree/5.0.3/asm-tree-5.0.3.jar",
          "http://repo1.maven.org/maven2/org/ow2/asm/asm-tree/5.0.3/asm-tree-5.0.3.jar",
          "http://maven.ibiblio.org/maven2/org/ow2/asm/asm-tree/5.0.3/asm-tree-5.0.3.jar",
      ],
      jar_sha256 = "347a7a9400f9964e87c91d3980e48eebdc8d024bc3b36f7f22189c662853a51c",
      exports = ["@org_ow2_asm"],
  )

def org_ow2_asm_util():
  java_import_external(
      name = "org_ow2_asm_util",
      licenses = ["notice"],  # BSD 3-clause
      jar_urls = [
          "http://bazel-mirror.storage.googleapis.com/repo1.maven.org/maven2/org/ow2/asm/asm-util/5.0.3/asm-util-5.0.3.jar",
          "http://repo1.maven.org/maven2/org/ow2/asm/asm-util/5.0.3/asm-util-5.0.3.jar",
          "http://maven.ibiblio.org/maven2/org/ow2/asm/asm-util/5.0.3/asm-util-5.0.3.jar",
      ],
      jar_sha256 = "2768edbfa2681b5077f08151de586a6d66b916703cda3ab297e58b41ae8f2362",
      exports = [
          "@org_ow2_asm_analysis",
          "@org_ow2_asm_tree",
      ],
  )

def phantomjs():
  platform_http_file(
      name = "phantomjs",
      amd64_urls = [
          "http://bazel-mirror.storage.googleapis.com/bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2",
          "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2",
      ],
      amd64_sha256 = "86dd9a4bf4aee45f1a84c9f61cf1947c1d6dce9b9e8d2a907105da7852460d2f",
      macos_urls = [
          "http://bazel-mirror.storage.googleapis.com/bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip",
          "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip",
      ],
      macos_sha256 = "538cf488219ab27e309eafc629e2bcee9976990fe90b1ec334f541779150f8c1",
  )


#!/usr/bin/python3

from io import BytesIO
from scipy import misc
from soco.discovery import by_name
import argparse
import requests
import socket
import struct
import sys
import time

def get_album_art(room):
    device = by_name(room)
    if device == None:
        return (None, None)
    track_info = device.get_current_track_info()
    link = track_info['album_art']
    if not link:
        return (link, None)

    res = requests.get(link)
    img_arr = misc.imread(BytesIO(res.content))

    dest_width = 320
    src_width = len(img_arr[0])
    ratio = dest_width / src_width
    arr = misc.imresize(img_arr, ratio, interp='bilinear')
    return (link, arr)

def display_album_art(image_array, device_name):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((device_name, 80))

        # Clear previous image
        s.send(struct.pack('<HHHHH', 5, 0, 0, 0, 0))
        s.recv(4)

        # send 10 row in each packet
        send_rows = 10

        h_size = len(arr[0])
        out_array = [None] * (send_rows * h_size)
        pixel_pos = 0
        out_row = 0
        for row_idx, row in enumerate(arr):
            for pixel_idx, pixel in enumerate(row):
                red = (pixel[0] & 0xf8) >> 3;
                green = (pixel[1] & 0xfc) >> 2;
                blue = (pixel[2] & 0xf8) >> 3;

                new_pix = red << 11 | green << 5 | blue
                out_array[pixel_pos] = new_pix
                pixel_pos += 1
                if pixel_pos == len(out_array):
                    head = struct.pack('<HHHHH', send_rows*h_size + 5, 0, out_row, h_size, send_rows)
                    s.send(head)
                    dataArray = bytearray()

                    for data in out_array:
                        dataArray += bytearray(struct.pack('<H', data))

                    s.send(dataArray)
                    out_row += send_rows
                    s.recv(4)
                    pixel_pos = 0

                if out_row >= 240:
                    return True
        return True
    except:
        return False

def get_play_state(room):
    device = by_name(room)
    if device == None:
        return False
    playState=device.group.coordinator.get_current_transport_info()['current_transport_state']
    switcher = {
        'PLAYING': True,
        'TRANSITIONING': True,
        'PAUSED_PLAYBACK': False,
        'STOPPED': False,
        }
    return switcher.get(playState)

# Here we go
parser = argparse.ArgumentParser()
parser.add_argument("device", help='The sonos device to get album art from', nargs='+')
parser.add_argument("display", help='The now playing display name (or IP address) to use', nargs='+')
result = parser.parse_args()

old_link = None

while(True):
    time.sleep(1)
    if not get_play_state(result.device[0]):
        continue

    link, arr = get_album_art(result.device[0])
    if not link:
        old_link = link
        continue

    if link != old_link:
        if display_album_art(arr, result.display[0]):
            old_link = link
        else:
            old_link = None


#!/usr/bin/env python3

#https://roboticsbackend.com/control-arduino-with-python-and-pyfirmata-from-raspberry-pi/#Step_1_Run_StandardFirmata_on_your_Arduino_board

#sudo python3 py_firmata_test4.py

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN, GPIO.PUD_UP)

from math import pi, cos, sin

#motor pins:
#5 = left speed (PWM)
#7 = left forwards
#8 = left backwards
#6 = right speed (PWM)
#11 = right forwards
#9 = right backwards
class Motor:
    def __init__(self, board, speed_pin_no, forward_pin_no, backward_pin_no):
        self.speed_pin = board.digital[speed_pin_no]
        self.speed_pin.mode = pyfirmata.PWM
        self.forward_pin = board.digital[forward_pin_no]
        self.backward_pin = board.digital[backward_pin_no]
        #
        self.spd = 0 #range 0-1
        self.direction = 1 #1 = forward, 0 = backward

    #spd in range 0 to 1
    #note anything less than 0.5 is rounded up to prevent motor issues
    #unless it's zero, which disables motors
    def set_speed(self, spd):
        if(0 < spd and spd < 0.5):
            spd = 0.5
        self.spd = spd

    def set_dir(self, d):
        if(d < 0.5):
            d = 0
        else:
            d = 1
        self.direction = d

    def set(self):
        # print(self.spd)
        if(self.spd == 0):
            self.speed_pin.write(0)
            self.forward_pin.write(0)
            self.backward_pin.write(0)
        else:
            self.speed_pin.write(self.spd)
            self.forward_pin.write(self.direction)
            self.backward_pin.write(1 - self.direction)

import pyfirmata
import time
if __name__ == '__main__':
    board = pyfirmata.Arduino('/dev/ttyACM0')
    print("Communication Successfully started")

    motor_left = Motor(board, 5, 7, 8)
    motor_right = Motor(board, 6, 11, 9)

    moving = 0
    pressing = False

    while True:
        #
        i = GPIO.input(11)
        b = (i < 0.5)
        if(b):
            if(not pressing):
                pressing = True
                moving = 1 - moving
        else:
            pressing = False
        #input heading from stdin
        line = input()
        vals = line.split(" ")
        # print("got", vals)
        heading_speed = float(vals[0])
        heading_angle = float(vals[1])
        #
        motor_spd_left = moving * heading_speed * cos(heading_angle + pi / 4)
        motor_spd_right = moving * heading_speed * cos(heading_angle - pi / 4)
        #

        motor_left.set_speed(abs(motor_spd_left))
        motor_left.set_dir(1 if motor_spd_left >= 0 else 0)
        motor_left.set()

        motor_right.set_speed(abs(motor_spd_right))
        motor_right.set_dir(1 if motor_spd_right >= 0 else 0)
        motor_right.set()


import datetime
from collections import defaultdict
from keywords import KEYWORD_CATS as KEYWORDS
import sys

def get_week(ts):
    d = datetime.datetime.strptime(ts, '%Y-%m-%d %H:%M:%S')
    y, w = d.isocalendar()[0:2]
    return f"{y}-{w}"

def read_data(file_name):
    data = []
    with open(file_name) as fileh:
        for line in fileh.readlines():
            pred, txt, ts = line[:-1].split("\t")[:3]
            try:
                week = get_week(ts)
            except:
                continue
            data.append({
                "week": week,
                "time": ts,
                "text": txt,
                "label": pred})
    return data

def hist(data):
    ghist = defaultdict(int)
    rhist = defaultdict(int)
    nhist = defaultdict(int)

    for twt in data:
        if twt["label"] == "Negative":
            rhist[twt["week"]] += 1
        elif twt["label"] == "Positive":
            ghist[twt["week"]] += 1
        elif twt["label"] == "Neutral":
            nhist[twt["week"]] += 1
        else:
            breakpoint()

    return rhist, ghist, nhist

def print_hist(rhist, ghist, nhist):

    for w in ghist:
        wr = rhist[w]
        wg = ghist[w]
        wn = nhist[w]
        print(f"{w}\t{wr}\t{wg}\t{wn}")

keywords = ["gos", "skjálft"]
def kw_hist(data, keywords):
    hist_data = {}
    for kw in keywords:
        hist_data[kw] = defaultdict(int)
        hist_data["both"] = defaultdict(int)
    for twt in data:
        kw_found = set()
        for kw in keywords:
            for lkw in KEYWORDS[kw]:
                if lkw in twt["text"].lower():
                    kw_found.add(kw)
        for kw in kw_found:
            hist_data[kw][twt["week"]] += 1
        if len(kw_found) > 1:
            hist_data["both"][twt["week"]] += 1

    return hist_data

def print_kw_hist(histdata):
    fkeys = list(histdata.keys())
    print("week\t" + '\t'.join(fkeys))
    for wk in histdata[fkeys[0]].keys():
        record = [wk]
        for kw in fkeys:
            record.append(str(histdata[kw][wk]))
        print("\t".join(record))

def check_keyword(tweet):
    for kw in KEYWORDS:
        for kwl in KEYWORDS[kw]:
            if kwl in tweet["text"].lower():
                return True
    return False

data = read_data(sys.argv[1])
rhist, ghist, nhist = hist(data)
print_hist(rhist, ghist, nhist)


from tkinter import Frame
from nbformat import read
import pandas as pd
import streamlit as st
import numpy as np
from pandas import DataFrame as df

st.header('Dashboard Data Pengidap Covid-19')
data_covid = pd.read_csv("covid_19_indonesia_time_series_all.csv")
st.write(data_covid)
jumlah = data_covid.iloc[:, 7:10]

st.header('Jumlah Kasus Penderita Covid-19')
jumlah_kasus = data_covid.iloc[:, 7]
total_kasus = jumlah_kasus.sum()
jumlah_kasus
st.write(total_kasus)

st.header('Jumlah Kasus Positif Covid-19')
jumlah_positif = data_covid.iloc[:, 10]
total_positif = jumlah_positif.sum()
jumlah_positif
st.write(total_positif)

st.header('Jumlah Kasus yang Pulih')
jumlah_pulih = data_covid.iloc[:, 9]
total_pulih = jumlah_pulih.sum()
jumlah_pulih
st.write(total_pulih)

st.header('Jumlah Kasus yang Meninggal')
jumlah_mati = data_covid.iloc[:, 8]
total_mati = jumlah_mati.sum()
jumlah_mati
st.write(total_mati)