import enum
import html
from typing import Any, List, Optional, Sequence, Tuple

from google.protobuf import empty_pb2
from google.protobuf import text_format
from google.rpc import code_pb2
from intrinsic.kubernetes.workcell_spec.proto import installer_pb2
from intrinsic.kubernetes.workcell_spec.proto import installer_pb2_grpc
from intrinsic.logging.proto import log_item_pb2
from intrinsic.perception.proto import frame_pb2
from intrinsic.solutions import camera_utils
from intrinsic.solutions import errors as solutions_errors
from intrinsic.solutions import ipython
from intrinsic.solutions import structured_logging

ERROR_SEPARATOR = '\n\n========\n'
NO_ERROR_FOUND_MSG = 'No error data found.'
_ERROR_REPORT_EVENT_SOURCE = 'error_report'
_COLLAPSIBLE_ERROR_HEADER_HTML = """
<meta name="viewport" content="width=device-width, initial-scale=1">

"""
_ERROR_INTRO_HTML = """
<legend style="color:#900; font-weight: bold">Errors summary:</legend>"""
_COLLAPSIBLE_SCRIPT_HTML = """"""

def _error_recovery_instructions_list_html(err: 'ErrorInstance') -> str:
  """Converts all recovery instructions into a human readable html list.

  Args:
    err: Error to retrieve instructions from.

  Returns:
    html string representation of error recovery instructions
  """
  if not err.recovery_instructions:
    return ''

  recovery_instructions = '
'
  for instruction in err.recovery_instructions:
    recovery_instructions += f'
{instruction.human_readable}
'
  recovery_instructions += '
'

  images = ''

  for d in err.data:
    if d.data and d.data.type_url:
      if frame_pb2.Frame.DESCRIPTOR.full_name in d.data.type_url:
        frame = camera_utils.get_frame_from_any(d.data)
        img = camera_utils.get_encoded_frame(frame)
        images += f""

  return (
      '
'
      '  Recovery Instructions:'
      f'     {recovery_instructions}'
      f'     {images}'
  )

