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

from datetime import date
from dateutil.parser import parse
from imio.smartweb.core.config import EVENTS_URL
from imio.smartweb.core.contents.sections.views import CarouselOrTableSectionView
from imio.smartweb.core.contents.sections.views import HashableJsonSectionView
from imio.smartweb.core.utils import batch_results
from imio.smartweb.core.utils import get_json
from imio.smartweb.core.utils import hash_md5
from plone import api
from Products.CMFPlone.utils import normalizeString

class EventsView(CarouselOrTableSectionView, HashableJsonSectionView):
    """Events Section view"""

    @property
    def items(self):
        today = date.today().isoformat()
        max_items = self.context.nb_results_by_batch * self.context.max_nb_batches
        selected_item = f"selected_agendas={self.context.related_events}"
        specific_related_events = self.context.specific_related_events
        if specific_related_events:
            selected_item = "&".join(
                [f"UID={event_uid}" for event_uid in specific_related_events]
            )
        params = [
            selected_item,
            "metadata_fields=category_title",
            "metadata_fields=start",
            "metadata_fields=end",
            "metadata_fields=has_leadimage",
            "metadata_fields=modified",
            "metadata_fields=UID",
            f"event_dates.query={today}",
            "event_dates.range=min",
            f"b_size={max_items}",
        ]
        current_lang = api.portal.get_current_language()[:2]
        if current_lang != "fr":
            params.append("translated_in_{}=1".format(current_lang))
        if not specific_related_events:
            params += [
                "sort_on=event_dates",
            ]
        url = "{}/@events?{}".format(EVENTS_URL, "&".join(params))
        self.json_data = get_json(url)
        self.refresh_modification_date()
        if self.json_data is None or len(self.json_data.get("items", [])) == 0:  # NOQA
            return []
        linking_view_url = self.context.linking_rest_view.to_object.absolute_url()
        image_scale = self.image_scale
        orientation = self.context.orientation
        items = self.json_data.get("items")[:max_items]
        results = []
        for item in items:
            item_id = normalizeString(item["title"])
            item_url = item["@id"]
            item_uid = item["UID"]
            start = item["start"] and parse(item["start"]) or None
            end = item["end"] and parse(item["end"]) or None
            date_dict = {"start": start, "end": end}
            modified_hash = hash_md5(item["modified"])
            dict_item = {
                "uid": item_uid,
                "title": item["title"],
                "description": item["description"],
                "category": item["category_title"],
                "event_date": date_dict,
                "url": f"{linking_view_url}#/{item_id}?u={item_uid}",
                "has_image": item["has_leadimage"],
                "image": f"{item_url}/@@images/image/{orientation}_{image_scale}?cache_key={modified_hash}",
            }
            results.append(dict_item)
        if specific_related_events:
            results = sorted(
                results, key=lambda x: specific_related_events.index(x["uid"])
            )
        return batch_results(results, self.context.nb_results_by_batch)

    @property
    def see_all_url(self):
        return self.context.linking_rest_view.to_object.absolute_url()

    def is_multi_dates(self, start, end):
        return start and end and start.date() != end.date()


# Simple demo of continuous ADC conversion mode for channel 0 of the ADS1x15 ADC.
# Author: Tony DiCola
# License: Public Domain
import sys
import time
from influxdb import InfluxDBClient
import RPi.GPIO as GPIO

# Raspberry setup
pin = 4
GPIO.setmode(GPIO.BCM)

# Import the ADS1x15 module.
import Adafruit_ADS1x15

client = InfluxDBClient(host='localhost', port=8086)
client.switch_database('giessen')

# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()

# Or create an ADS1015 ADC (12-bit) instance.
#adc = Adafruit_ADS1x15.ADS1015()

# Note you can change the I2C address from its default (0x48), and/or the I2C
# bus by passing in these optional parameters:
#adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1)

# Choose a gain of 1 for reading voltages from 0 to 4.09V.
# Or pick a different gain to change the range of voltages that are read:
#  - 2/3 = +/-6.144V
#  -   1 = +/-4.096V
#  -   2 = +/-2.048V
#  -   4 = +/-1.024V
#  -   8 = +/-0.512V
#  -  16 = +/-0.256V
# See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
GAIN = 1

# Start continuous ADC conversions on channel 0 using the previously set gain
# value.  Note you can also pass an optional data_rate parameter, see the simpletest.py
# example and read_adc function for more infromation.
adc.start_adc(0, gain=GAIN)
# Once continuous ADC conversions are started you can call get_last_result() to
# retrieve the latest result, or stop_adc() to stop conversions.

# Note you can also call start_adc_difference() to take continuous differential
# readings.  See the read_adc_difference() function in differential.py for more
# information and parameter description.

# Read channel 0 for 5 seconds and print out its values.
if (len(sys.argv)==2 and sys.argv[1]=="inf"):
    print(time.asctime(time.localtime(time.time())))
    print('Reading ADS1x15 channel 0 for 5 seconds...')
    while True:
        value = adc.get_last_result()
        print('Channel 0: {0}'.format(value))
        time.sleep(0.5)
else:
    raw_values=[]
    for i in range(6): # 0 to 5
        value = adc.get_last_result()
        raw_values.append(value)
        time.sleep(0.5)
    json_data = [
            {
            "measurement": "feuchte",
            "fields": {
                "location": "bonsai1",
                "value": raw_values[3], # use median (3rd value)
            },
            "time": time.asctime(time.localtime(time.time()))
            }
    ]
    client.write_points(json_data)
    if raw_values[3] > 16500:
        try:
            GPIO.setup(pin, GPIO.OUT)
            time.sleep(3)
            GPIO.setup(pin, GPIO.IN)
        except:
            GPIO.setup(pin, GPIO.IN)
            GPIO.cleanup()

# Stop continuous conversion.  After this point you can't get data from get_last_result!
adc.stop_adc()


import sys
sys.setrecursionlimit(10**6)
N = int(input())
MOD = 10**9+7

graph = [[] for _ in range(N)]
for _ in range(N-1):
    x, y = map(int, input().split())
    x, y = x-1, y-1
    graph[x].append(y)
    graph[y].append(x)

visited = [False] * N
dp = [[-1] * 2 for _ in range(N)]
def dfs(i):
    visited[i] = True
    dp[i][0] = 1
    dp[i][1] = 1
    for j in graph[i]:
        if visited[j] == True:
            continue
        dfs(j)
        dp[i][0] = dp[i][0] * (dp[j][0] + dp[j][1]) % MOD
        dp[i][1] = dp[i][1] * dp[j][0]
    return
dfs(0)
ans = (dp[0][0] + dp[0][1]) % MOD
print(ans)


"""Tests for spiketools.plts.spikes"""

import numpy as np

from spiketools.tests.tutils import plot_test
from spiketools.tests.tsettings import TEST_PLOTS_PATH

from spiketools.plts.spikes import *

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

@plot_test
def test_plot_waveform(twaveform):

    plot_waveform(twaveform,
                  file_path=TEST_PLOTS_PATH, file_name='tplot_waveform1d.png')

    plot_waveform(np.array([twaveform, twaveform + 1, twaveform -1]),
                  average='mean', shade='var', add_traces=True,
                  file_path=TEST_PLOTS_PATH, file_name='tplot_waveform2d.png')

@plot_test
def test_plot_waveforms3d(twaveform):

    plot_waveforms3d(np.vstack([twaveform] *  3),
                     file_path=TEST_PLOTS_PATH, file_name='tplot_waveforms3d.png')

@plot_test
def test_plot_waveform_density(twaveform):

    plot_waveform_density(np.vstack([twaveform] *  3),
                          file_path=TEST_PLOTS_PATH, file_name='tplot_waveform_density.png')

@plot_test
def test_plot_isis(tisis):

    plot_isis(tisis,
              file_path=TEST_PLOTS_PATH, file_name='tplot_isis.png')

@plot_test
def test_plot_firing_rates():

    plot_firing_rates(np.array([2.5, 0.5, 1.2, 3.4]),
                      file_path=TEST_PLOTS_PATH, file_name='tplot_firing_rates.png')


import csv
import datetime
import hashlib
import logging
import os
import re
import sys
import urllib.parse
from dataclasses import dataclass
from collections import defaultdict, deque
from concurrent.futures import ProcessPoolExecutor
from contextlib import contextmanager
from decimal import Decimal
from itertools import chain
from io import BytesIO, IOBase
from pathlib import Path, PurePosixPath
from typing import Optional, Callable

import dateutil
import dateutil.parser
from bs4 import BeautifulSoup
import httpx
from lxml import etree
from lxml.etree import XMLSyntaxError
from stream_unzip import stream_unzip

_COLUMNS = (
    'run_code',
    'company_id',
    'date',
    'file_type',
    'taxonomy',
    'balance_sheet_date',
    'companies_house_registered_number',
    'entity_current_legal_name',
    'company_dormant',
    'average_number_employees_during_period',
    'period_start',
    'period_end',
    'tangible_fixed_assets',
    'debtors',
    'cash_bank_in_hand',
    'current_assets',
    'creditors_due_within_one_year',
    'creditors_due_after_one_year',
    'net_current_assets_liabilities',
    'total_assets_less_current_liabilities',
    'net_assets_liabilities_including_pension_asset_liability',
    'called_up_share_capital',
    'profit_loss_account_reserve',
    'shareholder_funds',
    'turnover_gross_operating_revenue',
    'other_operating_income',
    'cost_sales',
    'gross_profit_loss',
    'administrative_expenses',
    'raw_materials_consumables',
    'staff_costs',
    'depreciation_other_amounts_written_off_tangible_intangible_fixed_assets',
    'other_operating_charges_format2',
    'operating_profit_loss',
    'profit_loss_on_ordinary_activities_before_tax',
    'tax_on_profit_or_loss_on_ordinary_activities',
    'profit_loss_for_period',
    'error',
    'zip_url',
)

logger = logging.getLogger(__name__)