def _error_to_collapsible_button_html(
    err: 'ErrorInstance',
    internal_errors: Optional[List['ErrorInstance']] = None,
) -> str:
  """Prepares html for an interactive button for an error.

  Args:
    err: Error summary
    internal_errors: Optional. Additional errors nested under this error.

  Returns:
    html representation for interactive error button.
  """
  summary = html.escape(err.human_readable_summary.replace('\n', '
'))
  error_message = html.escape(err.error_message)

  # Internal errors are represented as buttons that are only visible when the
  # parent error is uncollapsed.
  internal_buttons_html = ''
  if internal_errors:
    internal_buttons = [
        _error_to_collapsible_button_html(e) for e in internal_errors
    ]
    internal_buttons_html = ''.join(internal_buttons)

  recovery_instructions = _error_recovery_instructions_list_html(err)

  return (
      '
'
      f'  {summary}'
      '
'
      '

'
      f'
{error_message}
'
      f'  {recovery_instructions}'
      f'  {internal_buttons_html}'
      '

'
      '
'
  )

class PrintLevel(enum.Enum):
  """Config for how much detail is printed about errors."""

  OFF = 1  # No printing done.
  SUMMARY = 2  # Only a short summary about the error is printed.
  FULL_ERROR_REPORT = 3  # The full proto ErrorReport is printed.

class ErrorInstance:
  """ErrorReport augmented by further insights from error processing.

  Attributes: log_item_proto
    uid: LogItem unique ID of error.
    parent_error_uid: Set if this error happened in the scope of an error of a
      higher-level component. The UID is the LogItem UID of the parent.
  """

  def __init__(self, log_item: log_item_pb2.LogItem):
    """Constructs an ErrorInstance object.

    Args:
      log_item: LogItem proto for this ErrorInstance.
    """
    self._log_item_proto: log_item_pb2.LogItem = log_item

    # Set if this error happened in the scope of an error of a higher-level
    # component. The UID is the LogItem UID of the parent.
    self.parent_error_uid: Optional[int] = None

  def __str__(self) -> str:
    return f"{self.summary}\n\n For more details use the 'details' property."

  @property
  def uid(self) -> int:
    """LogItem unique ID of error."""
    return self._log_item_proto.metadata.uid

  @property
  def log_item_proto(self) -> log_item_pb2.LogItem:
    return self._log_item_proto

  @property
  def summary(self) -> str:
    """String representing a summary view on the error summary.

    Returns:
      String representing the summary
    """
    return (
        f'Error: {self.human_readable_summary} \nError Status:  '
        f' {code_pb2.Code.Name(self.log_item_proto.payload.error_report.description.status.code)}\n'
        f'  Message: {self.error_message}'
    )

  @property
  def details(self) -> str:
    """String representing a detailed view on the error summary.

    Returns:
      String representing the details
    """
    return (
        f'{self.summary}\n\nFull LogItem:\n'
        f'{text_format.MessageToString(self.log_item_proto)}'
    )

  @property
  def human_readable_summary(self) -> str:
    """String representing the human readable summary of the error.

    Returns:
      String representing the human readable summary
    """
    return (
        self.log_item_proto.payload.error_report.description.human_readable_summary
    )

  @property
  def error_message(self) -> str:
    """String representing the error message.

    Returns:
      String representing the error message
    """
    return self.log_item_proto.payload.error_report.description.status.message

  @property
  def recovery_instructions(self) -> Sequence[Any]:
    """Retrieves list of recovery instructions for this error.

    Returns:
      List of recovery instructions
    """
    return self.log_item_proto.payload.error_report.instructions.items

  @property
  def data(self) -> Sequence[Any]:
    """Retrieves list of additional data for this error.

    Returns:
      List of additional data
    """
    return self.log_item_proto.payload.error_report.data.items

  def additional_information(self, e: 'ErrorInstance') -> bool:
    """Checks whether additional information is provided by given error.

    Args:
      e: Error to compare for information

    Returns:
      False if given error does not provide additional Information
    """
    if self == e:
      return True
    if self.error_message == e.error_message:
      if self.recovery_instructions and not e.recovery_instructions:
        return False
      if self.recovery_instructions == e.recovery_instructions:
        if self.data and not e.data or self.data == e.data:
          return False
    return True

class ErrorGroup:
  """List of error summaries with utilities.

  Attributes: errors
    workcell_health_issue: Empty if the workcell was healthy when this object
      was constructed, otherwise a description of the health status.
  """

  def __init__(
      self, errors: List[ErrorInstance], workcell_health_issue: str = ''
  ):
    """Constructs an ErrorGroup object.

    Args:
      errors: List of ErrorInstance objects.
      workcell_health_issue: Empty if the workcell is healthy when this object
        is constructed, otherwise a description of the health status.
    """
    self._errors: List[ErrorInstance] = errors

    # We reverse to order to show the most recent error first.
    def negative_acquisition_time(e: ErrorInstance) -> Tuple[int, int]:
      return (
          -e.log_item_proto.metadata.acquisition_time.seconds,
          -e.log_item_proto.metadata.acquisition_time.nanos,
      )

    self._errors.sort(key=negative_acquisition_time)

    self._process_error_hierarchy()
    self.workcell_health_issue: str = workcell_health_issue

  def __str__(self) -> str:
    return self.summary

  @property
  def errors(self) -> List[ErrorInstance]:
    return self._errors

  @property
  def summary(self) -> str:
    """String representing a summary view on the error summaries.

    Returns:
      String representing the summary view
    """
    result = ''
    if self.workcell_health_issue:
      result += self.workcell_health_issue
    if not self.errors:
      result += NO_ERROR_FOUND_MSG
    else:
      result += '\n===Errors summary:===\n'
      result += ERROR_SEPARATOR.join([e.summary for e in self.errors])
    return result

  @property
  def details(self) -> str:
    """String representing a detailed view on the error summaries.

    Returns:
      String representing the details including the full ErrorReport proto.
    """
    result = ''
    if self.workcell_health_issue:
      result += self.workcell_health_issue
    if not self.errors:
      result += NO_ERROR_FOUND_MSG
    else:
      result += '\nDetailed error summaries:\n'
      result += ERROR_SEPARATOR.join([e.details for e in self.errors])
    return result

  def print_info(self, print_level: PrintLevel = PrintLevel.SUMMARY) -> None:
    """Print information about errors.

    Args:
      print_level: Config for how much detail is printed.
    """
    if print_level is PrintLevel.OFF:
      return
    elif print_level is PrintLevel.SUMMARY:
      print(self.summary)
    elif print_level is PrintLevel.FULL_ERROR_REPORT:
      print(self.details)
    else:
      raise solutions_errors.InvalidArgumentError(
          f'Unknown PrintLevel: {print_level} (value = {print_level.value})'
      )

  def display_only_in_ipython(self) -> None:
    """Display an object but only if running in IPython."""
    ipython.display_html_if_ipython(self._repr_html_(), newline_after_html=True)

  def _process_error_hierarchy(self) -> None:
    """Extracts hierarchical relationships between instances in self.errors.

    The results are stores within the error instances.
    """
    for err in self.errors:
      # Process subskill invocations. A subskill is expected to contain the ID
      # of its parent skill error in its LogItem context.
      if err.log_item_proto.context.parent_skill_id != 0:
        # Note that we currently assume only one nesting level.
        def is_parent(
            parent: ErrorInstance, child: ErrorInstance = err
        ) -> bool:
          """Evaluates whether 'child' is a child of 'parent'."""
          return parent.log_item_proto.context.parent_skill_id == 0 and (
              parent.log_item_proto.context.skill_id
              == child.log_item_proto.context.parent_skill_id
          )

        potential_parents = list(filter(is_parent, self.errors))
        if len(potential_parents) == 1:
          err.parent_error_uid = potential_parents[0].uid
        else:
          print(
              'Warning: Unexpected parent relationship of the error with UID'
              f' {err.uid}. Expected 1 parent but found '
              f'{len(potential_parents)}.'
          )

  def _get_top_level_errors(self) -> List[ErrorInstance]:
    """Returns all errors which are not nested below another parent error.

    Returns:
      List of errors which do not have child errors.
    """
    return list(filter(lambda err: not err.parent_error_uid, self.errors))

  def _get_children(self, uid: int) -> List[ErrorInstance]:
    """Returns all errors that are nested below a given error.

    Args:
      uid: LogItem UID of error.

    Returns:
      List children.
    """
    return list(
        filter(
            lambda e: e.parent_error_uid and e.parent_error_uid == uid,
            self.errors,
        )
    )

  def _get_unique_top_level_errors(self) -> List[ErrorInstance]:
    """Returns all errors which are not nested below another parent error.

    Additionally removes errors which group other top-level errors.

    Returns:
      List of unique errors which do not have child errors.
    """
    top_level_errors = self._get_top_level_errors()

    keep = []
    for e in top_level_errors:
      keep.append(e)
      for x in top_level_errors:
        if x not in keep:
          break
        if not e.additional_information(x):
          keep.remove(x)
        elif not x.additional_information(e):
          keep.remove(e)
          break

    return keep

  def _repr_html_(self) -> str:
    """Used to display rich information about errors in a Jupyter notebook.

    In a Jupyter notebook display(<this_object>) will render this HTML.

    Returns:
      Rich html representation of errors.
    """

    errors_repr = [
        _error_to_collapsible_button_html(
            err, internal_errors=self._get_children(err.uid)
        )
        for err in self._get_unique_top_level_errors()
    ]

    body = ''
    if self.errors:
      body = f"""
 <fieldset>
 {_ERROR_INTRO_HTML}
 {html.escape(self.workcell_health_issue)}
 {"".join(errors_repr)}
 </fieldset>
 {_COLLAPSIBLE_SCRIPT_HTML}
 """
    else:
      body = 'No errors found.'
    return f"""{_COLLAPSIBLE_ERROR_HEADER_HTML}

                  {body}
                """

class ErrorsLoader:
  """Extracts error reports and prepares for presentation to user.

  ErrorReports are structured data which is logged by various intrinsic
  components at
  runtime. This class uses the DataLogger as the backend storing the reports. It
  is both used as an internal helper class within workcell client modules to
  expose errors, as well as a separate module by the user.
  """

  def __init__(
      self,
      structured_logs: structured_logging.StructuredLogs,
      installer_service_stub: installer_pb2_grpc.InstallerServiceStub,
  ):
    """Constructs an Entity object.

    Note that already during construction, we fetch the list of children and
    cache them.

    Args:
      structured_logs: DataLogger client.
      installer_service_stub: Installer service to check the workcell health.
    """
    self._structured_logs: structured_logging.StructuredLogs = structured_logs
    self._installer_service_stub: installer_pb2_grpc.InstallerServiceStub = (
        installer_service_stub
    )

  def list_error_data(
      self,
      executive_plan_id: Optional[int] = None,
      last_seconds_to_read: int = 1200,
  ) -> ErrorGroup:
    """Load all ErrorReports for a given plan execution.

    This call might take a few seconds as data needs to be loaded from the
    backend.

    Note that currently only data for the last 6 hours is stored on prem. By
    default only the last 20 min are considered. If you have a longer execution
    or would like to load errors from executions in the past, adjust
    'last_seconds_to_read'.

    Args:
      executive_plan_id: Optional Log ID of the plan to consider. Can be e.g.
        found in ExecutiveState.
      last_seconds_to_read: Only considers recent logs within this timeframe

    Returns:
      List of LogItems containing metadata and the ErrorReport payload
    """
    print('Reading error reports...', end='')
    log_items = self._structured_logs.query(
        _ERROR_REPORT_EVENT_SOURCE, last_seconds_to_read
    )
    print('Done.')
    if not log_items:
      return ErrorGroup([], workcell_health_issue=self._load_workcell_health())
    if not executive_plan_id:
      return ErrorGroup(
          [ErrorInstance(proto) for proto in log_items],
          workcell_health_issue=self._load_workcell_health(),
      )
    log_item_proto_list = list(
        filter(
            lambda item: item.context.executive_plan_id == executive_plan_id,
            log_items,
        )
    )
    return ErrorGroup(
        [ErrorInstance(proto) for proto in log_item_proto_list],
        workcell_health_issue=self._load_workcell_health(),
    )

  def _load_workcell_health(self) -> str:
    """Loads the workcell health and returns an error message if not healthy.

    No retries, to avoid blocking the summary of errors.

    Returns:
      Empty if healthy, description otherwise.
    """
    try:
      response = self._installer_service_stub.GetInstalledSpec(
          empty_pb2.Empty()
      )
      error_reason = ''
      if isinstance(response.error_reason, str) and response.error_reason:
        error_reason = '\n\tError reason: ' + response.error_reason
      if response.status == installer_pb2.GetInstalledSpecResponse.HEALTHY:
        return ''
      elif response.status == installer_pb2.GetInstalledSpecResponse.PENDING:
        return (
            'WORKCELL NOT HEALTHY: Workcell backends not healthy now but '
            'expected to become healthy again automatically.'
            + error_reason
            + '\n'
        )
      elif response.status == installer_pb2.GetInstalledSpecResponse.ERROR:
        return (
            'WORKCELL NOT HEALTHY: Workcell backend is unhealthy and not '
            'expected to recover without intervention. Try restarting your '
            'app.'
            + error_reason
            + '\n'
        )
    except Exception:  # pylint: disable=broad-except
      return 'WORKCELL HEALTH UNKNOWN: Could not load the workcell status.\n'
    return (
        'WORKCELL HEALTH UNKNOWN: Unknown health status of workcell detected.\n'
    )


from django.urls import path, include
from . import views

urlpatterns = [
    path('medicalstaff/', views.medicalstaff, name='medicalstaff'),
    path('profile/', views.user_profile, name='user_profile'),
    path('userupdate/', views.user_update, name='user_update'),

    # API Routes
    path('getprofile/', views.getprofile, name='getprofile'),
    path('getpersonal/', views.getpersonal, name='getpersonal'),
    path('employees/', views.employees, name='employees'),
    path('getprofession/<int:id>', views.getprofession, name='getprofession'),
]


str1 = int(input())
str2 = int(input())
str1 = str(str1)
str2 = str(str2)
check = True
if int(str1) < int(str2):
    check = False
    t = str1
    str1 = str2
    str2 = t
str1 = str1[::-1]
str2 = str2[::-1]
nho = 0
xau = ''
for i in range(len(str2)):
    if ord(str1[i]) - 48 - nho >= ord(str2[i]) - 48:
        hieu = (ord(str1[i]) - 48) - (ord(str2[i]) - 48) - nho
        xau += chr(hieu + 48)
        nho = 0
    else:
        hieu = (ord(str1[i]) - 48 + 10) - (ord(str2[i]) - 48) - nho
        xau += chr(hieu + 48)
        nho = 1
for i in range(len(str2), len(str1)):
    if ord(str1[i]) - 48 - nho >= 0:
        hieu = (ord(str1[i]) - 48) - nho
        xau += chr(hieu + 48)
        nho = 0
    else:
        hieu = (ord(str1[i]) - 48 + 10) - nho
        xau += chr(hieu + 48)
        nho = 1
xau = xau[::-1]
xau = int(xau)
xau = str(xau)
if int(xau) == 0:
    print(0)
elif check == False:
    xau = '-' + xau
    print(xau)
elif check:
    print(xau)


# importing csv
import os
csvpath = os.path.join('Resources', 'budget_data.csv')
import csv
with open(csvpath, newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')
    print(csvreader)
    next(csvreader)
    first_month = next(csvreader)
 # defining terms
    print(first_month)
    months = 1
    amount = int(first_month[1])
    greatest_increase = 0
    greatest_decrease = 0
    previous_amount = int(first_month[1])
    total_difference = 0
    difference_count = 0
# creating loop of csv
# looping through for total months and total amounts
    for row in csvreader:
        months = months + 1
        amount = amount + int(row[1])
        difference = previous_amount - int(row[1])
# adding to loop to find average
        total_difference = total_difference + difference
        difference_count = difference_count + 1
# looping to get increases and decreases
        if difference > greatest_increase:
            greatest_increase = difference
        if difference < greatest_decrease:
            greatest_decrease = difference
        previous_amount = int(row[1])
# calculating total months
    print(f'Months: {months}')
# calculating total amount of Profit/Losses
    print(f'Total Amount: {amount}')
# calculating average of changes in Profit/Losses
    print(f'Average Changes: {total_difference/difference_count}')
# Find the greatest increase in profits (date and amount)
    print(f'Greatest Increase: {greatest_increase}')
# Find the greatest decrease in losses
    print(f'Greatest Decrease: {greatest_decrease}')

# Output new file
output_file = os.path.join('budget_data.csv')
with open(output_file, "w") as datafile:
    writer = csv.writer(datafile)
    writer.writerow(["Months", "Total Amount", "Average Changes", "Greatest Increase", "Greatest Decrease"])


import requests
import base64

with open('LEE.jpeg', 'rb') as f:
    im_b64 = base64.b64encode(f.read())

payload = {'type': 'jpeg', 'image': im_b64}

url = "http://localhost:8080/upload"

r = requests.post(url, data=payload)

# convert server response into JSON format.
print(r.json())


from os import path
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_toastr import Toastr
from flask_login import LoginManager
import logging

logger = logging.getLogger(__name__)

db = SQLAlchemy()
toastr = Toastr()
DATABASE_NAME = "database.db"

def create_app() -> Flask:
    app = Flask(__name__)

    app.config["SECRET_KEY"] = "secret"
    app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{DATABASE_NAME}"

    db.init_app(app)
    toastr.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix="/")
    app.register_blueprint(auth, url_prefix="/")

    from .models import User

    create_database(app)

    login_manager = LoginManager()
    login_manager.login_view = "auth.login"
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

def create_database(app: Flask) -> None:
    if not path.exists("src/" + DATABASE_NAME):
        db.create_all(app=app)
        logger.info("Database Initialized!")


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('patients', '0029_profilesuser_bp_interval'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='profilesuser',
            name='id_blood',
        ),
    ]


import requests

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.pagination import LimitOffsetPagination
from rest_framework import status

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

from .serializers import ClimateChangeInfo, ClimateChangeInfoSerializer

# Create your views here.

# To ensure data-type consistency, type check is added,
# if failed then by default 0 will be assigned
def custom_float(num):
    try:
        if type(eval(num)) == float:
            return float(num)
        elif type(eval(num)) == int:
            return int(num)
    except Exception as e:
        return 0

# Parsing climate change data
def parse_weather_data(region, parameter):
    try:
        url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/{0}/date/{1}.txt'.format(parameter, region)
        response = requests.get(url)
        data = response.text.split('\n')
        last_updated_date = ' '.join(data[4].split()[-2:])
        data_points = []
        for row in data[6:-1]:
            data_points.append(list(map(custom_float, row.split())))
        body = {
            'last_updated_date': last_updated_date,
            'data_points': data_points
        }
        return body
    except Exception as e:
        return {'error': 'Invalid region, parameter combination'}

test_param = [
    openapi.Parameter('region', openapi.IN_QUERY, description="Enter region name", type=openapi.TYPE_STRING),
    openapi.Parameter('parameter', openapi.IN_QUERY, description="Enter parameter name", type=openapi.TYPE_STRING),
    openapi.Parameter('limit', openapi.IN_QUERY, description="Enter limit value", type=openapi.TYPE_INTEGER),
    openapi.Parameter('offset', openapi.IN_QUERY, description="Enter offset value", type=openapi.TYPE_INTEGER),
]

class GetClimateChangeDataView(APIView):
    @swagger_auto_schema(
        responses={
            405: openapi.Response('Method Not Allowed', openapi.Schema(type=openapi.TYPE_OBJECT)),
        }
    )
    def post(self, request):
        return Response({'error' : 'Invalid Request Method'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
    @swagger_auto_schema(
        manual_parameters=test_param,
        responses={
            200: ClimateChangeInfoSerializer(many=True),
            400: openapi.Response('Bad Request', openapi.Schema(type=openapi.TYPE_OBJECT)),
        }
    )
    def get(self, request):
        paginator = LimitOffsetPagination()
        response = parse_weather_data(request.GET['region'], request.GET['parameter'])
        if 'error' in response:
            return Response(response, status=status.HTTP_400_BAD_REQUEST)
        data_points = response['data_points']
        climate_change_info_list = []
        for data in data_points:
            climate_change_object = ClimateChangeInfo(
                year = data[0],
                jan = data[1],
                feb = data[2],
                mar = data[3],
                apr = data[4],
                may = data[5],
                jun = data[6],
                jul = data[7],
                aug = data[8],
                sep = data[9],
                oct = data[10],
                nov = data[11],
                dec = data[12],
                win = data[13],
                spr = data[14],
                sum = data[15],
                aut = data[16],
                ann = data[17]
            )
            climate_change_info_list.append(climate_change_object)
        # the many param informs the serializer that it will be serializing more than a single climate change object.
        query_set = climate_change_info_list
        context = paginator.paginate_queryset(query_set, request)
        serializer = ClimateChangeInfoSerializer(context, many=True)
        return paginator.get_paginated_response(serializer.data)

if __name__ == '__main__':
    parse_weather_data('England_SE_and_Central_S', 'Rainfall')


#! /usr/bin/env python

# Thomas Kennedy
# February 2014
# Assignment 5 Solution

import os
import sys
import random
import math

#Constants residential customers
RES_BILL_PROC_FEES    =  4.50
RES_BASIC_SERV_COST   = 20.00
RES_COST_PREM_CHANNEL =  8.00

#Constants business customers
BUS_BILL_PROC_FEES    = 15.00
BUS_BASIC_SERV_COST   = 75.00
BUS_BASIC_CONN_COST   = 5.00

#
# Print a styled and centered heading
#
def printHeading(title, width=40, outs=sys.stdout):
    print("=" * width, file=outs)
    print(title.center(width), file=outs)
    print("=" * width, file=outs)

#Main Function
def main():
    #Variable declaration and intialization
    total_residential = 0    # Total Profit from residential customers
    total_business    = 0    # Total Profit from business customers

    num_residential   = 0    # Number of residential customers
    num_business      = 0    # Number of business customers

    try:
        #open the input file
        in_file = open( "A4-input.txt", "r")
    except:
        print("\nError: Could not open file.\n")
        sys.exit(1)

    #print Heading
    printHeading( "COMPUTING THE CABLE BILL", 40 )

    #Loop Until the End of the File
    for line in in_file:

        #create a list of items on the line-after stripping all whitespace
        line = [x.strip() for x in line.split()]

        #Read the account number
        account_number = line[0]

        #Convert Lowercase Letter to Uppercase Letter
        account_type = line[1].upper()

        print("\nCurrently Modifying:")
        print(" {:<15}: {:<20}".format("Acct #", account_number))
        print(" {:<15}:".format("Acct Type"), end=' ')

        if account_type == "R":
            print("Residential\n")

            num_premium_ch = int( input("Enter # of premium channels: ") )

            account_balance = ( RES_BILL_PROC_FEES + RES_BASIC_SERV_COST
                             + ( num_premium_ch * RES_COST_PREM_CHANNEL )
                              )

            total_residential += account_balance
            num_residential += 1

            print("\n{:<15}: $ {:<.2f}".format("New Balance", account_balance ))

        elif account_type == "B":
            print("Business\n\n")

            num_serv_conn = int( input("Enter # of service connections: " ) )

            #Calculate Amount Due
            account_balance = ( BUS_BILL_PROC_FEES + BUS_BASIC_SERV_COST
                               +( num_serv_conn  * BUS_BASIC_CONN_COST )
                              )

            total_business += account_balance
            num_business += 1

            print("\n{:<15}: $ {:<.2f}".format("New Balance", account_balance ))

        else:
            print("Invalid\n")

        print("-" * 40)

    printHeading( "PROFIT SUMMARY", 40 )

    print("{:<18}: {:>8.2f}".format("Residential Accts", num_residential))
    print("{:<18}: {:>8.2f}".format("Business Accts"    , num_business))
    print()
    print("{:<18}: {:>8.2f}".format("Residential Profit", total_residential))
    print("{:<18}: {:>8.2f}".format("Business Profit"   , total_business))
    print("{:<18}: {:>8.2f}".format("Total Profit",( total_business + total_residential ) ))

    in_file.close()

if __name__ == "__main__":
     main()


import settings
from django.test import TestCase
import sys, os, vcr, dhis2
from dhis2.dhis2_match import *
from dhis2.models import Dhis2_Mtrac_Indicators_Mapping
import json
from mock import *
from eav.models import Attribute

FIXTURES = os.path.abspath(dhis2.__path__[0]) + "/tests/fixtures/cassettes/"

DHIS2_HMIS033b_INDICATOR_URL= settings.DHIS2_HMIS033b_INDICATOR_URL
DHIS2_API_URL = settings.DHIS2_BASE_URL+ '/api/'

JSON_EXTENSION = '.json'

class Test_Dhis2_Fetch_Health_Indicators(TestCase):

    def setUp(self):
        self.fetcher = Dhis2_Fetch_Health_Indicators(97)

    def test_get_hmis033b_dataset(self):
       with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
           obj = self.fetcher.fetch(JSON_EXTENSION, DHIS2_HMIS033b_INDICATOR_URL)
           self.assertIsNotNone(obj)

    def test_clean_indicator_names_from_dhis2(self):
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2('Bubukwanga - WEP    '), 'Bubukwanga')
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2('Bubukwanga (helloo there , remove me)'), 'Bubukwanga')
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2('Bubukwanga - WEP  (asdasdasd ) '), 'Bubukwanga')
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2('Bubukwanga  (asdasdasd) - WEP '), 'Bubukwanga')
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2('(asdasdasd) - WEP '), 'asdasdasd')
        self.assertEqual(self.fetcher.clean_indicator_names_from_dhis2(' (asdasdasd) '), 'asdasdasd')

    def test_compare_strings(self):
        self.assertEqual(self.fetcher.compare_strings('Bubukwanga', 'Bubukwanga'), 100)
        self.assertEqual(self.fetcher.compare_strings('Bubukwanga', 'Bundibugyo'), 50)
        self.assertEqual(self.fetcher.compare_strings('a', 'b'), 0)

    def test_get_indicators_names_match_level(self):
        self.assertTrue(self.fetcher.get_indicators_names_match_level("Adverse Events Following Immunization Cases - WEP","Adverse Events Following Immunization Cases")==100)
        self.assertTrue(self.fetcher.get_indicators_names_match_level("some name - WEP","soome name")>90)

    def test_find_matching_indicator_from_mtrack(self):
        test_dhis2_name  = u'Adverse Events Following Immunization Cases - WEP'
        expected = u'Adverse Events Following Immunization cases'
        matching_mtrack= self.fetcher.find_matching_indicator_from_mtrack(test_dhis2_name)
        self.assertEquals(matching_mtrack.id , 360)

    def test_find_matching_known_indicator_from_mtrack(self):
        test_dhis2_name  = u'(Yellow Used)'
        matching_mtrack= self.fetcher.find_matching_indicator_from_mtrack(test_dhis2_name)
        self.assertEquals(matching_mtrack.id , 340)

    def test_find_matching_indicator_from_mtrack(self):
        test_dhis2_name  = u'I DONT EXIST IN MTRACK...YEAHHHH - WEP'
        self.assertEquals(self.fetcher.find_matching_indicator_from_mtrack(test_dhis2_name),None)

    def test_find_matches_and_update_mapping_table(self):
        Dhis2_Mtrac_Indicators_Mapping.objects.all().delete()
        arbitrary_disease = {"name":u"Typhoid Fever Cases - WEP", "id": u"IkI01xB7RIi", "href":DHIS2_API_URL + "dataElements/IkI01xB7RIi", "combo_id":u"92DkrSOchnL" }
        self.fetcher.find_matches_and_update_mapping_table(arbitrary_disease)
        record = Dhis2_Mtrac_Indicators_Mapping.objects.filter(dhis2_uuid='IkI01xB7RIi')
        self.assertIsNotNone(record)
        self.assertEquals(len(record), 1)
        record = record[0]
        self.assertEquals( record.dhis2_uuid, arbitrary_disease['id'])
        self.assertEquals( record.dhis2_combo_id, arbitrary_disease['combo_id'])
        self.assertEquals( record.eav_attribute, Attribute.objects.get(slug='cases_tf'))

    def test_malaria_case_is_mapped_to_cases_ma_slug_and_NOT_doc_ma(self):
        Dhis2_Mtrac_Indicators_Mapping.objects.all().delete()
        disease = {"name":u"Malaria Cases - WEP", "id": u"fclvwNhzu7d", "href":DHIS2_API_URL + "dataElements/fclvwNhzu7d", "combo_id":u"92DkrSOchnL" }
        self.fetcher.find_matches_and_update_mapping_table(disease)
        record = Dhis2_Mtrac_Indicators_Mapping.objects.filter(dhis2_uuid='fclvwNhzu7d')
        self.assertIsNotNone(record)
        self.assertEquals(len(record), 1)
        record = record[0]
        self.assertEquals( record.dhis2_uuid, disease['id'])
        self.assertEquals( record.dhis2_combo_id, disease['combo_id'])
        self.assertEquals( record.eav_attribute, Attribute.objects.get(slug='cases_ma'))
        self.assertNotEquals(record.eav_attribute, Attribute.objects.get(slug='doc_ma'))

    def test_get_indicator_combo_option_id_default(self):
        category_combo_url = DHIS2_API_URL + 'categoryCombos/92DkrSOchnL'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            self.assertEqual(self.fetcher.get_indicator_combo_option_id(category_combo_url), 'gGhClrV5odI')

    def test_get_indicator_combo_option_non_default(self):
        category_combo_url = DHIS2_API_URL + 'categoryCombos/7O1Zh4rJoIn'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            self.assertIsNone(self.fetcher.get_indicator_combo_option_id(category_combo_url) )

    def test_get_category_combos_from_combo_category_option(self):
        category_combo_url = DHIS2_API_URL + 'categoryCombos/7O1Zh4rJoIn'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            indicators = self.fetcher.get_category_combos_from_combo_category_option(category_combo_url)

            self.assertEquals(len(indicators),12)
            for indicator in indicators :
                 self.assertIsNotNone(indicator['combo_id'])
                 self.assertIsNotNone(indicator['name'])
                 self.assertIsNotNone(indicator['href'])

    def test_get_combo_id_from_indicator(self):
        url = DHIS2_API_URL + 'dataElements/fTwT8uX9Uto'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            combo_id = self.fetcher.get_combo_id_from_indicator(url)
            self.assertEquals(combo_id,'gGhClrV5odI')

    def test_update_mappings_table_with_default_indicator(self):
        element_id = 'fTwT8uX9Uto'
        disease_url = DHIS2_API_URL + 'dataElements/' + element_id
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            self.fetcher.update_mappings_table(disease_url)
            record = Dhis2_Mtrac_Indicators_Mapping.objects.filter(dhis2_uuid= element_id )
            self.assertEqual(len(record), 1)
            record=record[0]
            self.assertEqual(record.dhis2_combo_id, 'gGhClrV5odI')
            self.assertEqual(record.eav_attribute, Attribute.objects.get(slug='cases_ae'))

    def test_update_mappings_table_with_non_default_indicator(self):
        indicator_url = DHIS2_API_URL + 'dataElements/KPmTI3TGwZw'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            self.fetcher.update_mappings_table(indicator_url)
            record = Dhis2_Mtrac_Indicators_Mapping.objects.filter(dhis2_uuid= 'KPmTI3TGwZw')
            self.assertEqual(len(record), 7)

            record_mtrac = sorted([a_record.eav_attribute.id for a_record in record])
            expected_list = sorted([Attribute.objects.get(slug='test_sm').id,
                             Attribute.objects.get(slug='test_rdt').id,
                             Attribute.objects.get(slug='test_rdp').id,
                             Attribute.objects.get(slug='test_mtc').id,
                             Attribute.objects.get(slug='test_mtp').id,
                             Attribute.objects.get(slug='test_pcc').id,
                             Attribute.objects.get(slug='test_pcy').id ])

            self.assertListEqual(record_mtrac , expected_list)

    def test_fetch_elements_from_dataset(self):
        dataset_url = DHIS2_API_URL + 'dataSets/V1kJRs8CtW4'
        with vcr.use_cassette(FIXTURES + self.__class__.__name__ + "/" + sys._getframe().f_code.co_name + ".yaml"):
            elements = self.fetcher.fetch_elements_for_dataset(dataset_url)
            self.assertTrue(len(elements),39)