def _xbrl_to_rows(name_xbrl_xml_str_orig):
    name, xbrl_xml_str_orig = name_xbrl_xml_str_orig

    # Slightly hacky way to remove BOM, which is present in some older data
    xbrl_xml_str = BytesIO(xbrl_xml_str_orig[xbrl_xml_str_orig.find(b'<'):])

    # Low level value parsers

    def _date(text):
        return dateutil.parser.parse(text).date()

    def _parse(element, text, parser):
        return \
            parser(element, text.strip()) if text and text.strip() not in ['', '-'] else \
            None

    def _parse_str(element, text):
        return str(text).replace('\n', ' ').replace('"', '')

    def _parse_absolute(element, text):
        # Some cases where employee numbers have a negative sign attached,
        # seemingly indicating negative employee numbers
        return abs(_parse_decimal_with_colon_or_dash(element, text))

    def _parse_decimal(element, text):
        sign = -1 if element.get('sign', '') == '-' else +1
        text_without_thousands_separator = \
            text.replace('.', '').replace(',', '.') if element.get('format', '').rpartition(':')[2] == 'numdotcomma' else \
            text.replace(' ', '') if element.get('format', '').rpartition(':')[2] == 'numspacedot' else \
            text.replace(',', '')

        return sign * Decimal(text_without_thousands_separator) * Decimal(10) ** Decimal(element.get('scale', '0'))

    def _parse_decimal_with_colon_or_dash(element, text):
        # Values seem to have a human readble prefix that isn't part of the value,
        # like "2017 - 2" to mean 2 employees. So we strip the prefix.
        return _parse(element, re.sub(r'(.*:)|(.+- )', '', text), _parse_decimal)

    def _parse_date(element, text):
        format = element.get('format','').rpartition(':')[2].lower()
        day_first = format in ('datedaymonthyear', 'dateslasheu', 'datedoteu')
        if format == 'datedaymonthyearen':
            text = text.replace(' ','')
        text = re.sub(r"(?i)(\d)((st)|(nd)|(rd)|(th))", r"\1", text)
        try:
            return dateutil.parser.parse(text, dayfirst=day_first).date()
        except dateutil.parser.ParserError:
            # Try to parse mis-spellings that still have the first 3 characters right
            return dateutil.parser.parse(re.sub(r'([a-zA-Z]+)', lambda m: m.group(0)[:3], text), dayfirst=day_first).date()

    def _parse_bool(element, text):
        return False if text == 'false' else True if text == 'true' else None

    def _parse_reversed_bool(element, text):
        return False if text == 'true' else True if text == 'false' else None

    # Parsing strategy
    #
    # The XBRL format is a "tagging" format that can tag elements in any order with machine readable metadata.
    # While flexible, this means that it's difficult to efficiently convert to a dataframe.
    #
    # The simplest way to do this would XPath repeatedly to find extract the data for each columnn. This was
    # done in previous versions, but took about 3 times as long as the current solution. The current solution
    # leverages the fact that dictionary lookups are fast, and so constructs dictionaries that can be looked up
    # while iterating through all the elements in the document.

    # Although in some cases a dictionary lookup doesn't seem possible, and so a custom matcher can be defined

    @dataclass
    class _test():
        name: Optional[str]
        search: Callable = lambda element, local_name, attribute_name, context_ref: (element,)

    @dataclass
    class _tn(_test):
        # (Local) Tag name, i.e. withoout namespace
        pass

    @dataclass
    class _av(_test):
        # Attribute value. Matches on the "name" attribute, but stripping off the namespace prefix
        pass

    @dataclass
    class _custom(_test):
        # Custom test when matching on tag name or name attribute isn't enought
        pass

    GENERAL_XPATH_MAPPINGS = {
        'balance_sheet_date': (
            [
                (_av('BalanceSheetDate'), _parse_date),
                (_tn('BalanceSheetDate'), _parse_date),
            ]
        ),
        'companies_house_registered_number': (
            [
                (_av('UKCompaniesHouseRegisteredNumber'), _parse_str),
                (_tn('CompaniesHouseRegisteredNumber'), _parse_str),
            ]
        ),
        'entity_current_legal_name': (
            [
                (_av('EntityCurrentLegalOrRegisteredName', lambda element, local_name, attribute_name, context_ref: chain((element,), element.xpath("./*[local-name()='span'][1]"),)), _parse_str),
                (_tn('EntityCurrentLegalName', lambda element, local_name, attribute_name, context_ref: chain((element,), element.xpath("./*[local-name()='span'][1]"),)), _parse_str),
            ]
        ),
        'company_dormant': (
            [
                (_av('EntityDormantTruefalse'), _parse_bool),
                (_av('EntityDormant'), _parse_bool),
                (_tn('CompanyDormant'), _parse_bool),
                (_tn('CompanyNotDormant'), _parse_reversed_bool),
            ]
        ),
        'average_number_employees_during_period': (
            [
                (_av('AverageNumberEmployeesDuringPeriod'), _parse_absolute),
                (_av('EmployeesTotal'), _parse_absolute),
                (_tn('AverageNumberEmployeesDuringPeriod'), _parse_absolute),
                (_tn('EmployeesTotal'), _parse_absolute),
            ]
        ),
    }

    PERIODICAL_XPATH_MAPPINGS = {
        # balance sheet
        'tangible_fixed_assets': (
            [
                (_tn('FixedAssets'), _parse_decimal),
                (_av('FixedAssets'), _parse_decimal),
                (_tn('TangibleFixedAssets'), _parse_decimal),
                (_av('TangibleFixedAssets'), _parse_decimal),
                (_av('PropertyPlantEquipment'), _parse_decimal),
            ]
        ),
        'debtors': (
            [
                (_tn('Debtors'), _parse_decimal),
                (_av('Debtors'), _parse_decimal),
            ]
        ),
        'cash_bank_in_hand': (
            [
                (_tn('CashBankInHand'), _parse_decimal),
                (_av('CashBankInHand'), _parse_decimal),
                (_av('CashBankOnHand'), _parse_decimal),
            ]
        ),
        'current_assets': (
            [
                (_tn('CurrentAssets'), _parse_decimal),
                (_av('CurrentAssets'), _parse_decimal),
            ]
        ),
        'creditors_due_within_one_year': (
            [
                (_av('CreditorsDueWithinOneYear'), _parse_decimal),
                (_av('Creditors', lambda element, local_name, attribute_name, context_ref: (element,) if 'WithinOneYear' in element.get('contextRef') else ()), _parse_decimal),
            ]
        ),
        'creditors_due_after_one_year': (
            [
                (_av('CreditorsDueAfterOneYear'), _parse_decimal),
                (_custom(None, lambda element, local_name, attribute_name, context_ref: (element,) if 'Creditors' == local_name and 'AfterOneYear' in context_ref else ()), _parse_decimal)
            ]
        ),
        'net_current_assets_liabilities': (
            [
                (_tn('NetCurrentAssetsLiabilities'), _parse_decimal),
                (_av('NetCurrentAssetsLiabilities'), _parse_decimal),
            ]
        ),
        'total_assets_less_current_liabilities': (
            [
                (_tn('TotalAssetsLessCurrentLiabilities'), _parse_decimal),
                (_av('TotalAssetsLessCurrentLiabilities'), _parse_decimal),
            ]
        ),
        'net_assets_liabilities_including_pension_asset_liability': (
            [
                (_tn('NetAssetsLiabilitiesIncludingPensionAssetLiability'), _parse_decimal),
                (_av('NetAssetsLiabilitiesIncludingPensionAssetLiability'), _parse_decimal),
                (_tn('NetAssetsLiabilities'), _parse_decimal),
                (_av('NetAssetsLiabilities'), _parse_decimal),
            ]
        ),
        'called_up_share_capital': (
            [
                (_tn('CalledUpShareCapital'), _parse_decimal),
                (_av('CalledUpShareCapital'), _parse_decimal),
                (_custom(None, lambda element, local_name, attribute_name, context_ref: (element,) if 'Equity' == attribute_name and 'ShareCapital' in element.get('contextRef', '') else ()), _parse_decimal),
            ]
        ),
        'profit_loss_account_reserve': (
            [
                (_tn('ProfitLossAccountReserve'), _parse_decimal),
                (_av('ProfitLossAccountReserve'), _parse_decimal),
                (_custom(None, lambda element, local_name, attribute_name, context_ref: (element,) if 'Equity' == attribute_name and 'RetainedEarningsAccumulatedLosses' in element.get('contextRef', '') else ()), _parse_decimal),
            ]
        ),
        'shareholder_funds': (
            [
                (_tn('ShareholderFunds'), _parse_decimal),
                (_av('ShareholderFunds'), _parse_decimal),
                (_custom(None,  lambda element, local_name, attribute_name, context_ref: (element,) if 'Equity' == attribute_name and 'segment' not in context_ref else ()), _parse_decimal),
            ]
        ),
        # income statement
        'turnover_gross_operating_revenue': (
            [
                (_tn('TurnoverGrossOperatingRevenue'), _parse_decimal),
                (_av('TurnoverGrossOperatingRevenue'), _parse_decimal),
                (_tn('TurnoverRevenue'), _parse_decimal),
                (_av('TurnoverRevenue'), _parse_decimal),
            ]
        ),
        'other_operating_income': (
            [
                (_tn('OtherOperatingIncome'), _parse_decimal),
                (_av('OtherOperatingIncome'), _parse_decimal),
                (_tn('OtherOperatingIncomeFormat2'), _parse_decimal),
                (_av('OtherOperatingIncomeFormat2'), _parse_decimal),
            ]
        ),
        'cost_sales': (
            [
                (_tn('CostSales'), _parse_decimal),
                (_av('CostSales'), _parse_decimal),
            ]
        ),
        'gross_profit_loss': (
            [
                (_tn('GrossProfitLoss'), _parse_decimal),
                (_av('GrossProfitLoss'), _parse_decimal),
            ]
        ),
        'administrative_expenses': (
            [
                (_tn('AdministrativeExpenses'), _parse_decimal),
                (_av('AdministrativeExpenses'), _parse_decimal),
            ]
        ),
        'raw_materials_consumables': (
            [
                (_tn('RawMaterialsConsumables'), _parse_decimal),
                (_av('RawMaterialsConsumables'), _parse_decimal),
                (_tn('RawMaterialsConsumablesUsed'), _parse_decimal),
                (_av('RawMaterialsConsumablesUsed'), _parse_decimal),
            ]
        ),
        'staff_costs': (
            [
                (_tn('StaffCosts'), _parse_decimal),
                (_av('StaffCosts'), _parse_decimal),
                (_tn('StaffCostsEmployeeBenefitsExpense'), _parse_decimal),
                (_av('StaffCostsEmployeeBenefitsExpense'), _parse_decimal),
            ]
        ),
        'depreciation_other_amounts_written_off_tangible_intangible_fixed_assets': (
            [
                (_tn('DepreciationOtherAmountsWrittenOffTangibleIntangibleFixedAssets'), _parse_decimal),
                (_av('DepreciationOtherAmountsWrittenOffTangibleIntangibleFixedAssets'), _parse_decimal),
                (_tn('DepreciationAmortisationImpairmentExpense'), _parse_decimal),
                (_av('DepreciationAmortisationImpairmentExpense'), _parse_decimal),
            ]
        ),
        'other_operating_charges_format2': (
            [
                (_tn('OtherOperatingChargesFormat2'), _parse_decimal),
                (_av('OtherOperatingChargesFormat2'), _parse_decimal),
                (_tn('OtherOperatingExpensesFormat2'), _parse_decimal),
                (_av('OtherOperatingExpensesFormat2'), _parse_decimal),
            ]
        ),
        'operating_profit_loss': (
            [
                (_tn('OperatingProfitLoss'), _parse_decimal),
                (_av('OperatingProfitLoss'), _parse_decimal),
            ]
        ),
        'profit_loss_on_ordinary_activities_before_tax': (
            [
                (_tn('ProfitLossOnOrdinaryActivitiesBeforeTax'), _parse_decimal),
                (_av('ProfitLossOnOrdinaryActivitiesBeforeTax'), _parse_decimal),
            ]
        ),
        'tax_on_profit_or_loss_on_ordinary_activities': (
            [
                (_tn('TaxOnProfitOrLossOnOrdinaryActivities'), _parse_decimal),
                (_av('TaxOnProfitOrLossOnOrdinaryActivities'), _parse_decimal),
                (_tn('TaxTaxCreditOnProfitOrLossOnOrdinaryActivities'), _parse_decimal),
                (_av('TaxTaxCreditOnProfitOrLossOnOrdinaryActivities'), _parse_decimal),
            ]
        ),
        'profit_loss_for_period': (
            [
                (_tn('ProfitLoss'), _parse_decimal),
                (_av('ProfitLoss'), _parse_decimal),
                (_tn('ProfitLossForPeriod'), _parse_decimal),
                (_av('ProfitLossForPeriod'), _parse_decimal),
            ]
        ),
    }

    ALL_MAPPINGS = dict(**GENERAL_XPATH_MAPPINGS, **PERIODICAL_XPATH_MAPPINGS)

    TAG_NAME_TESTS = {
        test.name: (name, priority, test, parser)
        for (name, tests) in ALL_MAPPINGS.items()
        for (priority, (test, parser)) in enumerate(tests)
        if isinstance(test, _tn)
    }

    ATTRIBUTE_VALUE_TESTS = {
        test.name: (name, priority, test, parser)
        for (name, tests) in ALL_MAPPINGS.items()
        for (priority, (test, parser)) in enumerate(tests)
        if isinstance(test, _av)
    }

    CUSTOM_TESTS = tuple(
        (name, priority, test, parser)
        for (name, tests) in ALL_MAPPINGS.items()
        for (priority, (test, parser)) in enumerate(tests)
        if isinstance(test, _custom)
    )

    def _get_dates(context):
        instant_elements = context.xpath("./*[local-name()='instant']")
        start_date_text_nodes = context.xpath("./*[local-name()='startDate']/text()")
        end_date_text_nodes = context.xpath("./*[local-name()='endDate']/text()")
        return \
            (None, None) if context is None else \
            (instant_elements[0].text.strip(), instant_elements[0].text.strip()) if instant_elements else \
            (None, None) if start_date_text_nodes[0] is None or end_date_text_nodes[0] is None else \
            (start_date_text_nodes[0].strip(), end_date_text_nodes[0].strip())

    try:
        document = etree.parse(xbrl_xml_str, etree.XMLParser(ns_clean=True, recover=True))
        root = document.getroot()
        document.xpath("//*[0]")
    except:
        # In at least one case - Prod224_9956_04944372_20100331.xml, the XML seems very badly formed.
        # Suspect this is before Companies House had better validation. The best we can do is log and
        # carry on. We can at least still get a row in the data
        logger.warning("Bad XML. Name: %s XML: %s", name, xbrl_xml_str_orig)
        document = etree.parse(BytesIO(b'<?xml version="1.0" encoding="UTF-8"?><root></root>'), etree.XMLParser(ns_clean=True, recover=True))
        root = document.getroot()

    context_dates = {
        e.get('id'): _get_dates(period)
        for e in document.xpath("//*[local-name()='context']")
        for period in e.xpath("./*[local-name()='period']")[:1]
    }

    fn = os.path.basename(name)
    # Some April 2021 data files end in .zip, but seem to really be html
    mo = re.match(r'^(Prod\d+_\d+)_([^_]+)_(\d\d\d\d\d\d\d\d)\.(html|xml|zip)', fn)
    run_code, company_id, date, filetype = mo.groups()
    allowed_taxonomies = [
        'http://www.xbrl.org/uk/fr/gaap/pt/2004-12-01',
        'http://www.xbrl.org/uk/gaap/core/2009-09-01',
        'http://xbrl.frc.org.uk/fr/2014-09-01/core',
    ]

    core_attributes = (
        run_code,
        company_id,
        _date(date),
        filetype,
        ';'.join(set(allowed_taxonomies) & set(root.nsmap.values())),
    )

    # Mutable dictionaries to store the "priority" (lower is better) of a found value
    general_attributes_with_priorities = {
        name: (10, None)
        for name in GENERAL_XPATH_MAPPINGS.keys()
    }
    periodic_attributes_with_priorities = defaultdict(lambda: {
        name: (10, None)
        for name in PERIODICAL_XPATH_MAPPINGS.keys()
    })

    def tag_name_tests(local_name):
        try:
            yield from (TAG_NAME_TESTS[local_name],)
        except KeyError:
            pass

    def attribute_value_tests(attribute_value):
        try:
            yield from (ATTRIBUTE_VALUE_TESTS[attribute_value],)
        except KeyError:
            pass

    def handle_general(element, local_name, attribute_value, context_ref, name, priority, test, parse):
        best_priority, best_value = general_attributes_with_priorities[name]

        if priority > best_priority:
            return

        for element in test.search(element, local_name, attribute_value, context_ref):
            filtered = ((e.text or '') for e in element.iter() if e.tag.rpartition('}')[2] != "exclude")
            value = _parse(element, ''.join(filtered), parse)
            if value is not None:
                general_attributes_with_priorities[name] = (priority, value)
                break

    def handle_periodic(element, local_name, attribute_value, context_ref, name, priority, test, parse):
        if not context_ref:
            return
        dates = context_dates.get(context_ref)
        if not dates:
            return

        for element in test.search(element, local_name, attribute_value, context_ref):
            best_priority, best_value = periodic_attributes_with_priorities[dates][name]

            if priority >= best_priority:
                return

            filtered = ((e.text or '') for e in element.iter() if etree.QName(e).localname != "exclude")
            value = _parse(element, ''.join(filtered), parse)
            if value is not None:
                periodic_attributes_with_priorities[dates][name] = (priority, value)
                break

    error = None
    try:
        for element in document.xpath('//*'):
            _, _, local_name = element.tag.rpartition('}')
            _, _, attribute_value = element.get('name', '').rpartition(':')
            context_ref = element.get('contextRef', '')

            for name, priority, test, parse in chain(tag_name_tests(local_name), attribute_value_tests(attribute_value), CUSTOM_TESTS):
                handler = \
                    handle_general if name in general_attributes_with_priorities else \
                    handle_periodic

                handler(element, local_name, attribute_value, context_ref, name, priority, test, parse)

        general_attributes = tuple(
            general_attributes_with_priorities[name][1]
            for name in GENERAL_XPATH_MAPPINGS.keys()
        )

        periods = tuple(
            (datetime.date.fromisoformat(period_start_end[0]), datetime.date.fromisoformat(period_start_end[1]))
            + tuple(
                periodic_attributes[name][1]
                for name in PERIODICAL_XPATH_MAPPINGS.keys()
            )
            for period_start_end, periodic_attributes in periodic_attributes_with_priorities.items()
        )
        sorted_periods = sorted(periods, key=lambda period: (period[0], period[1]), reverse=True)
    except ValueError as e:
        error = str(e)

    return \
        ((core_attributes + (None,) * (2 + len(GENERAL_XPATH_MAPPINGS) + len(PERIODICAL_XPATH_MAPPINGS)) + (error,)),) if error is not None else \
        tuple((core_attributes + general_attributes + period + (None,)) for period in sorted_periods) if sorted_periods else \
        ((core_attributes + general_attributes + (None,) * (3 + len(PERIODICAL_XPATH_MAPPINGS))),)