import pandas as pd
import matplotlib.pyplot as plt

def plot(path, name):
    df = pd.read_csv(path["data_folder"] + "robotSensors", index_col=False, sep=" ", header=None, names=["t", "light", "bluelight", "redlight", "groundmemory", "redbattery"])

    fig, ax = plt.subplots(2)
    df.plot(x="t", y="light", color="tab:orange", ax=ax[0])
    df.plot(x="t", y="bluelight", color="tab:blue", ax=ax[0])
    df.plot(x="t", y="groundmemory", color="tab:brown", ax=ax[0])

    df.plot(x="t", y="redlight", color="tab:red", ax=ax[1])
    df.plot(x="t", y="redbattery", color="tab:green", ax=ax[1])
    plt.savefig(path["exp_folder"] + name, bbox_inches='tight')


import serial
from config import CONFIG
import logging
import time

class DisplayIO:

    def connect(self):
        try:
            ser = serial.Serial(CONFIG.SERIALPORT, CONFIG.SERIALRATE, timeout=CONFIG.SERIALTIMEOUT)
            ser.flush()
            msg = f"connect(): Connected to {ser}"
            logging.debug(msg)
            return ser
        except Exception as error:
            msg = f"connect(): Could not connect to serial port {CONFIG.SERIALPORT}"
            logging.error(msg)
            logging.debug(error)
            return 0

    def getserialdata(self, serial_connection):
        try:
            data = serial_connection.readline().decode('utf-8').rstrip()
            msg = f"getserialdata(): String received: {data}"
            logging.debug(msg)
            return data
        except Exception as error:
            msg = f"connect(): Error receiving serial data!"
            logging.error(msg)
            logging.debug(error)
            return 0

    def sendserialdata(self, serial_connection, data):
        send = serial_connection.write(data.encode('utf-8'))
        time.sleep(0.1)
        msg = f"sendserialdata(): Data sent: {send}"
        logging.debug(msg)
        return send


""" Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3 """

from typing import List

class TreeNode:
    def __init__(self, x):
        self.x = x
        self.left = None
        self.right = None

class Solution:
    def binaryTreePath(self, root: TreeNode) -> List[str]:

        def dfs(root, path):

            if not root.left and not root.right:
                path.append(path)
                return

            if root.left:
                dfs(root.left, path + '->' + str(root.left.val))

            if root.right:
                dfs(root.right, path + '->' + str(root.right.val))

        paths = []
        if not root:
            return paths

        dfs(root, str(root.val))

        return paths


import unittest
import urllib.parse

from tests.components.http_base import TestHttpMessageApiMixIn
from then.components.http import CONTENT_TYPE_ALIASES
from then.components.slack import Slack, SlackMessage

class TestSlack(TestHttpMessageApiMixIn, unittest.TestCase):
    team = 'T00000000'
    bot = 'B00000000'
    token = 'XXXXXXXXXXXXXXXXXXXXXXXX'
    body = 'foo'

    def get_component(self, **kwargs):
        return Slack(self.team, self.bot, self.token, **kwargs)

    def test_send(self):
        slack = self.get_component()
        message = slack.message(body=self.body)
        req_text = 'payload={}'.format(urllib.parse.quote(message.get_body()['payload'])).replace('%20', '+')
        self.session_mock.post(SlackMessage.url_pattern.format(component=self),
                               request_headers={'Content-Type': CONTENT_TYPE_ALIASES['form']},
                               additional_matcher=lambda req: req.text == req_text)
        message.send()

    def test_payload_text(self):
        then = self.get_component()
        self.assertEqual(then.message(body=self.body).get_payload(), {
            'text': self.body, 'icon_emoji': then.icon, 'username': then.from_,
        })

    def test_payload_icon_emoji(self):
        icon = ':foo:'
        then = self.get_component(icon=icon)
        self.assertEqual(then.message(body=self.body).get_payload().get('icon_emoji'), icon)

    def test_payload_icon_url(self):
        icon = 'http://path.to/image.jpg'
        then = self.get_component(icon=icon)
        self.assertEqual(then.message(body=self.body).get_payload().get('icon_url'), icon)


# -*- coding: utf-8 -*-
import numpy as np
import scipy as sp
from sklearn import tree
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.cross_validation import train_test_split

''' 数据读入 '''
''' 列表类型data'''
data = []
labels = []
fr=open("./disvurl1.txt","r")

ci=0;
while True:
    line=fr.readline()
    if line:
        ci=ci+1
        tokens = line.strip().split('|')
        data.append([str(tk) for tk in tokens[:-1]])
        #print("the",ci,"line is ",data)
        labels.append(tokens[-1])
    else:
        break
fr.close();

print("the",ci,"line is ",data)

x = np.array(data)
print("original y is :",np.array(labels))
#print("xis:",x)
labels = np.array(labels)
#print("labelsis:",labels)
#print("labels shape",labels.shape)
y = np.zeros(labels.shape)
#print("yis:",y)
''' 标签转换为0/1/2/3/4/.. '''
y[labels=='BRAN']=0
y[labels=='XXXX']=1
y[labels=='SHOW']=2
y[labels=='EVAL']=3
y[labels=='PROL']=4
y[labels=='SUBS']=5
y[labels=='PASS']=6
print("转换后yis:",y)

'''
import pandas as pd
pdx=pd.DataFrame(x)
print("framex is:",pdx)
print("type of framex is",pdx.dtypes)
print("dfhead: ",pdx.head(2))
print("dftail: ",pdx.tail(2))
'''


'''
2. (intersecao) Faça um programa que preencha duas listas A e B de 5 posições
com números inteiros. As listas representam conjuntos e seus elementos
estão em uma ordem qualquer. O programa deve calcular e imprimir uma
lista C tal que C = A ∩ B, ou seja, C deve conter a interseção entre
os conjuntos A e B.
'''

listaA = []
listaB = []
listaC = []

#Preencher o conjunto A
for i in range(5):
    aux = int(input("Digite a lista A: "))
    listaA.append(aux)

#Preencher o conjunto B
for i in range(5):
    aux = int(input("Digite a lista B: "))
    listaB.append(aux)

#Achar a intersecao
for i in listaA:
    if(i in listaB):
        listaC.append(i)

print(f"A interseção é: {listaC}")


#! /usr/bin/env python3

"""plot figures for mirna editing events"""

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from barplot import X_COL, Y_COL

EDITED_IN_COL = "EDITED IN"

def count_seed_editing_events(df: pd.DataFrame) -> pd.DataFrame:
    if df.shape[0] < 1:
        return pd.DataFrame({})

    seed_edit = set()
    for _, mirline in df[df.TYPE == "miRNA"].iterrows():
        seq_len = len(mirline.REF_SEQ)
        edit_pos = mirline.REF_SEQ_POS + 1

        pass_strand_seed_pos = (
            mirline.STRAND == "-" and edit_pos < seq_len and edit_pos > seq_len - 8
        )
        prim_strand_seed_pos = mirline.STRAND == "+" and edit_pos > 1 and edit_pos < 8

        if pass_strand_seed_pos or prim_strand_seed_pos:
            seed_edit.add(mirline.POS)

    df[EDITED_IN_COL] = "outside seed region"
    for mir_pos in seed_edit:
        df[EDITED_IN_COL] = df.apply(
            in_seed_region(mir_pos),
            axis=1,
        )

    df[X_COL] = df.apply(lambda row: row.REF + " -> " + row.ALT, axis=1)
    return df

def in_seed_region(pos: int) -> str:
    def func(row: pd.Series) -> str:
        return (
            "seed region" if pos > row.START and pos < row.END else row[EDITED_IN_COL]
        )

    return func

def plot_seed_editing_events_count(df: pd.DataFrame, name: str, result_image: str):
    data = (
        pd.crosstab(df[EDITED_IN_COL], df[X_COL])
        .melt(ignore_index=False, value_name=Y_COL)
        .reset_index()
    )

    sns.set_context("poster")
    fig, ax = plt.subplots(figsize=(20, 14))
    fig.suptitle(f"Editing events in seed regions and outside seed regions in\n{name}")

    palette = dict(
        zip(
            ["seed region", "outside seed region"],
            sns.color_palette(n_colors=2),
        )
    )
    sns.barplot(
        data=data.sort_values(Y_COL),
        x=X_COL,
        y=Y_COL,
        hue=EDITED_IN_COL,
        ax=ax,
        palette=palette,
    )
    fig.savefig(result_image)


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

persoana  = 5

actiune   = 2       # 0->STAT ; 1->MERS ; 2->ALERGAT ; 3->CAZATURA
incercare = 1

ID = "%s_%s_%s" % (persoana, actiune, incercare)
denumire = 'D:/LICENTA/OwnDatabase/' + ID +'.csv'

Accel_X = pd.read_csv(denumire, usecols=['Accel_X'])
Accel_Y = pd.read_csv(denumire, usecols=['Accel_Y'])
Gyro_X = pd.read_csv(denumire, usecols=['Gyro_X'])
Gyro_Y = pd.read_csv(denumire, usecols=['Gyro_Y'])

accel_x = Accel_X[200:700].squeeze()
time = np.linspace(0,10,500)
accel_x_fft = np.abs((np.fft.fft(accel_x, 1024)))
freqs = np.fft.rfftfreq(1024) * 50
# plt.figure(),plt.xlabel('Timp [s]'),plt.ylabel('Accelerație [$m/{s^2}$]'), plt.plot(time,accel_x), plt.show()
plt.figure(),plt.xlabel('Frecvență [$Hz$]'),plt.ylabel('|X(k)|') ,plt.plot(freqs, accel_x_fft[:int(1024/2) + 1]), plt.show()
# print(freqs.shape)