@contextmanager
def stream_read_xbrl_zip(
    zip_bytes_iter,
    zip_url=None,
):
    queue = deque()
    num_workers = max(os.cpu_count() - 1, 1)

    def imap(executor, func, param_iterables):
        for params in param_iterables:
            if len(queue) == num_workers:
                yield queue.popleft().result()

            queue.append(executor.submit(func, params))

        while queue:
            yield queue.popleft().result()

    with ProcessPoolExecutor(max_workers=num_workers) as executor:
        yield _COLUMNS, (
            row + (zip_url,)
            for results in imap(executor, _xbrl_to_rows, ((name.decode(), b''.join(chunks)) for name, _, chunks in stream_unzip(zip_bytes_iter)))
            for row in results
        )

@contextmanager
def stream_read_xbrl_sync(
    ingest_data_after_date=datetime.date(datetime.MINYEAR, 1, 1),
    data_urls=(
        'https://download.companieshouse.gov.uk/en_accountsdata.html',
        'https://download.companieshouse.gov.uk/en_monthlyaccountsdata.html',
        'https://download.companieshouse.gov.uk/historicmonthlyaccountsdata.html',
    ),
    get_client = lambda: httpx.Client(timeout=60.0, transport=httpx.HTTPTransport(retries=3)),
    chunk_size = 100 * 1048576  # 100 MiB
):
    def extract_start_end_dates(url):
        file_basename = os.path.basename(url)
        file_name_no_ext = os.path.splitext(file_basename)[0]

        if 'JanToDec' in file_name_no_ext or 'JanuaryToDecember' in file_name_no_ext:
            file_name_no_ext = os.path.splitext(url)[0]
            year = file_name_no_ext[-4:]
            return datetime.date(int(year), 1, 1), datetime.date(int(year), 12, 31)
        elif 'Accounts_Monthly_Data' in file_name_no_ext and file_name_no_ext[-4:].isnumeric():
            year = int(file_name_no_ext[-4:])
            month_name = file_name_no_ext.split('-')[1][:-4]
            # Convert the month name to a month number
            month_num = datetime.datetime.strptime(month_name, '%B').month
            # Calculate the last date of the month
            first_day_of_month = datetime.date(year, month_num, 1)
            next_month = datetime.date(year, month_num, 28) + datetime.timedelta(days=4)
            last_day_of_month = next_month - datetime.timedelta(days=next_month.day)
            return (first_day_of_month, last_day_of_month)
        elif 'Accounts_Bulk_Data' in file_name_no_ext:
            date_str = file_name_no_ext.split('-', 1)[1]
            day = datetime.datetime.strptime(date_str, '%Y-%m-%d').date()
            return (day, day)
        else:
            return (None, None)

    def get_content(client, url):
        r = client.get(url)
        r.raise_for_status()
        return r.content

    @contextmanager
    def get_content_streamed(client, url):

        def get_chunks():
            start = 0
            end = chunk_size - 1
            etag = None
            remaining = None

            while remaining is None or remaining > 0:
                with client.stream('GET', url, headers={
                    'range': f'bytes={start}-{end}'
                }) as r:
                    r.raise_for_status()
                    if etag is None:
                        etag = r.headers['etag']
                    else:
                        if etag != r.headers['etag']:
                            raise Exception('etag has changed since beginning requests')
                    if remaining is None:
                        remaining = int(r.headers['content-range'].split('/')[1])
                    content_length =int(r.headers['content-length'])
                    assert content_length > 0
                    remaining -= content_length
                    yield from r.iter_bytes(chunk_size=65536)
                start += chunk_size
                end += chunk_size

        chunks = get_chunks()
        try:
            yield chunks
        finally:
            # This is for the case of unfinished iteration. It raises a GeneratorExit in get_chunks, so any
            # open context in "get_chunks" gets properly closed, i.e. to close its open HTTP connection
            chunks.close()

    dummy_list_to_ingest = [
        (datetime.date(2021, 5, 2), (('1', '2'), ('3', '4'))),
        (datetime.date(2022, 2, 8), (('5', '6'), ('7', '8'))),
    ]

    with get_client() as client:
        pages_of_links = [
            (data_url, BeautifulSoup(get_content(client, data_url), 'html.parser').find_all('a'))
            for data_url in data_urls
        ]

        all_zip_urls = [
            link.attrs['href'].strip() if link.attrs['href'].strip().startswith('http://') or link.attrs['href'].strip().startswith('https://') else
            urllib.parse.urljoin(data_url, link.attrs['href'].strip())
            for (data_url, page_of_links) in pages_of_links
            for link in page_of_links
            if link.attrs.get('href', '').endswith('.zip')
        ]

        all_zip_urls_with_dates = [
            (zip_url, extract_start_end_dates(zip_url))
            for zip_url in all_zip_urls
        ]

        all_zip_urls_with_parseable_dates = [
            (zip_url, dates)
            for (zip_url, dates) in all_zip_urls_with_dates
            if dates != (None, None)
        ]

        all_zip_urls_with_dates_oldest_first = sorted(
            all_zip_urls_with_parseable_dates, key=lambda zip_start_end: (zip_start_end[1][0], zip_start_end[1][1])
        )

        zip_urls_with_date_in_range_to_ingest = [
            (zip_url, (start_date, end_date))
            for (zip_url, (start_date, end_date)) in all_zip_urls_with_dates_oldest_first
            if (start_date, end_date) != (None, None) and end_date > ingest_data_after_date
        ]

        def _final_date_and_rows():
            for zip_url, (start_date, end_date) in zip_urls_with_date_in_range_to_ingest:
                with get_content_streamed(client, zip_url) as chunks:
                    with stream_read_xbrl_zip(chunks, zip_url=zip_url) as (_, rows):
                        yield (start_date, end_date), rows

        yield (_COLUMNS, _final_date_and_rows())