# gyro_x = Gyro_X[200:700].squeeze()
# gyro_x_fft = np.abs((np.fft.fft(gyro_x, 1024)))
# freqs = np.fft.rfftfreq(1024) * 50
# plt.figure(), plt.plot(gyro_x), plt.show()
# plt.figure(), plt.plot(freqs, gyro_x_fft[:int(1024/2) + 1]), plt.show()
# print(freqs.shape)


with open("input1", "r") as f:
    lines = f.readlines()

groups = []
group = []

for line in lines:
    line = line.strip()

    if len(line) == 0:
        groups.append(group)
        group = []
    else:
        group.append(int(line))
groups.append(group)

sums = []

mas_grande = 0
for group in groups:
    acc = 0
    for num in group:
        acc = num + acc
    sums.append(acc)

sums.sort()

Acc = 0
for num in sums[-3:]:
    Acc = num + Acc
print (Acc)

mas_grande = 0
for sum in sums:
    if sum > mas_grande:
        mas_grande = sum


"""
@author: Rai
Perspective Transformation
"""

import numpy as np
import matplotlib.pyplot as plt
import cv2

def getPerspectiveMatrix(src, dst):
    """
    Function to compute the perspective transformation matrix.

    Parameters:
    - src: Source points
    - dst: Destination points

    Returns:
    - warpMatrix: The perspective transformation matrix
    """

    assert src.shape[0] == dst.shape[0] and src.shape[0] >= 4

    n = src.shape[0]
    A = np.zeros((2 * n, 8))
    B = np.zeros((2 * n, 1))
    for i in range(n):
        A_item = src[i, :]
        B_item = dst[i, :]
        A[2 * i, :] = [A_item[0], A_item[1], 1, 0, 0, 0,
                       -A_item[0] * B_item[0], -A_item[1] * B_item[0]]
        A[2 * i + 1, :] = [0, 0, 0, A_item[0], A_item[1], 1,
                           -A_item[0] * B_item[1], -A_item[1] * B_item[1]]
        B[2 * i] = B_item[0]
        B[2 * i + 1] = B_item[1]

    A = np.mat(A)
    warpMatrix = A.I * B

    warpMatrix = np.array(warpMatrix).T[0]  # Reshaping from (1,8) to (8)
    warpMatrix = np.insert(warpMatrix, warpMatrix.shape, values=1.0)
    warpMatrix = warpMatrix.reshape(3, 3)

    return warpMatrix