def stream_read_xbrl_sync_s3_csv(s3_client, bucket_name, key_prefix):

    def _to_file_like_obj(iterable):
        chunk = b''
        offset = 0
        it = iter(iterable)

        def up_to_iter(size):
            nonlocal chunk, offset

            while size:
                if offset == len(chunk):
                    try:
                        chunk = next(it)
                    except StopIteration:
                        break
                    else:
                        offset = 0
                to_yield = min(size, len(chunk) - offset)
                offset = offset + to_yield
                size -= to_yield
                yield chunk[offset - to_yield : offset]

        class FileLikeObj(IOBase):
            def readable(self):
                return True

            def read(self, size=-1):
                return b''.join(
                    up_to_iter(float('inf') if size is None or size < 0 else size)
                )

        return FileLikeObj()

    def _convert_to_csv(columns, rows):
        class PseudoBuffer:
            def write(self, value):
                return value.encode("utf-8")

        pseudo_buffer = PseudoBuffer()
        csv_writer = csv.writer(pseudo_buffer, quoting=csv.QUOTE_NONNUMERIC)
        yield csv_writer.writerow(columns)
        yield from (csv_writer.writerow(row) for row in rows)

    s3_paginator = s3_client.get_paginator('list_objects_v2')
    dates = (
        # The -10: is to support older versions where only the end date was in the file name
        datetime.date.fromisoformat(PurePosixPath(content['Key']).stem[-10:])
        for page in s3_paginator.paginate(Bucket=bucket_name, Prefix=key_prefix)
        for content in page.get('Contents', ())
    )
    latest_completed_date = max(dates, default=datetime.date(datetime.MINYEAR, 1, 1))

    with stream_read_xbrl_sync(latest_completed_date) as (columns, final_date_and_rows):
        for ((start_date, final_date), rows) in final_date_and_rows:
            key = f'{key_prefix}{start_date}--{final_date}.csv'
            logger.info('Saving Companies House accounts data to %s/%s ...', bucket_name, key)
            csv_file = _to_file_like_obj(_convert_to_csv(columns, rows))
            s3_client.upload_fileobj(Bucket=bucket_name, Key=key, Fileobj=csv_file)
            logger.info('Saving Companies House accounts data to %s/%s (done)', bucket_name, key)

def stream_read_xbrl_debug(zip_url, run_code, company_id, date, debug_cache_folder=".debug-cache"):
    Path(debug_cache_folder).mkdir(parents=True, exist_ok=True)

    # Hashing so we have a filesystem-safe URL
    hashed_zip_url = hashlib.sha256(zip_url.encode('utf-8')).hexdigest()
    local_zip_file = Path(debug_cache_folder).joinpath(hashed_zip_url)

    if not local_zip_file.exists():
        print('The ZIP', zip_url, 'does not exist in local cache. Downloading...', file=sys.stderr)
        done = False
        try:
            with \
                    httpx.stream('GET', zip_url) as r, \
                    open(local_zip_file, 'wb') as f:
                r.raise_for_status()
                for chunk in r.iter_bytes():
                    f.write(chunk)
            done = True
        finally:
            if not done:
                local_zip_file.unlink(missing_ok=True)
        print('Downloaded', file=sys.stderr)
    else:
        print('Found', zip_url, 'in local cache', file=sys.stderr)

    def local_chunks():
        with open(local_zip_file, 'rb') as f:
            while True:
                chunk = f.read(65536)
                if not chunk:
                    break
                yield chunk

    print('Searching ZIP for member file matching', run_code, company_id, date, file=sys.stderr)
    found = False
    for name, _, chunks in stream_unzip(local_chunks()):
        fn = os.path.basename(name.decode('utf-8'))
        mo = re.match(r'^(Prod\d+_\d+)_([^_]+)_(\d\d\d\d\d\d\d\d)\.(html|xml)', fn)
        _run_code, _company_id, _date, _ = mo.groups()
        # print(_run_code, _company_id, _date)

        if _run_code == run_code and _company_id == company_id and _date == date.isoformat().replace('-', ''):
            print('Found matching file', name, file=sys.stderr)
            found = True
            for chunk in chunks:
                sys.stdout.buffer.write(chunk)
        else:
            for chunk in chunks:
                pass

    if not found:
        print('No matching member file found', file=sys.stderr)

    print('Finished', file=sys.stderr)


from global_var_config import calc_ranging_threshold

def calc_ranging(times):
    light_speed = 299792458
    times = times / 63.8976 / 1e9
    rnd0 = times[:, 3] - times[:, 0]
    rnd1 = times[:, 5] - times[:, 2]
    rsp0 = times[:, 2] - times[:, 1]
    rsp1 = times[:, 4] - times[:, 3]
    sum_r = rnd0 + rnd1 + rsp0 + rsp1
    r = light_speed * (rnd0 * rnd1 - rsp0 * rsp1) / sum_r
    mask = (r < calc_ranging_threshold)

    return r, mask


def equation(a,b,c):
    d=(b*b)-(4*a*c)
    if(d>0):
        return("the equation having real roots")
    elif(d==0):
        return("the equation having equal roots")
    elif(d<0):
        return("the equation having no real roots! the roots are imaginary")
a=int(input("enter the coefficient of x square"))
b=int(input("enter the coefficient of x"))
c=int(input("enter the constant term"))
x=equation(a,b,c)
print(x)

PROGRAMS/wap create a function to display whether the quadratic equation having rela, equal or imaginary roots.py


from PyPDF2 import PdfMerger
import os

#Create an instance of PdfFileMerger() class
merger = PdfMerger()

#Define the path to the folder with the PDF files
path_to_files = r'C:/Users/kaabi/Downloads/Rent Slips Vitry/'

folder_name = os.path.split(path_to_files.rstrip('/'))[-1]

#Get the file names in the directory
for file_name in os.listdir(path_to_files):

    if file_name.endswith(".pdf"):
        merger.append(path_to_files + file_name)

#Write out the merged PDF file
merger.write(path_to_files + "/" + folder_name + ".pdf")
merger.close()

# -*- coding: utf-8 -*-
# """
# Created on Wed Sep  6 14:35:21 2023

# @author: kaabi
# """

# from PyPDF2 import PdfMerger
# import os

# #Create an instance of PdfFileMerger() class
# merger = PdfMerger()

# #Define the path to the folder with the PDF files
# path_to_files = r'C:/Users/ChimieENS/Downloads/Documents_RP/'

# #Get the file names in the directory
# for root, dirs, file_names in os.walk(path_to_files):
#     #Iterate over the list of the file names
#     for file_name in file_names:
#         #Append PDF files
#         merger.append(path_to_files + file_name)

# #Write out the merged PDF file
# merger.write("C:/Users/ChimieENS/Downloads/Documents_RP/merged_all_pages.pdf")
# merger.close()


T = int(input())
def calculate_profit(i, j):
    global max_home
    for k in range(1, N + 2):
        home = []
        expense = k * k + (k - 1) * (k - 1)
        for ni in [y for y in range(i - (k - 1), i + k) if 0 <= y < N]:
            for nj in [x for x in range(j - (k - 1), j + k) if 0 <= x < N]:
                if abs(i - ni) + abs(j - nj) <= k - 1:
                    if city[ni][nj] == 1:
                        home.append((i, j))
        profit = len(home) * M - expense
        if profit >= 0:
            max_home = max(max_home, len(home))

for tc in range(1, T + 1):
    N, M = map(int, input().split())
    city = [list(map(int, input().split())) for _ in range(N)]
    max_home = 0
    for i in range(N):
        for j in range(N):
            calculate_profit(i, j)
    print(f'#{tc} {max_home}')


import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import base64
import requests
import io
from scipy.io.wavfile import write
import sounddevice as sd
from pydub import AudioSegment
from pydub.playback import play
import numpy as np
import os

class VisionTTSNode(Node):
    def __init__(self):
        super().__init__('vision_tts_node')

        # Declare and get parameters
        self.declare_parameters(
            namespace='',
            parameters=[
                ('openai_api_key', os.environ.get('OPENAI_API_KEY')),
                ('vision_model', 'gpt-4-vision-preview'),
                ('tts_model', 'tts-1'),
                ('stt_model', 'whisper-1'),
                ('voice', 'echo'),
                ('camera_wait_ms', 2056),
                ('max_tokens_vision', 32),
                ('audio_record_seconds', 6),
                ('audio_sample_rate', 22100),
                ('audio_channels', 1),
                ('audio_output_path', '/tmp/gpt_audio.wav')
            ]
        )
        self.api_key = self.get_parameter('openai_api_key').value
        self.vision_model = self.get_parameter('vision_model').value
        self.tts_model = self.get_parameter('tts_model').value
        self.stt_model = self.get_parameter('stt_model').value
        self.voice = self.get_parameter('voice').value
        self.camera_wait_ms = self.get_parameter('camera_wait_ms').value
        self.max_tokens_vision = self.get_parameter('max_tokens_vision').value
        self.audio_record_seconds = self.get_parameter('audio_record_seconds').value
        self.audio_sample_rate = self.get_parameter('audio_sample_rate').value
        self.audio_channels = self.get_parameter('audio_channels').value
        self.audio_output_path = self.get_parameter('audio_output_path').value

        # Initialize a CvBridge to convert ROS images to OpenCV format
        self.bridge = CvBridge()

        # Subscription to the image topic
        self.image_subscription = self.create_subscription(
            Image,
            'camera/image_raw',
            self.image_callback,
            10
        )
        self.get_logger().info('Subscribed to camera image topic.')

        # Initialize the OpenAI client
        self.client = None  # This should be replaced with the actual client initialization, if available

    def image_callback(self, msg):
        try:
            # Convert ROS2 image message to OpenCV format
            cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')

            # Process the image and perform API calls, etc.
            self.process_image(cv_image)
        except Exception as e:
            self.get_logger().error('Failed to process image: %r' % (e,))

    def process_image(self, cv_image):
        # Encode the image as base64
        base64_image = self.encode_image_to_base64(cv_image)

        # Record audio
        self.record_audio()

        # Transcribe audio to text
        prompt = self.transcribe_audio()

        # Send to vision model
        reply = self.vision(prompt, base64_image)

        # Play audio response
        self.text2speech(reply)

    def encode_image_to_base64(self, img):
        _, buffer = cv2.imencode('.jpg', img)
        jpg_as_text = base64.b64encode(buffer).decode('utf-8')
        return jpg_as_text

    def record_audio(self):
        self.get_logger().info(f'Recording for {self.audio_record_seconds} seconds.')
        audio_data = sd.rec(
            int(self.audio_record_seconds * self.audio_sample_rate),
            samplerate=self.audio_sample_rate,
            channels=self.audio_channels,
        )
        sd.wait()  # Wait until recording is finished
        write(self.audio_output_path, self.audio_sample_rate, audio_data)  # Save as WAV file

    def transcribe_audio(self, audio_path=None):
        if audio_path is None:
            audio_path = self.audio_output_path

        # This should be replaced with the actual transcription code using your OpenAI client
        transcript = 'This is a dummy transcript.'
        return transcript

    def vision(self, prompt, base64_image):
        # This should be replaced with the actual vision API call using your OpenAI client
        response = 'This is a dummy response from the vision model.'
        return response

    def text2speech(self, text):
        # This should be replaced with the actual TTS API call using
        pass

def main():
    rclpy.init()
    node = VisionTTSNode()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == '__main__':
    main()


import utils
from lexicon import lex

class FeatureVectorAffiliation(object):
	def __init__(self):
		self.string = None
		self.label = None
		self.line_stat = None # LINESTART, LINEIN, LINEEND
		self.bold = False
		self.italic = False
		self.capital = None # INITCAP, ALLCAPS, NOCAPS
		self.digit = None # ALLDIGIT, CONTAINDIGIT, NODIGIT
		self.single_char = False
		self.proper_name = False
		self.common_name = False
		self.first_name = False
		self.location_name = False
		self.country_name = False
		self.punct_type = None
		self.word_shape = None # NOPUNCT, OPENBACKET, ENDBACKET, DOT, COMMA, HYPHEN, QUOTE, PUNCT

	@staticmethod
	def proc_line(line, line_stat, is_place):
		features = FeatureVectorAffiliation()
		tokens = line.split()
		for i, token in enumerate(tokens):
			label = None
			if i+1 < len(tokens):
				label = tokens[i+1]
			features.string = token
			features.label = label
			features.line_stat = line_stat
			if len(token) == 1:
				features.single_char = True
			if utils.test_all_captial(token):
				features.capital = "ALLCAPS"
			elif utils.test_first_capital(token):
				features.capital = "INITCAP"
			else:
				features.capital = "NOCAPS"

			features.common_name = False
			features.proper_name = False
			features.location_name = is_place

			if utils.test_all_digit(token):
				features.digit = "ALLDIGIT"
			elif utils.test_contain_digit(token):
				features.digit = "CONTAINDIGIT"
			else:
				features.digit = "NODIGIT"

			features.punct_type = "NOPUNCT"
			if token == ",":
				features.punct_type = "COMMA"
			if token == "(" or token == "[":
				features.punct_type = "OPENBRACKET"
			if token == ".":
				features.punct_type = "DOT"
			if token == "-":
				features.punct_type = "HYPHEN"
			if token == "\"" or token == "\'" or token == "`":
				features.punct_type = "QUOTE"

			features.country_name = lex.is_country(token)

			features.word_shape = utils.get_word_shape(token)
		return features

	@staticmethod
	def proc_lines(lines, location):
		line_stat = "LINESTART"
		result = []
		location = location[0]
		cur_pos_place = 0
		cur_token = 0

		for i, line in enumerate(lines):
			is_loc = False
			if line == "\n":
				result.append("\n \n")
				continue

			for j in range(cur_pos_place, len(location)):
				loc = location[j]
				if loc[0] <= cur_token and loc[1] >= cur_token:
					is_loc = True
					cur_pos_place = j
					break
				elif loc[0] > cur_token:
					is_loc = False
					cur_pos_place = j
					break

			if (line.strip() == "@newline"):
				line_stat = "LINESTART"
				continue

			if line.strip() == "":
				result.append("\n")
				line_stat = "LINESTART"
			else:
				if (i+1) < len(lines):
					if lines[i+1].strip() == "":
						line_stat = "LINEEND"
				elif (i+1) == len(lines):
					line_stat = "LINEEND"

				vector = FeatureVectorAffiliation.proc_line(line, line_stat, is_loc)
				result.append(vector.gen_vector())

				if line_stat == "LINESTART":
					line_stat = "LINEIN"

			cur_token += 1

		return result

	def gen_vector(self):
		if self.string is None:
			return None
		if len(self.string) == 0:
			return None
		res = [self.string]
		s = self.string
		res.append(s.lower())
		# prefix
		res.append(s[:1])
		res.append(s[:2])
		res.append(s[:3])
		res.append(s[:4])
		# suffix
		res.append(s[-1])
		res.append(s[-2:])
		res.append(s[-3:])
		res.append(s[-4:])

		res.append(self.line_stat)
		if self.digit == "ALLDIGIT":
			res.append("NOCAPS")
		else:
			res.append(self.capital)
		res.append(self.digit)

		if self.single_char:
			res.append("1")
		else:
			res.append("0")

		if self.proper_name:
			res.append("1")
		else:
			res.append("0")

		if self.common_name:
			res.append("1")
		else:
			res.append("0")

		if self.location_name:
			res.append("1")
		else:
			res.append("0")

		if self.country_name:
			res.append("1")
		else:
			res.append("0")

		res.append(self.punct_type)

		res.append(self.word_shape)

		if self.label is not None:
			res.append(self.label)
		else:
			res.append("0")
		return " ".join(res)


#!/usr/bin/python3

import time
import wiringpi
import config as CONFIG

class AcServo:
	AC_ON_POSITION = 150
	AC_ON_REST_POSITION = 151
	AC_OFF_POSITION = 165
	ON_REST_DELAY = 1

	def __init__(self, servo_pin, servo_delay):
		wiringpi.wiringPiSetupGpio()
		wiringpi.pinMode(servo_pin, wiringpi.GPIO.PWM_OUTPUT)
		wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)
		wiringpi.pwmSetClock(CONFIG.PWM_CLOCK)
		wiringpi.pwmSetRange(CONFIG.PWM_RANGE)

		self.servo_pin = servo_pin
		self.servo_delay = servo_delay
		self.current_state = False

	def on(self):
		self._move(AcServo.AC_ON_POSITION)
		time.sleep(AcServo.ON_REST_DELAY)
		self._move(AcServo.AC_ON_REST_POSITION)
		self.current_state = True

	def off(self):
		self._move(AcServo.AC_OFF_POSITION)
		self.current_state = False

	def get_current_state(self):
		return self.current_state

	def _move(self, servo_position):
		wiringpi.pwmWrite(self.servo_pin, servo_position)
		time.sleep(self.servo_delay)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Code for grabbing data from ARM THREDDS catalogues using siphon