if __name__ == '__main__':
    src = np.float32([[207, 151], [517, 285], [17, 601], [343, 731]])
    dst = np.float32([[0, 0], [337, 0], [0, 488], [337, 488]])

    warpMatrix = getPerspectiveMatrix(src, dst)
    print('Perspective Transform Matrix:\n', warpMatrix)

    img = cv2.imread('PerspectiveTransform_src.jpg')
    h, w, _ = img.shape
    img_dst = cv2.warpPerspective(img, warpMatrix, (337, 488))
    cv2.imshow('Perspective Transformed Image', img_dst)
    cv2.imwrite('PerspectiveTransform_dst.png', img_dst)
    cv2.waitKey(0)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        :ref:https://blog.csdn.net/liuxiao214/article/details/77803348
        """
        if head==None or head.next==None:
            return True
        slow=head
        fast=head
        while fast.next!=None and fast.next.next!=None:
            slow=slow.next
            fast=fast.next.next
        def reverselist(head):
            pre=None
            ne=None
            while head!=None:
                ne=head.next
                head.next=pre
                pre=head
                head=ne
            return pre
        slow.next=reverselist(slow.next)
        slow=slow.next
        while slow!=None:
            if slow.val!=head.val:
                return False
            slow=slow.next
            head=head.next
        return True


import numpy as np
from numpy import *
import matplotlib.pyplot as plt

A = np.array([[4,5],[1,2]])
B = np.array([20,13])
answer = np.linalg.solve(A,B)
print(answer)

'''
***************** Code for plotting the graph **********************
This code first initializes all th evalues for x
Then, an equation in y is given
In the y equation, an array is generated by running a for loop
The for loop assigns the value for x while running through the list of x
Then the values are taken for y and a list is generated for y

*********************************************************************
'''
x1 = np.arange(20)

y1 = [(20-5*i)/4 for i in x1]

x2 = np.arange(20)

y2 = [(13-2*j) for j in x2]

plt.plot(x1,y1,label='First line',color='r')
plt.plot(x2,y2,label='Second line',color='b')

plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.legend()
plt.grid()
plt.show()


from collections import defaultdict

class Solution:
    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:

        email_to_ids = defaultdict(set)
        for i, v in enumerate(accounts):
            for email in v[1:]:
                email_to_ids[email].add(i)

        visited = [False for _ in accounts]
        ret = []
        for i, v in enumerate(accounts):
            if not visited[i]:
                emails = set()
                self.dfs(i, accounts, email_to_ids, emails, visited)
                ret.append([v[0]] + sorted(emails))

        return ret

    def dfs(self, i, accounts, email_to_ids, emails, visited):
        visited[i] = True
        for email in accounts[i][1:]:
            emails.add(email)
            for nbr in email_to_ids[email]:
                if not visited[nbr]:
                    self.dfs(nbr, accounts, email_to_ids, emails, visited)

    def accountsMerge_error(self, accounts: List[List[str]]) -> List[List[str]]:

        email_id = {}
        id_emails = defaultdict(list)
        for i in range(len(accounts)):
            person = None
            for email in accounts[i][1:]:
                if email in email_id:
                    person = email_id[email]
                    break

            for email in accounts[i][1:]:
                if person is None:
                    person = i
                    email_id[email] = person
                    id_emails[person].append(email)
                elif email not in email_id:
                    email_id[email] = person
                    id_emails[person].append(email)

        ret = []
        for k, v in id_emails.items():
            ret.append([accounts[k][0]] + sorted(v))

        return ret


import re
import string

from keras_preprocessing.sequence import pad_sequences
from keras_preprocessing.text import Tokenizer
from nltk.corpus import stopwords

def sanitize_text(media):
    # fill empty values

    media = media.fillna('')

    # remove punctuation

    media['media_summary'] = media['media_summary'].apply(lambda x: re.sub('[^\w\s]', '', x))
    media['media_title'] = media['media_title'].apply(lambda x: re.sub('[^\w\s]', '', x))

    media['media_genre_0'] = media['media_genre_0'].apply(lambda x: re.sub('\s', '', x))
    media['media_genre_1'] = media['media_genre_1'].apply(lambda x: re.sub('\s', '', x))
    media['media_genre_2'] = media['media_genre_2'].apply(lambda x: re.sub('\s', '', x))
    media['media_genre_3'] = media['media_genre_3'].apply(lambda x: re.sub('\s', '', x))

    # remove stop words

    stops = stopwords.words('german')

    media['media_summary'] = media['media_summary'].apply(
        lambda x: ' '.join([word for word in x.lower().translate(x.maketrans('', '', string.punctuation)).split() if
                            word not in stops])
    )

    media['media_title'] = media['media_title'].apply(
        lambda x: ' '.join([word for word in x.lower().translate(x.maketrans('', '', string.punctuation)).split() if
                            word not in stops])
    )

    return media

def process_media(media):
    # remove unneeded columns
    # not sure how to process mediaReleaseDate for now - maybe use unix seconds since 1970

    media = media.drop(columns=['media_id', 'media_release_date'])

    # remove stopwords

    media = sanitize_text(media)

    # process vote_type

    if 'vote_type' in media:
        vote_type_dict = {
            'positive': 1,
            'neutral': 0,
            'negative': -1
        }

        media['vote_type'] = media['vote_type'].apply(lambda x: vote_type_dict.get(x))

    # process media_type

    media_type_dict = {
        'movie': 1,
        'tv': 2,
    }

    media['media_type'] = media['media_type'].apply(lambda x: media_type_dict.get(x))

    # fit tokenizer for genres

    max_genres = 4

    genre_tok = Tokenizer(oov_token='<UnknownGenre>')

    for i in range(4):
        genre_tok.fit_on_texts(media[f'media_genre_{i}'])

    # map genres to tokens

    genre_cols = []

    for i in range(max_genres):
        genre_cols.append(f'media_genre_{i}')

    media[genre_cols] = media[genre_cols].apply(
        lambda x: x.apply(
            lambda y: (lambda z: z[0][0] if z[0] else float(0))(genre_tok.texts_to_sequences([y]))
        )
    )

    # fit tokenizer on summaries and titles

    prosa_tokenizer = Tokenizer(oov_token='<OOV>')

    prosa_tokenizer.fit_on_texts(media['media_summary'])
    prosa_tokenizer.fit_on_texts(media['media_title'])

    # map prosa to tokens

    summary_word_count = 60

    summary_seqs = pad_sequences(prosa_tokenizer.texts_to_sequences(media['media_summary']), maxlen=summary_word_count,
                                 padding='post')

    for i in range(summary_word_count):
        media[f'media_summary_{i}'] = summary_seqs[:, i]

    title_word_count = 5

    title_seqs = pad_sequences(prosa_tokenizer.texts_to_sequences(media['media_title']), maxlen=title_word_count,
                               padding='post')

    for i in range(title_word_count):
        media[f'media_title_{i}'] = title_seqs[:, i]

    return media.drop(columns=['media_summary', 'media_title'])


import os
import json
import glob

# Windows specific Imports
from platform import system
if system() == 'Windows':
    import pathlib
    temp = pathlib.PosixPath
    pathlib.PosixPath = pathlib.WindowsPath

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD = os.path.join(BASE_DIR, 'upload')
MODELS = os.path.join(BASE_DIR, 'static', 'models')

NO_MASK = 0
INCORRECT = 1
MASK = 2

def box_resp(mylist):
    json_resp = []
    for i in range(len(mylist)):
        (x0,y0,x1,y1) = mylist[i][0]
        prediction = mylist[i][1]
        json_resp.append({
                'top': str(y0),
                'bottom': str(y1),
                'left': str(x0),
                'right': str(x1),
                'result': prediction,
        })
    return json.dumps(json_resp)

def delete_uploads():
    """Deletes all files in UPLOAD folder """
    files = glob.glob(os.path.join(UPLOAD, '*.png'), recursive=True)
    for f in files:
        try:
            os.remove(f)
        except OSError as e:
            print("Error: %s : %s" % (f, e.strerror))
    return "All Good!"


# %%
import json
import re
import requests
from bs4 import BeautifulSoup
# %%
class wikipediaProvinceScraper():
    def __init__(self, link: str) -> None:
        self.rsp = requests.get(link)
        if self.rsp.status_code == 200:
            self.soup = BeautifulSoup(self.rsp.text, "html.parser")
        else:
            raise ValueError("Error !")
    def proces(self):
        self.mainLink = "https://fa.wikipedia.org/"
        self.pagesLink = []
        self.tags = self.soup.findAll("div", {"class": "CategoryTreeItem"})
        for i in self.tags:
            self.pagesLink.append(i.findNext("a")["href"])

        self.provinces = []
        for i in self.pagesLink:
            self.tempRsp = requests.get(self.mainLink + i)
            if self.tempRsp.status_code == 200:
                self.tempSoup = BeautifulSoup(self.tempRsp.text, "html.parser")
                self.tempTags = self.tempSoup.find("div", {"class": "mw-category-generated"}).findAll("div", {"class": "mw-category-group"})
                for category in self.tempTags:
                    self.liTags = category.findAll("li")
                    for li in self.liTags:
                        self.provinces.append(li.find("a")["title"])
            else:
                raise ValueError("Error !")

        return self.provinces
# %%
m = wikipediaProvinceScraper("https://fa.wikipedia.org/wiki/%D8%B1%D8%AF%D9%87:%D9%85%D8%AD%D9%84%D9%87%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%AA%D9%87%D8%B1%D8%A7%D9%86_%D8%A8%D8%B1_%D9%BE%D8%A7%DB%8C%D9%87_%D9%85%D9%86%D8%B7%D9%82%D9%87")
mahaleh = (m.proces())
with open("./mahaleh.txt", "w", encoding="utf-8") as f:
    for i in mahaleh:
        f.writelines(i)
        f.writelines("\n")
    f.close()
# %%
with open("./data.json", "r", encoding="utf-8") as f:
    data = json.load(f)
# %%
class province():
    def __init__(self) -> None:
        with open("./stopWords.txt", "r", encoding="utf-8") as f:
            self.stopWords = f.read().splitlines()
            f.close()
        with open("./mahaleh.txt", "r", encoding="utf-8") as f:
            self.mahaleh = f.read().splitlines()
            f.close()
        with open("./reqCount.txt", "r+", encoding="utf-8") as f:
            self.reqCount = int(f.read())
            f.close()
        if self.reqCount >= 5000:
            raise ValueError(f"number of requests to api.neshan.org is more than 5000 !")

    def __del__(self):
        with open("./reqCount.txt", "w", encoding="utf-8") as f:
            f.write(str(self.reqCount))
            f.close()

    def getLngLat(self, url: str):
        rsp = requests.get(url)
        if rsp.status_code == 200:
            try:
                soup = BeautifulSoup(rsp.text, "html.parser")
                lat, long = soup.find("div", {"class": "map-container"}).find("a")["href"].split("/")[-1].split(",")
                return lat.strip(), long.strip()
            except:
                raise ValueError(f"Error in '{url}' for give lat, long !")
        else:
            raise ValueError(f"request to '{url}' || status code: {rsp.status_code}")

    def proces(self, address: str, name: str, link: str):
        apiCode = ""
        if len(address.strip()) == 0 or len(name.strip()) == 0 or len(link.strip()) == 0:
            raise ValueError(f"address: '{address}' is empty OR name: '{name}' is empty OR link: '{link}' is empty")
        else:
            if re.findall(r"\(\w+\)", name):
                return re.findall(r"\(\w+\)", name)[0].strip("(").strip(")")

            for word in self.stopWords:
                rePattern = re.compile(fr"{word.strip()}")
                address = rePattern.sub(" ", address)

            if "،" in address:
                address = address.split("،")
                if len(address[0].strip().split()) > 2:
                    if " ".join(address[0].split()[0:2]) not in self.mahaleh:
                        try:
                            lat, lng = self.getLngLat(link)
                            rsp = requests.get(f"https://api.neshan.org/v5/reverse?lat={lat}&lng={lng}", headers={"Api-Key": f"{apiCode}"})
                            self.reqCount += 1
                            if rsp.status_code == 200:
                                try:
                                    return rsp.json()["neighbourhood"]
                                except:
                                    return -1
                            else:
                                return f"status code: {rsp.status_code} from .neshan.org"

                        except Exception as e:
                            return e

                    else:
                        return " ".join(address[0].split()[0:2])
                else:
                    if len(address[0].strip().split()) == 2:
                        if address[0].strip().split()[0] in self.mahaleh:
                            return address[0].strip().split()[0]
                        elif address[0].strip().split()[1] in self.mahaleh:
                            return address[0].strip().split()[1]
                        else:
                            try:
                                lat, lng = self.getLngLat(link)
                                rsp = requests.get(f"https://api.neshan.org/v5/reverse?lat={lat}&lng={lng}", headers={"Api-Key": f"{apiCode}"})
                                self.reqCount += 1
                                if rsp.status_code == 200:
                                    try:
                                        return rsp.json()["neighbourhood"]
                                    except:
                                        return -1
                                else:
                                    return f"status code: {rsp.status_code} from api.neshan.org"

                            except Exception as e:
                                return e
                    else:
                        if address[0].strip() in self.mahaleh:
                            return address[0].strip()
                        else:
                            try:
                                lat, lng = self.getLngLat(link)
                                rsp = requests.get(f"https://api.neshan.org/v5/reverse?lat={lat}&lng={lng}", headers={"Api-Key": f"{apiCode}"})
                                self.reqCount += 1
                                if rsp.status_code == 200:
                                    try:
                                        return rsp.json()["neighbourhood"]
                                    except:
                                        return -1
                                else:
                                    return f"status code: {rsp.status_code} from api.neshan.org"

                            except Exception as e:
                                return e
            else:
                return " ".join(address.split()[0:2])
# %%
p = province()
prov = []
for city in data:
    for coffee in data[city]:
        ans =  p.proces(data[city][coffee]["address"], coffee, data[city][coffee]["link"])
        prov.append(ans)
        data[city][coffee]["province"] = ans

del p # important!
# %%
def exportTojson(data):
    try:
        with open("./data.json", "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except:
        raise ValueError("Can Not Save !")
# %%
exportTojson(data)


class CreateSuccessPacket:
    def __init__(self):
        self.type = "CREATESUCCESS"
        self.send = True
        self.objectId = 0
        self.charId = 0
        self.unknownStr = ""

    def read(self, reader):
        self.objectId = reader.readInt32()
        self.charId = reader.readInt32()
        self.unknownStr = reader.readStr()

    def write(self, writer):
        writer.writeInt32(self.objectId)
        writer.writeInt32(self.charId)
        writer.writeStr(self.unknownStr)


from django.shortcuts import render
from django.http import HttpResponse
import requests
import os
import json
from bs4 import BeautifulSoup
from .models import Greeting
from .skr import getdatas,maximizeRate,makeoutputDic,manycontest,getdatasa

# Create your views here.
def index(request):
    return vote(request)

def result(request,username):
    r = ""
    name = username
    sex = "male"
    return last(request,name,sex,r)

def resultr(request,username):
    r = "r"
    name = username
    sex = "female"
    return last(request,name,sex,r)

def vote(request):
    name = "hdnkt"
    sex = "male"
    try:
        name = request.POST["username"]
        sex = request.POST["sex"]
    except:
        name = "hdnkt"
        sex = "male"
    return last(request,name,sex,"")

def last(request,name,sex,r):
    error = " "

    try:
        if sex =="female":
            r = "r"
            dic=manycontest()
            tmp,ratedHis = getdatas(name,dic)
            real = tmp[len(tmp)-1]["NewRating"]
            ans,ind=maximizeRate(tmp,ratedHis)
            final = makeoutputDic(ans,ind,tmp)
        else:
            tmp,ratedHis = getdatasa(name)
            real = tmp[len(tmp)-1]["NewRating"]
            ans,ind=maximizeRate(tmp,ratedHis)
            final = makeoutputDic(ans,ind,tmp)
    except:
        name="hdnkt"
        tmp,ratedHis = getdatasa(name)
        real = tmp[len(tmp)-1]["NewRating"]
        ans,ind=maximizeRate(tmp,ratedHis)
        final = makeoutputDic(ans,ind,tmp)
        error = "入力された名前のユーザーは存在しません。"

    highest = final[len(final)-1]["NewRating"]
    dist = "+"+str(highest-real) if highest-real >= 0 else str(highest-real)

    return render(request,"ratinggraph.html",{"final":final,"name":name,"error":error,"r":r,"highest":highest,"real":real,"dist":dist})

def db(request):
    greeting = Greeting()
    greeting.save()
    greetings = Greeting.objects.all()
    return render(request, "db.html", {"greetings": greetings})


'''
Source codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)
Chapter 14 Making Decision in Complex Environments with Reinforcement Learning
Author: Yuxi (Hayden) Liu (yuxi.liu.ece@gmail.com)
'''

import torch
import gym

env = gym.make('Blackjack-v0')

env.reset()

env.step(1)

env.step(1)

env.step(0)

def run_episode(env, hold_score):
    state = env.reset()
    rewards = []
    states = [state]
    while True:
        action = 1 if state[0] < hold_score else 0
        state, reward, is_done, info = env.step(action)
        states.append(state)
        rewards.append(reward)
        if is_done:
            break
    return states, rewards

from collections import defaultdict

def mc_prediction_first_visit(env, hold_score, gamma, n_episode):
    V = defaultdict(float)
    N = defaultdict(int)
    for episode in range(n_episode):
        states_t, rewards_t = run_episode(env, hold_score)
        return_t = 0
        G = {}
        for state_t, reward_t in zip(states_t[1::-1], rewards_t[::-1]):
            return_t = gamma * return_t + reward_t
            G[state_t] = return_t
        for state, return_t in G.items():
            if state[0] <= 21:
                V[state] += return_t
                N[state] += 1
    for state in V:
        V[state] = V[state] / N[state]
    return V

gamma = 1
hold_score = 18
n_episode = 500000

value = mc_prediction_first_visit(env, hold_score, gamma, n_episode)

print(value)

print('Number of states:', len(value))


# https://atcoder.jp/contests/abc007/tasks/abc007_3

from collections import deque

class Point:
    def __init__(self, x, y, d):
        super().__init__()
        self.x = x
        self.y = y
        self.d = d

    def __repr__(self):
        return 'x {} y {} d {}'.format(self.x, self.y, self.d)

if __name__ == "__main__":
    R, C = map(int, input().split())
    sy, sx = map(int, input().split())
    gy, gx = map(int, input().split())
    sy -= 1
    sx -= 1
    gx -= 1
    gy -= 1
    A = []
    for _ in range(R):
        row = [c for c in input()]
        A.append(row)

    queue = deque()
    queue.appendleft(Point(sx, sy, 0))

    result = -1
    while queue:
        point = queue.pop()
        if point.x == gx and point.y == gy:
            result = point.d
            break

        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            x = point.x + dx
            y = point.y + dy
            if A[y][x] == '.':
                A[y][x] = '#'
                queue.appendleft(Point(x, y, point.d+1))

    print(result)


"""
Util functions for MLBootcamp
"""
import os
import re
import time
import glob
import shutil
import zipfile
import urllib.request
import pandas as pd

non_decimal = re.compile(r'[^\d.]+') # regex for removing non-decimal characters from string
def parse_beds(string):
    strings = string.lower().split(', ')
    num_beds = None
    for s in strings:
        if "bd" in s:
            try:
                num_beds = float(non_decimal.sub('', s))
            except Exception as e:
                pass
        # treat studio as 0 bedrooms
        elif "studio" in s.lower():
            num_beds = 0
        return num_beds

def parse_bath(string):
    strings = string.lower().split(', ')
    num_bath = None
    for s in strings:
        if "ba" in s:
            try:
                num_bath = float(non_decimal.sub('', s))
            except Exception as e:
                pass
            finally:
                return num_bath
def parse_sqft(string):
    strings = string.lower().split(', ')
    sqft = None
    for s in strings:
        if "ft" in s:
            try:
                sqft = float(non_decimal.sub('', s))
            except Exception as e:
                pass
            finally:
                return sqft

def parse_property_type(string):
    # property types mapping
    property_types = {'Condo For Sale': 'condo',
                      'House For Sale': 'house',
                      'Apartment For Sale': 'apartment',
                      'New Construction': 'new',
                      'Foreclosure': 'foreclosure',
                       'Lot/Land For Sale': 'lot',
                      'Coming Soon': 'coming',
                      'Co-op For Sale': 'coop',
                      'Auction': 'auction',
                      'For Sale by Owner': None,
                      'Townhouse For Sale': 'townhouse'}
    try:
        property_type = property_types[string]
    except KeyError as e:
        print(e)
        property_type = None
    finally:
        return property_type

def download_extract_data(data_dir: str):
    """
    Download zipfile and extract its contents to data_dir
    Args:
        data_dir: extract data here
    """
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    data_save_path = os.path.join(data_dir, 'data.zip')
    data_download_url = 'https://github.com/kylehounslow/datasets/raw/master/mlbootcamp/sf_housing.zip'
    print('downloading data...')
    urllib.request.urlretrieve(data_download_url, data_save_path)
    print('extracting data to {data_dir}...'.format(data_dir=data_dir))
    data_zip = zipfile.ZipFile(data_save_path)
    data_zip.extractall(data_dir)
    data_zip.close()
    print('Done.')

def load_data_to_dataframe(data_dir: str) -> pd.DataFrame:
    """
    Load all .csv files from data_dir and concatenate them into a single DataFrame.
    Args:
        data_dir: path to data directory
    Returns:
        pd.DataFrame: all data from files in data_dir
    Notes:
        All duplicate rows will be discarded
    """
    all_csvs = []
    # load the csv files from all scraping runs
    csv_filenames = os.path.join(data_dir, '**/*.csv')
    print('loading data {csv_filenames}'.format(csv_filenames=csv_filenames))
    for filename in glob.glob(csv_filenames):
        all_csvs.append(pd.read_csv(filename))
    # combine all dataframes together and drop any duplicate entries
    df = pd.concat(all_csvs, ignore_index=True).drop_duplicates()
    print("Found a total of {count} data points".format(count=len(df)))
    # save this combined dataframe as csv for safe keeping
    df.to_csv(os.path.join(data_dir, 'all_data.csv'), index=False)
    return df

def format_price(price: str):
    """
    Remove all non-numerical values from price column
    Args:
        price: string representation of price
    Returns:
        price_num: floating point representation of price
    """
    price = str(price)
    multiply_factor = 1
    if 'M' in price:
        multiply_factor = 1e6
    elif 'K' in price:
        multiply_factor = 1e3
    non_decimal = re.compile(r'[^0-9\.]')
    price_num = None
    try:
        price_num = float(non_decimal.sub('', price))*multiply_factor
    except Exception as e:
#         print(f'error converting \"{price}\": {e}')
        pass
    finally:
        return price_num
def load_sf_housing_dataset():
    """
    Download, extract, and format the housing dataset.
    Returns:
        pd.DataFrame: formatted dataset
    """
    data_dir = './tmp'
    download_extract_data(data_dir=data_dir)
    df = load_data_to_dataframe(data_dir=data_dir)
    df['price'] = df.price.apply(format_price)
    df['bed'] = df['facts and features'].apply(parse_beds)
    df['bath'] = df['facts and features'].apply(parse_bath)
    df['sqft'] = df['facts and features'].apply(parse_sqft)
    df['property_type'] = df['title'].apply(parse_property_type)
    if os.path.exists(data_dir):
        shutil.rmtree(data_dir)
    return df


from django.shortcuts import render_to_response
from models import City

def home(request):
    # create a location for no particular reason
    if City.objects.count() == 0:
        City.find("Cambridge", "MA")
    return render_to_response('home.html')

def whois(request):
    name = request.GET.get("name", "") or "World"
    if City.objects.count() > 0:
        city = City.objects.all()[0]
        address = str(city)
    else:
        address = "someplace interesting"
    return render_to_response('whois.html',
                              {"name": name,
                               "address": address,
                               "citylist": City.objects.all()})


import os
import pyspark.sql.functions as F
import pyspark.sql.types as T
from utilities import SEED
# import any other dependencies you want, but make sure only to use the ones
# availiable on AWS EMR

# ---------------- choose input format, dataframe or rdd ----------------------
INPUT_FORMAT = 'dataframe'  # change to 'rdd' if you wish to use rdd inputs
# -----------------------------------------------------------------------------
if INPUT_FORMAT == 'dataframe':
    import pyspark.ml as M
    import pyspark.sql.functions as F
    import pyspark.sql.types as T
    from pyspark.ml.regression import DecisionTreeRegressor
    from pyspark.ml.evaluation import RegressionEvaluator
if INPUT_FORMAT == 'koalas':
    import databricks.koalas as ks
elif INPUT_FORMAT == 'rdd':
    import pyspark.mllib as M
    from pyspark.mllib.feature import Word2Vec
    from pyspark.mllib.linalg import Vectors
    from pyspark.mllib.linalg.distributed import RowMatrix
    from pyspark.mllib.tree import DecisionTree
    from pyspark.mllib.regression import LabeledPoint
    from pyspark.mllib.linalg import DenseVector
    from pyspark.mllib.evaluation import RegressionMetrics

# ---------- Begin definition of helper functions, if you need any ------------

# def task_1_helper():
#   pass

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

def task_1(data_io, review_data, product_data):
    # -----------------------------Column names--------------------------------
    # Inputs:
    asin_column = 'asin'
    overall_column = 'overall'
    # Outputs:
    mean_rating_column = 'meanRating'
    count_rating_column = 'countRating'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df1a = review_data\
                    .select(review_data[asin_column].alias('blah_asin'),
                            overall_column
                           )\
                    .groupby('blah_asin')\
                    .agg(F.avg(overall_column).alias(mean_rating_column),
                         F.count(overall_column).alias(count_rating_column)
                        )
    temp_df = product_data\
                    .join(temp_df1a,
                          product_data[asin_column] == temp_df1a['blah_asin'],
                          how = 'left'
                         )\
                    .drop('blah_asin')

    mR1 = temp_df\
            .agg(F.count(asin_column).alias('count_total'),
                 F.avg(mean_rating_column).alias('mean_meanRating'),
                 F.variance(mean_rating_column).alias('variance_meanRating'),
                 F.avg(count_rating_column).alias('mean_countRating'),
                 F.variance(count_rating_column).alias('variance_countRating'),
                 F.count(F.when(F.col(mean_rating_column).isNull(),1)).alias('numNulls_meanRating'),
                 F.count(F.when(F.col(count_rating_column).isNull(),1)).alias('numNulls_countRating')
                ).cache()

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

    # ---------------------- Put results in res dict --------------------------
    # Calculate the values programmaticly. Do not change the keys and do not
    # hard-code values in the dict. Your submission will be evaluated with
    # different inputs.
    # Modify the values of the following dictionary accordingly.
    res = {
        'count_total': None,
        'mean_meanRating': None,
        'variance_meanRating': None,
        'numNulls_meanRating': None,
        'mean_countRating': None,
        'variance_countRating': None,
        'numNulls_countRating': None
    }
    # Modify res:

    res['count_total'] = mR1.select('count_total').head()[0]
    res['mean_meanRating'] = mR1.select('mean_meanRating').head()[0]
    res['variance_meanRating'] = mR1.select('variance_meanRating').head()[0]
    res['numNulls_meanRating'] = mR1.select('numNulls_meanRating').head()[0]
    res['mean_countRating'] = mR1.select('mean_countRating').head()[0]
    res['variance_countRating'] = mR1.select('variance_countRating').head()[0]
    res['numNulls_countRating'] = mR1.select('numNulls_countRating').head()[0]

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_1')
    return res
    # -------------------------------------------------------------------------

def task_2(data_io, product_data):
    # -----------------------------Column names--------------------------------
    # Inputs:
    salesRank_column = 'salesRank'
    categories_column = 'categories'
    asin_column = 'asin'
    # Outputs:
    category_column = 'category'
    bestSalesCategory_column = 'bestSalesCategory'
    bestSalesRank_column = 'bestSalesRank'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df2 = product_data.withColumns({category_column:\
                                             F.when(F.col(categories_column)[0][0] == '', None)\
                                             .otherwise(F.col(categories_column)[0][0]),
                                         bestSalesCategory_column:F.map_keys(F.col(salesRank_column)).getItem(0),
                                         bestSalesRank_column:F.map_values(F.col(salesRank_column)).getItem(0)
                                        }
                                       )
    mR2 = temp_df2\
            .agg(F.count(asin_column).alias('count_total'),
                 F.avg(bestSalesRank_column).alias('mean_bestSalesRank'),
                 F.variance(bestSalesRank_column).alias('variance_bestSalesRank'),
                 F.count(F.when(F.col(category_column).isNull(),1)).alias('numNulls_category'),
                 F.count(F.when(F.col(bestSalesCategory_column).isNull(),1)).alias('numNulls_bestSalesCategory'),
                 F.count_distinct(F.when(F.col(category_column).isNotNull()
                                         & (F.col(category_column) != ''),
                                         F.col(category_column)
                                        )).alias('countDistinct_category'),
                 F.count_distinct(F.when(F.col(bestSalesCategory_column).isNotNull()
                                         & (F.col(bestSalesCategory_column) != ''),
                                         F.col(bestSalesCategory_column)
                                        )).alias('countDistinct_bestSalesCategory'),
                ).cache()

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'count_total': None,
        'mean_bestSalesRank': None,
        'variance_bestSalesRank': None,
        'numNulls_category': None,
        'countDistinct_category': None,
        'numNulls_bestSalesCategory': None,
        'countDistinct_bestSalesCategory': None
    }
    # Modify res:

    res['count_total'] = mR2.select('count_total').head()[0]
    res['mean_bestSalesRank'] = mR2.select('mean_bestSalesRank').head()[0]
    res['variance_bestSalesRank'] = mR2.select('variance_bestSalesRank').head()[0]
    res['numNulls_category'] = mR2.select('numNulls_category').head()[0]
    res['countDistinct_category'] = mR2.select('countDistinct_category').head()[0]
    res['numNulls_bestSalesCategory'] = mR2.select('numNulls_bestSalesCategory').head()[0]
    res['countDistinct_bestSalesCategory'] = mR2.select('countDistinct_bestSalesCategory').head()[0]

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_2')
    return res
    # -------------------------------------------------------------------------

def task_3(data_io, product_data):
    # -----------------------------Column names--------------------------------
    # Inputs:
    asin_column = 'asin'
    price_column = 'price'
    attribute = 'also_viewed'
    related_column = 'related'
    # Outputs:
    meanPriceAlsoViewed_column = 'meanPriceAlsoViewed'
    countAlsoViewed_column = 'countAlsoViewed'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df3 = product_data\
                    .select(asin_column,
                            F.explode(
                            F.map_values(
                                F.map_filter(related_column, lambda k,v: k==attribute)))\
                            .alias('temp'))\
                    .withColumn(attribute,
                                F.explode(F.col('temp')))\
                    .select(asin_column,attribute)

    temp_df3a = product_data.select(F.col(asin_column).alias('also_asin'),price_column)

    temp_df3 = temp_df3\
                    .join(temp_df3a,
                          temp_df3[attribute] == temp_df3a['also_asin'],
                          how = 'left')\
                    .select(temp_df3[asin_column].alias('blah_asin'),
                            attribute,
                            price_column
                           )\
                    .groupby('blah_asin')\
                    .agg(F.avg(price_column).alias(meanPriceAlsoViewed_column),
                         F.count('blah_asin').alias(countAlsoViewed_column)
                        )

    temp_df3 = product_data\
                .join(temp_df3,
                      product_data[asin_column] == temp_df3['blah_asin'],
                      how = 'left')\
                .drop('blah_asin')

    mR3 = temp_df3\
            .agg(F.count(asin_column).alias('count_total'),
                 F.avg(meanPriceAlsoViewed_column).alias('mean_meanPriceAlsoViewed'),
                 F.variance(meanPriceAlsoViewed_column).alias('variance_meanPriceAlsoViewed'),
                 F.avg(countAlsoViewed_column).alias('mean_countAlsoViewed'),
                 F.variance(countAlsoViewed_column).alias('variance_countAlsoViewed'),
                 F.count(F.when(F.col(meanPriceAlsoViewed_column).isNull(),1)).alias('numNulls_meanPriceAlsoViewed'),
                 F.count(F.when(F.col(countAlsoViewed_column).isNull(),1)).alias('numNulls_countAlsoViewed')
                ).cache()

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'count_total': None,
        'mean_meanPriceAlsoViewed': None,
        'variance_meanPriceAlsoViewed': None,
        'numNulls_meanPriceAlsoViewed': None,
        'mean_countAlsoViewed': None,
        'variance_countAlsoViewed': None,
        'numNulls_countAlsoViewed': None
    }
    # Modify res:

    res['count_total'] = mR3.select('count_total').head()[0]
    res['mean_meanPriceAlsoViewed'] = mR3.select('mean_meanPriceAlsoViewed').head()[0]
    res['variance_meanPriceAlsoViewed'] = mR3.select('variance_meanPriceAlsoViewed').head()[0]
    res['numNulls_meanPriceAlsoViewed'] = mR3.select('numNulls_meanPriceAlsoViewed').head()[0]
    res['mean_countAlsoViewed'] = mR3.select('mean_countAlsoViewed').head()[0]
    res['variance_countAlsoViewed'] = mR3.select('variance_countAlsoViewed').head()[0]
    res['numNulls_countAlsoViewed'] = mR3.select('numNulls_countAlsoViewed').head()[0]

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_3')
    return res
    # -------------------------------------------------------------------------

def task_4(data_io, product_data):
    # -----------------------------Column names--------------------------------
    # Inputs:
    price_column = 'price'
    title_column = 'title'
    # Outputs:
    meanImputedPrice_column = 'meanImputedPrice'
    medianImputedPrice_column = 'medianImputedPrice'
    unknownImputedTitle_column = 'unknownImputedTitle'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df4 = product_data.withColumn(price_column, F.col(price_column).cast('float'))

    im1 = M.feature.Imputer(inputCol = price_column,
                            outputCol = meanImputedPrice_column,
                            strategy = 'mean'
                           )
    im2 = M.feature.Imputer(inputCol = price_column,
                            outputCol = medianImputedPrice_column,
                            strategy = 'median'
                           )

    temp_df4 = im1.fit(temp_df4).transform(temp_df4)
    temp_df4 = im2.fit(temp_df4).transform(temp_df4)

    temp_df4 = temp_df4.withColumn(unknownImputedTitle_column,
                                   F.when(F.col(title_column) == '',None)\
                                       .otherwise(F.col(title_column))
                                  )\
                    .fillna('unknown',unknownImputedTitle_column)

    mR4 = temp_df4\
            .agg(F.avg(meanImputedPrice_column).alias('mean_meanImputedPrice'),
                 F.variance(meanImputedPrice_column).alias('variance_meanImputedPrice'),
                 F.avg(medianImputedPrice_column).alias('mean_medianImputedPrice'),
                 F.variance(medianImputedPrice_column).alias('variance_medianImputedPrice'),
                 F.count(F.when(F.col(meanImputedPrice_column).isNull(),1)).alias('numNulls_meanImputedPrice'),
                 F.count(F.when(F.col(medianImputedPrice_column).isNull(),1)).alias('numNulls_medianImputedPrice'),
                 F.count(F.when(F.col(unknownImputedTitle_column)=='unknown',1)).alias('numUnknowns_unknownImputedTitle')
                ).cache()

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'count_total': None,
        'mean_meanImputedPrice': None,
        'variance_meanImputedPrice': None,
        'numNulls_meanImputedPrice': None,
        'mean_medianImputedPrice': None,
        'variance_medianImputedPrice': None,
        'numNulls_medianImputedPrice': None,
        'numUnknowns_unknownImputedTitle': None
    }
    # Modify res:

    res['count_total'] = temp_df4.count()
    res['mean_meanImputedPrice'] = mR4.select('mean_meanImputedPrice').head()[0]
    res['variance_meanImputedPrice'] = mR4.select('variance_meanImputedPrice').head()[0]
    res['numNulls_meanImputedPrice'] = mR4.select('numNulls_meanImputedPrice').head()[0]
    res['mean_medianImputedPrice'] = mR4.select('mean_medianImputedPrice').head()[0]
    res['variance_medianImputedPrice'] = mR4.select('variance_medianImputedPrice').head()[0]
    res['numNulls_medianImputedPrice'] = mR4.select('numNulls_medianImputedPrice').head()[0]
    res['numUnknowns_unknownImputedTitle'] = mR4.select('numUnknowns_unknownImputedTitle').head()[0]

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_4')
    return res
    # -------------------------------------------------------------------------

def task_5(data_io, product_processed_data, word_0, word_1, word_2):
    # -----------------------------Column names--------------------------------
    # Inputs:
    title_column = 'title'
    # Outputs:
    titleArray_column = 'titleArray'
    titleVector_column = 'titleVector'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df5 = product_processed_data.withColumn(titleArray_column,
                                                 F.split(F.lower(F.col(title_column)), ' ')
                                                )

    w2V = M.feature.Word2Vec(vectorSize = 16,
                             minCount = 100,
                             seed = SEED,
                             numPartitions = 4,
                             inputCol = titleArray_column
                            )
    model = w2V.fit(temp_df5)

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'count_total': None,
        'size_vocabulary': None,
        'word_0_synonyms': [(None, None), ],
        'word_1_synonyms': [(None, None), ],
        'word_2_synonyms': [(None, None), ]
    }
    # Modify res:

    res['count_total'] = temp_df5.count()
    res['size_vocabulary'] = model.getVectors().count()
    for name, word in zip(
        ['word_0_synonyms', 'word_1_synonyms', 'word_2_synonyms'],
        [word_0, word_1, word_2]
    ):
        res[name] = model.findSynonymsArray(word, 10)

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_5')
    return res
    # -------------------------------------------------------------------------

def task_6(data_io, product_processed_data):
    # -----------------------------Column names--------------------------------
    # Inputs:
    category_column = 'category'
    # Outputs:
    categoryIndex_column = 'categoryIndex'
    categoryOneHot_column = 'categoryOneHot'
    categoryPCA_column = 'categoryPCA'
    # -------------------------------------------------------------------------

    # ---------------------- Your implementation begins------------------------

    temp_df6 = product_processed_data

    temp_df6 = M.feature.StringIndexer(inputCol = category_column,
                                       outputCol = categoryIndex_column
                                      )\
                                    .fit(temp_df6)\
                                    .transform(temp_df6)

    temp_df6 = M.feature.OneHotEncoder(inputCol = categoryIndex_column,
                                       outputCol = categoryOneHot_column,
                                       dropLast = False
                                      )\
                                    .fit(temp_df6)\
                                    .transform(temp_df6)

    temp_df6 = M.feature.PCA(inputCol = categoryOneHot_column,
                             outputCol = categoryPCA_column,
                             k = 15
                            )\
                            .fit(temp_df6)\
                            .transform(temp_df6)

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'count_total': None,
        'meanVector_categoryOneHot': [None, ],
        'meanVector_categoryPCA': [None, ]
    }
    # Modify res:

    res['count_total'] = temp_df6.count()
    res['meanVector_categoryOneHot'] = temp_df6.select(M.stat.Summarizer.mean(F.col(categoryOneHot_column))).head()[0]
    res['meanVector_categoryPCA'] = temp_df6.select(M.stat.Summarizer.mean(F.col(categoryPCA_column))).head()[0]

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_6')
    return res
    # -------------------------------------------------------------------------

def task_7(data_io, train_data, test_data):

    # ---------------------- Your implementation begins------------------------

    reg = M.regression.DecisionTreeRegressor(featuresCol = 'features',
                                             labelCol = 'overall',
                                             predictionCol = 'prediction',
                                             maxDepth = 5,
                                            )\
                                            .fit(train_data)
    pred = reg.transform(test_data)
    rmse = M.evaluation.RegressionEvaluator(predictionCol = 'prediction',
                                            labelCol = 'overall',
                                            metricName = 'rmse'
                                           )\
                                            .evaluate(pred)

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'test_rmse': None
    }
    # Modify res:

    res['test_rmse'] = rmse

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_7')
    return res
    # -------------------------------------------------------------------------

def task_8(data_io, train_data, test_data):

    # ---------------------- Your implementation begins------------------------

    train_data, valid_data = train_data.randomSplit([0.75,0.25])

    best_rmse = 1e6
    evaluator = M.evaluation.RegressionEvaluator(predictionCol = 'prediction',
                                                 labelCol = 'overall',
                                                 metricName = 'rmse'
                                                )

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

    # ---------------------- Put results in res dict --------------------------
    res = {
        'test_rmse': None,
        'valid_rmse_depth_5': None,
        'valid_rmse_depth_7': None,
        'valid_rmse_depth_9': None,
        'valid_rmse_depth_12': None,
    }
    # Modify res:

    for k in [5,7,9,12]:
        reg = M.regression.DecisionTreeRegressor(featuresCol = 'features',
                                             labelCol = 'overall',
                                             predictionCol = 'prediction',
                                             maxDepth = k,
                                            )\
                                            .fit(train_data)
        pred = reg.transform(valid_data)
        rmse = evaluator.evaluate(pred)

        res['valid_rmse_depth_{}'.format(k)] = rmse

        if rmse < best_rmse:
            best_depth = k
            best_reg = reg

    test_pred = best_reg.transform(test_data)
    res['test_rmse'] = evaluator.evaluate(test_pred)

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

    # ----------------------------- Do not change -----------------------------
    data_io.save(res, 'task_8')
    return res
    # -------------------------------------------------------------------------


#Break and Continue Loops
#Break - Stops the loop all together
#Continue - tells python to stop the current iteration and to start the next one

#Example
items = [1, 2, 3, 4, 5]
for item in items:
    if item == 2:
        continue
    print('Prints after continue')