@author: Mónica Zamora Z., UChile. http://mzamora.github.io
"""

from __future__ import print_function
from siphon.catalog import TDSCatalog
import pandas as pd

# i ordered data in 2 catalogues. Add xml link after logging in!
#cat=TDSCatalog('YourARMlink')
cat=TDSCatalog('https://archive.arm.gov/orders/catalog/orders/zamoram1/225099/catalog.xml?ticket=ST-4668-OlIM3xgaZeuGe2jEEfBeMlZGF0ssso')
dss=list(cat.datasets) # list of files in the dataset

# types of files (manually putting the different prefixes of the ordered products)
prfx1='corxsacrgridrhiM1.c1.'
prfx2='corkasacrgridrhiM1.c1.'

# set date (loopable)
yy=2019
mm=4
dd=26
thisday=pd.datetime(yy,mm,dd)
# beginning of the filename to search for
nm1=prfx1+thisday.strftime('%Y%m%d')
nm2=prfx2+thisday.strftime('%Y%m%d')
# filenames corresponding to that date
matches1 = [match for match in dss if nm1 in match]
matches2 = [match for match in dss if nm2 in match]

#access the variable list in the 1st set of nc files
ds=cat.datasets[matches1[0]] #for the first file
remoteds=ds.remote_access() #access the nc file remotely
remoteds #print its data
t=remoteds.variables['time'][:] #to grab data from the remote dataset

#access the variable list in the 2nd set of nc files
ds=cat.datasets[matches2[0]] #for the first file
remoteds=ds.remote_access() #access the nc file remotely
remoteds #print its data

# loop for grabbing or downloading
#for match in matches1:
#    ds=cat.datasets[match]
    #ds.download() #this will download the nc file!
    #remoteds=ds.remote_access() #access the nc file remotely
    #t=remoteds.variables['time'][:]


from my_call_serp import serach_serp
from html_contetss import my_peoplecard
from pdf_converter import make_html_pdf
websites_links,snippets,search_images,my_people_data = serach_serp("Ajey Nagar","United States")
if my_people_data!={}:
    post_images1 = ""
    prof_images1 = ""
    if my_people_data.get("post_images")!=None:
        for image_link in my_people_data["post_images"]:
            post_images11= f'''
                '''
            post_images1 += post_images11
    if  my_people_data.get("profile_images")!=None:
        prof_images1 +=f""""""
    if my_people_data.get("websites")!=None:
        websites1 = []
        for m in my_people_data["websites"]:
            if m!=None or m!="":
                # print(len(my_people_data["websites"]))
                websites1.append(m)
        if len(websites1)>0:
            websites1 = "\n".join(websites1)
    else:
        websites1 = None

    html_people_card = my_peoplecard(my_people_data,websites=websites1,post_images=post_images1,profile_images=prof_images1)
    make_html_pdf("Ajey Nagar",html_content=html_people_card,main_path="pdfs")


def analysis(string_list):
    if len(string_list) == 0:
        return IndexError
    if len(string_list) == 3:
        if not string_list[0].isalpha():
            return NameError
        if '@' and '.' not in string_list[1]:
            return SyntaxError
        if int(string_list[2]) > 99 or int(string_list[2]) < 10:
            return ValueError
        else:
            return True

bad_log = open('registrations_bad.log', 'w')
good_log = open('registrations_good.log', 'w')

with open('registrations.txt', 'r') as infile:
    for string in infile:
        data = string.split()
        flag = analysis(data)
        if flag == IndexError:
            bad_log.write(string.rstrip() + (' ' * 5) + 'НЕ присутствуют все три поля' + '\n')
        if flag == NameError:
            bad_log.write(string.rstrip() + (' ' * 5) + 'поле имени содержит НЕ только буквы' + '\n')
        if flag == SyntaxError:
            bad_log.write(string.rstrip() + (' ' * 5) + 'поле емейл НЕ содержит @ и .(точку)' + '\n')
        if flag == ValueError:
            bad_log.write(string.rstrip() + (' ' * 5) + 'поле возраст НЕ является числом от 10 до 99' + '\n')
        if flag == True:
            good_log.write(string.rstrip() + '\n')

bad_log.close()
good_log.close()


from django.contrib import admin
from django.urls import path, include
from recipes import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', views.hello_view),
    path('add/$', views.add),
    path('getAllUser/$', views.getAllUser),
    path('index/', views.index),
    path('常見問題/', views.normal,name="normal")
    #url(r'^new_add/(\d+)/(\d+)/$', views.add2, name='add2')
]


"""Prototypes to conveniently define data classes with built-in validation."""
from __future__ import annotations
from typing import Union, Optional, Any, Callable
from collections import Counter
from copy import copy, deepcopy
import re
from . import types as dvtypes
from .validation import ValidationResult, Validator
from .exceptions import DataValidationError

DataFieldDescT = Union[
    "DataField",        # Fully instantiated DataField
    dict[str, Any],     # For shorthand constructor notations
]

DataGroupDataT = dict[str, DataFieldDescT]

DataGroupDescT = Union[
    "DataGroup", DataGroupDataT  # Fully instantiated DataGroup # shorthand constructor
]

SchemaDescT = dict[str, Union[DataGroupDescT, DataFieldDescT]]

SchemaDataT = dict[str, Union[dict[str, Any], Any]]

FieldParamSpecT = list[Union[tuple[str, Any, str], tuple[str, Any, str, Any]]]

class DataField:
    """Base class for data schema fields.

    To instantiate, use VField, CField, or shorthand notation in a DataSchema
    declaration.
    """

    name: str
    type_: Any
    typedesc: str
    required: bool

    _fieldparams: FieldParamSpecT = [
        ("name", str, "The name of the DataField"),
        ("type_", Any, "The data type for the DataField"),
        ("typedesc", str, "A user-intelligible description of the data type"),
        ("required", bool, "Whether the field is required", True),
    ]

    def __init__(self, name: str, type_: Any, typedesc: str, required: bool = True):
        """Instantiates a new DataField."""
        if "/" in name:
            raise TypeError(
                "DataField and DataGroup names may not include the character `/`."
            )
        self.name = name
        self.type_ = type_
        self.typedesc = typedesc
        self.required = required

    @classmethod
    def fieldparams(cls) -> FieldParamSpecT:
        """Returns the parameter list for a DataField of this type."""
        return deepcopy(cls._fieldparams)

    def fieldspecs(self) -> dict[str, Any]:
        """Returns the values for each parameter of the DataField."""
        specs: dict[str, Any] = {"fieldtype": self.__class__}
        for param in self._fieldparams:
            specs[param[0]] = getattr(self, param[0])
        return specs

    def __str__(self) -> str:
        """Returns a (possibly shortened) string representaiton of the DataField."""
        label = self.__class__.__name__
        return (
            f"{label}({repr(self.name)}, {self.type_}, "
            f"{repr(self.typedesc)}, required={self.required})"
        )

    def __repr__(self) -> str:
        """Returns a Pythonesque string representation of the DataField."""
        return self.__str__()

class CField(DataField):
    """Defines a manually validated data field for DataSchema classes."""

    vmethod: Union[str, Callable[[Any, Any], Any]]
    forcecast: Optional[bool]

    _fieldparams: FieldParamSpecT = [
        ("name", str, "The name of the DataField"),
        ("type_", Any, "The data type for the DataField"),
        ("typedesc", str, "A user-intelligible description of the data type"),
        (
            "vmethod",
            Callable[[Any, Any], Any],
            (
                "A callable accepting a two arguments: the first is the type_ of the "
                "DataField and the second the value. The callable should raise either "
                "a TypeError or a DataValidationError if the value is invalid, and "
                "must return a (possibly processed) version of the value it was passed "
                "which fits the type_ it was passed."
            ),
        ),
        (
            "forcecast",
            Optional[bool],
            "Whether to force casting of data during validation",
            None,
        ),
        ("required", bool, "Whether the field is required", True),
    ]

    def __init__(
        self,
        name: str,
        type_: str,
        typedesc: str,
        vmethod: Callable[[Any, Any], Any],
        forcecast: Optional[bool] = None,
        required: bool = True,
    ):
        """Instantiates a new CField."""
        super().__init__(name, type_, typedesc, required)
        self.vmethod = vmethod
        self.forcecast = forcecast

    def __repr__(self) -> str:
        """Returns a Pythonesque string representation of the CField."""
        label = self.__class__.__name__
        params = {
            "name": repr(self.name),
            "type_": repr(self.type_),
            "typedesc": repr(self.typedesc),
            "vmethod": repr(self.vmethod),
            "forcecast": repr(self.forcecast),
            "required": repr(self.required),
        }
        paramspec = ", ".join(f"{k}={v}" for k, v in params.items())
        return f"{label}({paramspec})"

class VField(DataField):
    """Defines an auto-validated data field for DataSchema classes."""

    constraint: Any
    forcecast: Optional[bool]
    ignorecase: Optional[bool]
    flags: Union[re.RegexFlag, int]

    _fieldparams: FieldParamSpecT = [
        ("name", str, "The name of the DataField"),
        ("type_", Any, "The data type for the DataField"),
        ("typedesc", str, "A user-intelligible description of the data type"),
        ("constraint", Any, "A DataValidator constraint approprite for type_"),
        (
            "forcecast",
            Optional[bool],
            "Whether to force casting of data during validation",
            None,
        ),
        (
            "ignorecase",
            Optional[bool],
            "Whether to ignore case for string-type data validation",
            None,
        ),
        (
            "flags",
            Union[re.RegexFlag, int],
            "Flags to pass to the regular expression engine if type_ is `str`.",
            0,
        ),
        ("required", bool, "Whether the field is required", True),
    ]

    def __init__(
        self,
        name: str,
        type_: str,
        typedesc: str,
        constraint: Any,
        forcecast: Optional[bool] = None,
        ignorecase: Optional[bool] = None,
        flags: Union[re.RegexFlag, int] = 0,
        required: bool = True,
    ):
        """Instantiates a new VField."""
        super().__init__(name, type_, typedesc, required)
        self.constraint: Any = constraint
        self.forcecast: Optional[bool] = forcecast
        self.ignorecase: Optional[bool] = ignorecase
        self.flags: Union[re.RegexFlag, int] = flags

    def __repr__(self) -> str:
        """Returns a Pythonesque string representation of the VField."""
        label = self.__class__.__name__
        params = {
            "name": repr(self.name),
            "type_": repr(self.type_),
            "typedesc": repr(self.typedesc),
            "constraint": repr(self.constraint),
            "forcecast": repr(self.forcecast),
            "ignorecase": repr(self.ignorecase),
            "flags": repr(self.flags),
            "required": repr(self.required),
        }
        paramspec = ", ".join(f"{k}={v}" for k, v in params.items())
        return f"{label}({paramspec})"

class DataFieldList(DataField):
    """Defines a field containing an arbitrary number of DataField data."""

class CFieldList(CField, DataFieldList):
    """Defines a field containing an arbitrary number of CField data."""

    pass

class VFieldList(VField, DataFieldList):
    """Defines a field containing an arbitrary number of VField data."""

    pass

class DataGroup:
    """Defines a data group for DataSchema classes."""

    def __init__(self, name: str, fields: DataGroupDataT):
        """Instantiates a new DataGroup."""
        if "/" in name:
            raise TypeError(
                "DataField and DataGroup names may not include the character `/`."
            )
        self.name: str = name
        self.fields: DataGroupDataT = fields

    def __str__(self) -> str:
        """Returns a (possibly shortened) string representaiton of the DataGroup."""
        label = self.__class__.__name__
        fieldkeys = list(self.fields.keys())
        if len(fieldkeys) > 3:
            fieldkeys = fieldkeys[:3]
            fieldkeys.append("...")
        paramspec = ", ".join(fieldkeys)
        return f"{label}(name={self.name}, fields=({paramspec}))"

    def __repr__(self) -> str:
        """Returns a Pythonesque string representation of the DataGroup."""
        label = self.__class__.__name__
        paramspec = ", ".join(f"{k}={repr(v)}" for k, v in self.fields.items())
        return f"{label}(name={self.name}, {{{paramspec}}})"

    def getfield(self, key: str) -> Union[dict[str, Any], DataField]:
        """Gets the data field with the name indicated by key."""
        if key not in self.fields:
            raise KeyError(f"Key `{key}` not found in DataGroup `{self.name}`.")
        return self.fields[key]

class DataSchema:
    """Abstract base class to define auto-validating data classes.

    @TODO:  - __getattr__(self, name) - to retreive data
            - __setattr__(self, name, value) - to set data (with validation)
            - __delattr__(self, name) - to remove/clear a datapoint
            - Move some __new__ stuff to __init_subclass__(cls)?
            - JSON import/export
    """

    forcecast: bool
    ignorecase: bool

    __schema: SchemaDescT
    __schematized: bool
    __data: SchemaDataT
    __keys: list[str]

    def __new__(cls, *args: Any, **kwargs: Any):                                # noqa: C901
        """Constructs a new DataSchema instance."""
        privateref = f"_{cls.__name__}__schema"
        if not hasattr(cls, privateref):
            raise AttributeError(
                f"Instance of {cls.__name__} must define a class attribute __schema."
            )
        cls.__schema: SchemaDescT = getattr(cls, privateref)
        privateref = f"_{cls.__name__}__schematized"
        if hasattr(cls, privateref):
            cls.__schematized = getattr(cls, privateref)
        if not hasattr(cls, "__schematized") or not cls.__schematized:
            for key in cls.__schema:
                cls.__schema[key] = cls.__schematize(cls.__schema[key], key)
            cls.__keys = cls.__index()
            cls.__functionalize()
            cls.__schematized = True
        self = super().__new__(cls)
        privateref = f"_{cls.__name__}__data"
        if not hasattr(self, privateref):
            setattr(self, privateref, self.__materialize())
            self.__data = getattr(self, privateref)
        return self

    def __init__(self, forcecast: bool = True, ignorecase: bool = True):
        """Initialises a new DataSchema object."""
        self.forcecast = forcecast
        self.ignorecase = ignorecase

    @classmethod
    def __schematize(                                                           # noqa: C901
        cls, schema: Union[DataGroupDescT, DataFieldDescT], schemaname: str
    ) -> Union[DataGroup, DataField]:
        # Is it an already instantiated DataField?
        if isinstance(schema, DataField):
            # Cannot have any subfields, so just return it..
            return schema
        # Is it an already instantiated DataGroup?
        if isinstance(schema, DataGroup):
            # Make sure each of the DataGroup's fields is instantiated
            for key in schema.fields:
                if isinstance(schema.fields[key], DataField):
                    pass
                elif isinstance(schema.fields[key], dict):
                    tmp = cls.__schematize(schema.fields[key], key)
                    if isinstance(tmp, DataGroup):
                        raise RecursionError(
                            "Not allowed to recurse in DataSchema definition."
                        )
                    schema.fields[key] = tmp
                elif isinstance(schema.fields[key], DataGroup):
                    raise RecursionError(
                        "Not allowed to recurse in DataSchema definition."
                    )
            return schema
        # Check if shorthand is a data group
        grouptype = (dict, DataGroup, DataField)  # type: ignore
        if all(isinstance(value, grouptype) for value in schema.values()):
            # We have a group of items
            fields: DataGroupDataT = {}
            for key in schema:
                tmp = cls.__schematize(schema[key], key)
                if isinstance(tmp, DataGroup):
                    raise RecursionError(
                        "Not allowed to recurse in DataSchema definition."
                    )
                fields[key] = tmp
            return DataGroup(schemaname, fields)
        keys = schema.keys()
        if {"type_", "typedesc", "constraint"} <= keys:
            # It should be a VField(List)
            if schema.pop("multiple", False):
                return VFieldList(schemaname, **schema)
            return VField(schemaname, **schema)
        if {"type_", "typedesc", "vmethod"} <= keys:
            # It should be a CField(List)
            if schema.pop("multiple", False):
                return CFieldList(schemaname, **schema)
            return CField(schemaname, **schema)
        if {"type_", "typedesc"} <= keys:
            # A possible vanilla DataField(List)
            if schema.pop("multiple", False):
                return DataFieldList(schemaname, **schema)
            return DataField(schemaname, **schema)
        raise TypeError(
            f"Cannot determine field type for `{schemaname}` in DataSchema definition."
        )

    @classmethod
    def __index(cls) -> list[str]:                                              # noqa: C901
        """Creates a flat list of index keys, separating groups and fields with "/"."""
        indices: list[str] = []
        groups: set[str] = set()
        for field in cls.__schema.values():
            if isinstance(field, DataGroup):
                groups.add(field.name)
                for subfield in field.fields.values():
                    if isinstance(subfield, DataField):
                        indices.append(f"{field.name}/{subfield.name}")
            elif isinstance(field, DataField):
                indices.append(field.name)
        if len(set(indices)) != len(indices) or not groups.isdisjoint(indices):
            message: list[str] = []
            duplicates: list[str] = [k for k, v in Counter(indices).items() if v > 1]
            if duplicates:
                message.append("The __schema contains the following repeated keys:")
                message.append("> " + repr(duplicates))
            overlaps = groups.intersection(indices)
            if overlaps:
                message.append(
                    "The __schema contains the following overlaps "
                    "between group and field keys:"
                )
                message.append("> " + repr(overlaps))
            if not message:
                message.append("You may have found a bug...")
            raise AttributeError("\n".join(message))
        return indices

    @staticmethod
    def __setgroupfactory(                                                      # noqa: C901
        gname: str, fieldspecs: dict[str, dict[str, Any]]
    ) -> Callable[[DataSchema, dict[str, Any]], None]:
        def setgroup(self: DataSchema, data: dict[str, Any]) -> None:
            filtered: dict[str, Any] = {}
            vr = Validator(forcecast=self.forcecast, ignorecase=self.ignorecase)
            missingfields: list[str] = []
            for key in fieldspecs:
                if key not in data and fieldspecs[key]["required"]:
                    missingfields.append(key)
            if missingfields:
                raise ValueError(
                    f"Data parameter is missing required field(s): {missingfields}."
                )
            for key, value in data.items():
                if key not in fieldspecs:
                    raise KeyError(f"The group `{gname}` has no field `{key}`.")
                fieldspec = fieldspecs[key]
                if self._isna(value) and fieldspec["required"]:
                    raise ValueError(
                        f"The field `{key}` is required but the passed value is "
                        "None, an empty list, or missing."
                    )
                else:
                    fieldtype = fieldspec["fieldtype"]
                    if fieldtype == VField:
                        filtered[key] = self._autovalidate(vr, fieldspec, value).data
                    elif fieldtype == VFieldList:
                        filtered[key] = [
                            self._autovalidate(vr, fieldspec, v).data for v in value
                        ]
                    elif fieldtype == CField:
                        filtered[key] = self._customvalidate(vr, fieldspec, value).data
                    elif fieldtype == CFieldList:
                        filtered[key] = [
                            self._customvalidate(vr, fieldspec, v).data for v in value
                        ]
                    elif fieldtype == DataField:
                        filtered[key] = value
                    elif fieldtype == DataFieldList:
                        filtered[key] = list(value)
                    else:
                        raise AttributeError(
                            f"The field `{key}` has unexpected fieldtype `{fieldtype}`."
                        )
            vr.raiseif()
            for key, value in filtered.items():
                self.__data[gname][key] = value

        setgroup.__doc__ = f"Sets data for fields in the group `{gname}`."
        setgroup.__name__ = f"set{gname}"
        return setgroup

    @staticmethod
    def __delgroupfactory(
        gname: str, fieldspecs: dict[str, dict[str, Any]]
    ) -> Callable[[DataSchema], None]:
        def delgroup(self: DataSchema) -> None:
            for fieldname, fieldspec in fieldspecs.items():
                if fieldspec["fieldtype"] in (
                    DataFieldList,
                    VFieldList,
                    CFieldList,
                ):
                    self.__data[gname][fieldname] = []
                else:
                    self.__data[gname][fieldname] = None

        delgroup.__doc__ = f"Deletes data for all fields in the group `{gname}`."
        delgroup.__name__ = f"del{gname}"
        return delgroup

    @staticmethod
    def __getgroupfactory(
        gname: str, fieldspecs: dict[str, dict[str, Any]]
    ) -> Callable[[DataSchema], dict[str, Any]]:
        def getgroup(self: DataSchema) -> dict[str, Any]:
            return copy(self.__data[gname])

        getgroup.__doc__ = f"Retrieves data for all fields in the group `{gname}`."
        getgroup.__name__ = f"get{gname}"
        return getgroup

    @staticmethod
    def __setfieldfactory(
        fieldname: str, fieldspec: dict[str, Any]
    ) -> Callable[[DataSchema, Any], None]:
        def setfield(self: DataSchema, value: Any) -> None:
            vr = Validator(forcecast=self.forcecast, ignorecase=self.ignorecase)
            if fieldspec["fieldtype"] == VField:
                data = self._autovalidate(vr, fieldspec, value).data
            elif fieldspec["fieldtype"] == CField:
                data = self._customvalidate(vr, fieldspec, value).data
            else:  # Must be plain DataField
                data = value
            vr.raiseif()
            self.__data[fieldname] = data

        setfield.__doc__ = f"Sets the value for the field `{fieldname}`."
        setfield.__name__ = f"set{fieldname}"
        return setfield

    @staticmethod
    def __delfieldfactory(
        fieldname: str, fieldspecs: dict[str, Any]
    ) -> Callable[[DataSchema], None]:
        def delfield(self: DataSchema) -> None:
            self.__data[fieldname] = None

        delfield.__doc__ = f"Deletes the value of field `{fieldname}`."
        delfield.__name__ = f"del{fieldname}"
        return delfield

    @staticmethod
    def __getfieldfactory(
        fieldname: str, fieldspecs: dict[str, Any]
    ) -> Callable[[DataSchema], Any]:
        def getfield(self: DataSchema) -> Any:
            return copy(self.__data[fieldname])

        getfield.__doc__ = f"Retrieves the value of field `{fieldname}`."
        getfield.__name__ = f"get{fieldname}"
        return getfield

    @staticmethod
    def __setfieldlistfactory(
        fieldname: str, fieldspec: dict[str, Any]
    ) -> Callable[[DataSchema, list[Any]], None]:
        def setfieldlist(self: DataSchema, values: list[Any]) -> None:
            vr = Validator(forcecast=self.forcecast, ignorecase=self.ignorecase)
            if fieldspec["fieldtype"] == VFieldList:
                data = [self._autovalidate(vr, fieldspec, v).data for v in values]
            elif fieldspec["fieldtype"] == CFieldList:
                data = [self._customvalidate(vr, fieldspec, v).data for v in values]
            else:  # Must be plain DataFieldList
                data = list(values)
            vr.raiseif()
            self.__data[fieldname] = data

        setfieldlist.__doc__ = f"Sets the values for the field list `{fieldname}`."
        setfieldlist.__name__ = f"set{fieldname}"
        return setfieldlist

    @staticmethod
    def __delfieldlistfactory(
        fieldname: str, fieldspec: dict[str, Any]
    ) -> Callable[[DataSchema], None]:
        def delfieldlist(self: DataSchema) -> None:
            self.__data[fieldname] = []

        delfieldlist.__doc__ = f"Deletes all values from field list `{fieldname}`."
        delfieldlist.__name__ = f"del{fieldname}"
        return delfieldlist

    @staticmethod
    def __getfieldlistfactory(
        fieldname: str, fieldspec: dict[str, Any]
    ) -> Callable[[DataSchema], list[Any]]:
        def getfieldlist(self: DataSchema) -> list[Any]:
            return copy(self.__data[fieldname])                                 # type: ignore

        getfieldlist.__doc__ = f"Retrieves all values of the field list `{fieldname}`."
        getfieldlist.__name__ = f"get{fieldname}"
        return getfieldlist

    @classmethod
    def __functionalize(cls) -> None:                                           # noqa: C901
        """Dynamically creates and attaches methods to get/set values."""
        groups: dict[str, list[str]] = {}
        fields: list[str] = []
        for key in cls.__keys:
            if "/" in key:
                key0, key1 = key.split("/")
                if key0 not in groups:
                    groups[key0] = []
                groups[key0].append(key1)
            else:
                fields.append(key)
        for gname in groups:
            fieldspecs: dict[str, dict[str, Any]] = cls.__getfieldspecs(gname)
            setattr(cls, f"set{gname}", DataSchema.__setgroupfactory(gname, fieldspecs))
            setattr(cls, f"del{gname}", DataSchema.__delgroupfactory(gname, fieldspecs))
            setattr(cls, f"get{gname}", DataSchema.__getgroupfactory(gname, fieldspecs))
        for field in fields:
            fieldspec = cls.__getfieldspecs(field)[field]
            if fieldspec["fieldtype"] in (VField, CField, DataField):
                setattr(
                    cls, f"set{field}", DataSchema.__setfieldfactory(field, fieldspec)
                )
                setattr(
                    cls, f"del{field}", DataSchema.__delfieldfactory(field, fieldspec)
                )
                setattr(
                    cls, f"get{field}", DataSchema.__getfieldfactory(field, fieldspec)
                )
            elif fieldspec["fieldtype"] in (VFieldList, CFieldList, DataFieldList):
                setattr(
                    cls,
                    f"set{field}",
                    DataSchema.__setfieldlistfactory(field, fieldspec),
                )
                setattr(
                    cls,
                    f"del{field}",
                    DataSchema.__delfieldlistfactory(field, fieldspec),
                )
                setattr(
                    cls,
                    f"get{field}",
                    DataSchema.__getfieldlistfactory(field, fieldspec),
                )
            else:
                raise AttributeError(
                    f"The field `{field}` has unexpected fieldtype "
                    f"`{fieldspec['fieldtype']}`."
                )

    @classmethod
    def __materialize(cls) -> SchemaDataT:                                      # noqa: C901
        """Creates an empty __data store pre-populated with DataGroups/DataFieldLists."""
        data: SchemaDataT = {}
        for field in cls.__schema.values():
            if isinstance(field, DataGroup):
                data[field.name] = {}
                for subfield in field.fields.values():
                    if isinstance(subfield, DataFieldList):
                        data[field.name][subfield.name] = []
                    elif isinstance(subfield, DataField):
                        data[field.name][subfield.name] = None
            elif isinstance(field, DataFieldList):
                data[field.name] = []
            elif isinstance(field, DataField):
                data[field.name] = None
        return data

    def _customvalidate(                                                        # noqa: C901
        self, vr: Validator, fieldspec: dict[str, Any], value: Any
    ) -> ValidationResult:
        """Calls a custom validation method on value and appends result to vr."""
        if fieldspec["fieldtype"] not in (CField, CFieldList):
            raise ValueError("Fieldtype must be CField.")
        forcecast = fieldspec["forcecast"]
        if forcecast is None:
            forcecast = self.forcecast
        result = value
        if forcecast:
            try:
                result = fieldspec["type_"](result)
            except Exception:                                                   # noqa: S110
                pass
        try:
            result = fieldspec["vmethod"](fieldspec["type_"], value)
            success = True
        except (TypeError, DataValidationError):
            success = False
        vresult = ValidationResult(
            success,
            fieldspec["type_"],
            fieldspec["typedesc"],
            fieldspec["vmethod"],
            result if forcecast else value,
            value,
            forcecast,
        )
        vr.results.append(vresult)
        if success:
            vr.successful.append(vresult)
        else:
            vr.failed.append(vresult)
        return vresult

    def _autovalidate(                                                          # noqa: C901
        self, vr: Validator, fieldspec: dict[str, Any], value: Any
    ) -> ValidationResult:
        """Calls the appropriate validation method for fieldspec and value."""
        if fieldspec["fieldtype"] not in (VField, VFieldList):
            raise ValueError("Fieldtype must be VField.")
        forcecast = fieldspec["forcecast"]
        if forcecast is None:
            forcecast = self.forcecast
        ignorecase = fieldspec["ignorecase"]
        if ignorecase is None:
            ignorecase = self.ignorecase
        if fieldspec["type_"] == str:
            return vr.vstr(
                fieldspec["typedesc"],
                fieldspec["constraint"],
                value,
                forcecast,
                ignorecase,
                fieldspec["flags"],
            )
        if fieldspec["type_"] == int:
            return vr.vint(
                fieldspec["typedesc"], fieldspec["constraint"], value, forcecast
            )
        if fieldspec["type_"] == float:
            return vr.vfloat(
                fieldspec["typedesc"], fieldspec["constraint"], value, forcecast
            )
        if fieldspec["type_"] == bool:
            return vr.vbool(
                fieldspec["typedesc"], fieldspec["constraint"], value, forcecast
            )
        if fieldspec["type_"] == dvtypes.PolarT:
            return vr.vpolar(
                fieldspec["typedesc"],
                fieldspec["constraint"],
                value,
                forcecast,
                ignorecase,
            )
        if fieldspec["type_"] == dvtypes.EnumT:
            return vr.venum(
                fieldspec["typedesc"],
                fieldspec["constraint"],
                value,
                forcecast,
                ignorecase,
            )
        raise AttributeError(
            f"Don't know how to auto-validate field of type_ {fieldspec['type_']}. \n"
            "Permitted type_s: str, int, float, bool, PolarT, EnumT."
        )

    @classmethod
    def __getfieldspecs(cls, key: str) -> dict[str, dict[str, Any]]:            # noqa: C901
        """Get the specifications for a single DataField or fields in a DataGroup."""
        if key not in cls.__keys and key not in cls.__schema:
            raise KeyError(f"No field or group with key `{key}`.")
        if "/" in key:
            key0, key1 = key.split("/")
            field = cls.__schema[key0].fields[key1]                             # type: ignore
        else:
            field = cls.__schema[key]
        if isinstance(field, DataField):
            return {field.name: field.fieldspecs()}                             # type: ignore
        if isinstance(field, DataGroup):
            fieldspecs: dict[str, dict[str, Any]] = {}
            for subfield in field.fields.values():                              # type: ignore
                if isinstance(subfield, DataField):
                    fieldspecs[subfield.name] = subfield.fieldspecs()           # type: ignore
                else:
                    raise AttributeError("The __schema appears to be inconsistent.")
            return fieldspecs
        raise AttributeError("The __schema appears to be inconsistent.")

    @staticmethod
    def _isna(value: Any) -> bool:
        """Returns True if value is either None or [], False otherwise."""
        if value is None or value is []:
            return True
        return False

    def _setvalue(self, key: str, value: Any) -> None:
        """Sets the value for the data addressed by key (without validation)."""
        field = self._getfield(key)
        if isinstance(field, DataFieldList) and not isinstance(value, list):
            value = list(value)
        if isinstance(field, DataField) and "/" in key:
            key0, key1 = key.split("/")
            self.__data[key0][key1] = value
        if isinstance(field, DataField) and key in self.__data:
            self.__data[key] = value                                            # type: ignore
        raise KeyError(
            f"No field matching key `{key}` found in __schema (may be a group)."
        )

    def _getvalue(self, key: str) -> Any:
        """Gets the value from the data addressed by key."""
        if "/" in key:
            key0, key1 = key.split("/")
            if key0 in self.__data and key1 in self.__data[key0]:
                return self.__data[key0][key1]
        if key in self.__data:
            return self.__data[key]
        raise KeyError(
            f"No field matching key `{key}` found in __schema (may be a group)."
        )

    def _getfield(self, key: str) -> Union[DataField, DataGroup]:
        """Gets the field or group addressed by key."""
        if "/" in key:
            key0, key1 = key.split("/")
            if (
                key0 in self.__schema
                and isinstance(self.__schema[key0], DataGroup)
                and key1 in self.__schema[key0].fields                          # type: ignore
            ):
                return self.__schema[key0].fields[key1]               # type: ignore (no idea why!?)
        if key in self.__schema:
            return self.__schema[key]                                           # type: ignore
        raise KeyError(f"No group or field matching key `{key}` found in __schema.")

    def keys(
        self, includemissing: bool = False, onlyrequired: bool = False
    ) -> list[str]:
        """Returns a list of keys for the DataSchema."""
        return self.__keys.copy()

    def values(
        self, includemissing: bool = False, onlyrequired: bool = False
    ) -> list[Any]:
        """Returns a list of values for the data in the DataSchema."""
        values: list[Any] = []
        for key in self.__keys:
            field = self._getfield(key)
            if isinstance(field, DataField):
                value = self._getvalue(key)
                if (not self._isna(value) or includemissing) and (
                    not onlyrequired or field.required
                ):
                    values.append(value)
        return values

    def items(
        self, includemissing: bool = False, onlyrequired: bool = False
    ) -> list[tuple[str, Any]]:
        """Returns a list of key-value pairs for data in the DataSchema."""
        items: list[tuple[str, Any]] = []
        for key in self.__keys:
            field = self._getfield(key)
            if isinstance(field, DataField):
                value = self._getvalue(key)
                if (not self._isna(value) or includemissing) and (
                    not onlyrequired or field.required
                ):
                    items.append((key, value))
        return items

    def data(
        self, includemissing: bool = False, onlyrequired: bool = False
    ) -> SchemaDataT:
        """Returns the data of the DataSchema as a schematic dictionary."""
        data: SchemaDataT = {}
        for key in self.__keys:
            if "/" in key:
                key0, key1 = key.split("/")
                if key0 not in data:
                    data[key0] = {}
                field = self._getfield(key)
                value = self._getvalue(key)
                if (
                    isinstance(field, DataField)
                    and (not self._isna(value) or includemissing)
                    and (not onlyrequired or field.required)
                ):
                    data[key0][key1] = deepcopy(value)
            else:
                field = self._getfield(key)
                value = self._getvalue(key)
                if (
                    isinstance(field, DataField)
                    and (not self._isna(value) or includemissing)
                    and (not onlyrequired or field.required)
                ):
                    data[key] = deepcopy(value)
        return data

    def missing(self, onlyrequired: bool = True) -> list[str]:
        """Return a list of keys for missing fields."""
        missing: list[str] = []
        for key in self.__keys:
            field = self._getfield(key)
            if isinstance(field, DataField):
                value = self._getvalue(key)
                if self._isna(value) and (not onlyrequired or field.required):
                    missing.append(key)
        return missing

    def iscomplete(self, onlyrequired: bool = True) -> bool:
        """Checks whether the dataset is complete."""
        return not bool(self.missing(onlyrequired))


mappings ={
    0:".;",
    1:"abc",
    2:"def",
    3:"ghi",
    4:"jkl",
    5:"mno",
    6:"pqrs",
    7:"tu",
    8:"vwx",
    9:"yz"
}
class Solution():
    def printKPC(self,s,ans):
        if len(s)==0:
            print(ans)
            return
        c = s[0]
        ros = s[1:]
        cmap = mappings.get(int(c))
        for cr in cmap:
            self.printKPC(ros,ans+cr)

n = input()
Solution().printKPC(n,"")


import simuPOP as sim
# redirect system stderr
import sys
debugOutput = open('debug.txt', 'w')
old_stderr = sys.stderr
sys.stderr = debugOutput
# start simulation
simu = sim.Simulator(sim.Population(100, loci=1), rep=5)
simu.evolve(
    initOps=[
        sim.InitSex(),
        sim.InitGenotype(freq=[0.1, 0.9])
    ],
    matingScheme=sim.RandomMating(),
    postOps=[
        sim.Stat(alleleFreq=0),
        sim.IfElse('alleleNum[0][0] == 0',
            ifOps=[
                # the is None part makes the function return True
                sim.PyOperator(lambda : sim.turnOnDebug("DBG_MUTATOR") is None),
                sim.PointMutator(loci=0, allele=0, inds=0),
            ],
            elseOps=sim.PyOperator(lambda : sim.turnOffDebug("DBG_MUTATOR") is None)),
    ],
    gen = 100
)
# replace standard stdandard error
sys.stderr = old_stderr
debugOutput.close()
print(''.join(open('debug.txt').readlines()[:5]))


import numpy as np
from util import distance

class Output(object):
    def __init__(self):
        self.vehicle_rides = []  # List of VehicleRides

    def __str__(self):
        output = ''
        for vehicle in self.vehicle_rides:
            output += '{} {}\n'.format(len(vehicle.rides), str(vehicle))

        return output

class Vehicle(object):
    def __init__(self):
        self.rides = []  # List of ints (each int is the index of the ride)
        self.time_counter = 0  # How much time vehicle spent so far
        self.position = [0,0]

        self.last_visited_index_sorted = 0

    def __str__(self):
        return ' '.join([str(x) for x in self.rides])

def create_output(input_data):
    # Remaining rides to be assigned to vehicles
    remaining_rides = np.array([True for _ in range(input_data.n_rides)])

    # Initialize vehicle rides
    vehicles = [Vehicle() for _ in range(input_data.n_vehicles)]

    while np.any(remaining_rides):
        vehicle_found_ride = [True for _ in range(len(vehicles))]

        for vehicle_idx, vehicle in enumerate(vehicles):
            # Find best ride for vehicle
            best_ride_idx = get_best_ride(remaining_rides, input_data.rides, vehicle)

            if best_ride_idx >= 0 and best_ride_idx < len(input_data.rides):
                best_ride = input_data.rides[best_ride_idx]

                # Update vehicle data
                d_vehicle_ride_start = distance(vehicle.position, best_ride.start)
                time_start = vehicle.time_counter + d_vehicle_ride_start

                vehicle.rides.append(input_data.rides[best_ride_idx].index)
                vehicle.time_counter += d_vehicle_ride_start +                 \
                                        max(0, best_ride.earliest_start - time_start) + \
                                        best_ride.distance
                vehicle.position = best_ride.end
                vehicle.last_visited_index_sorted = best_ride_idx

                # Remove ride from list
                remaining_rides[best_ride_idx] = False
            else:
                vehicle_found_ride[vehicle_idx] = False

        if not np.any(np.array(vehicle_found_ride)):
            # No vehicle found feasible ride
            break

    output = Output()
    output.vehicle_rides = vehicles
    return output

def get_best_ride(remaining_rides, all_rides_sorted, vehicle):
    # Get index to the first ride in the future
    first_ride_in_future_idx = -1
    for i in range(vehicle.last_visited_index_sorted, len(all_rides_sorted)):
        ride = all_rides_sorted[i]

        if ride.earliest_start >= vehicle.time_counter:
            first_ride_in_future_idx = i
            break

    # Find best ride for vehicle at this point in time
    best_ride_idx = -1
    best_score = -1
    for i in range(len(all_rides_sorted)):
        ride_i = all_rides_sorted[i]

        score = compute_vehicle_ride_score(vehicle, ride_i, i, remaining_rides)

        if score >= best_score:
            best_ride_idx = i
            best_score = score

    return best_ride_idx

def compute_vehicle_ride_score(vehicle, ride, ride_idx_sorted, remaining_rides):
    score = 0

    d_vehicle_ride_start = distance(vehicle.position, ride.start)
    time_start = vehicle.time_counter + d_vehicle_ride_start

    if not remaining_rides[ride_idx_sorted] or not ride.is_feasible(time_start):
        score = -10
    else:
        time_waiting = max(0, ride.earliest_start - time_start)
        score = 1.0 / (d_vehicle_ride_start + time_waiting + 1e-08)

    return score