#!/usr/bin/python
# -*- coding: utf-8 -*-
# createlist.py
# Module of musiclist.py
# Functions that create files in several formats.

import os
import sys
import locale
import sqlite3
import csv
import json
import xml.etree.ElementTree as ET

EXT_LIST = ['.MP3', '.M4A']  # List of extensions allowed (in upper case): MP3, ACC
dict_artists = {}            # Music information loaded in memory

def load_music_list(music_dir):
    """
    Load the music list in memory 'dict_artists' from the music directory.

    Example of directory used:
      music/
      │
      ├── artist_1
      │   ├── album_1_1/
      │   │   ├── track_1_1_1
      │   │   ├── track_1_1_2
      │   │   └── track_1_1_3
      │   └── album_1_2/
      │       ├── track_1_2_1
      │       └── track_1_2_2
      ├── artist_2/
      │   ├── album_2_1/
      │   │   ├── track_2_1_1
      │   │   └── track_2_1_2
      │   │
      │   └── album_2_2/
      │       ├── track_2_2_1
      │       └── track_2_2_2
      └── artist_3/
          └── lbum_3_1/
              ├── track_3_1_1
              └── track_3_1_2

    Example of the structure created in memory:
      dict_artists =
        {'artist-1': {'album-1_1': ['track-1_1_1', 'track-1_1_2', 'track-1_1_3'] ,
                      'album-1_2': ['track-1_2_1', 'track-1_2_2']},
        'artist-2': {'album-2_1': ['track-2_1_1', 'track-2_1_2'],
                      'album-2_2': ['track-2_2_1', 'track-2_2_2']},
        'artist-3': {'album-3_1': ['track-3_1_1', 'track-3_1_2']}
        }
    """

    global dict_artists

    print('Loading music information from "' + music_dir + '"...')
    dict_artists.clear()
    # Artists loop starts, filter only directories
    artists = filter(lambda x: os.path.isdir(os.path.join(music_dir, x)), os.listdir(music_dir))
    for artist in artists:
        dict_albums = {}
        artist_dir = music_dir + os.sep + artist
        # Albums loop starts, filter only directories
        albums = filter(lambda x: os.path.isdir(os.path.join(artist_dir, x)), os.listdir(artist_dir))
        for album in albums:
            album_dir = artist_dir + os.sep + album
            list_tracks = []
            # Tracks loop starts, filter only files
            tracks = filter(lambda x: os.path.isfile(os.path.join(album_dir, x)), os.listdir(album_dir))
            for track in tracks:
                fileext = os.path.splitext(track)[1].upper()
                if fileext in EXT_LIST:
                    list_tracks.append(track)
            # Tracks loop ends
            dict_albums[album] = list_tracks
            dict_artists[artist] = dict_albums
        # Albums loop ends
    # Artists loop ends
    print('Music information loaded')

    return

def write_file(file_name, data):
    """
    Create and write a text file.
    """
    f = open(file_name, 'w', encoding='utf-8')
    for item in data:
        f.write(item + '\n')
    f.close()
    return

def write_json_file(json_name, data):
    """
    Create and write an JSON file.
    """
    with open(json_name, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, indent=2, sort_keys=True)
    return

def write_xml_file(xml_name, data):
    """
    Create and write an XML file.
    """
    tree = ET.ElementTree(data)
    tree.write(xml_name, xml_declaration=True, encoding='utf-8')
    return

def write_html_file(html_name, data):
    """
    Create and write an HTML file.
    """
    with open(html_name, 'wb') as f:
        f.write('<!doctype html>'.encode('utf8'))
        tree = ET.ElementTree(data)
        tree.write(f, 'utf-8')
    return

def print_list():
    """
    Show in the screen the content of the Mucic list in 'dict_artists'.
    """
    global dict_artists

    print('\nMUSIC LIST')
    print('----------')
    for k_artist in sorted(dict_artists.keys()):
        for  k_album in sorted(dict_artists[k_artist].keys()):
            print('ARTIST: ', k_artist.encode('utf-8').decode(sys.stdout.encoding))
            print('ALBUM: ', k_album.encode('utf-8').decode(sys.stdout.encoding))
            print('TRACKS:')
            for track in sorted(dict_artists[k_artist][k_album]):
                print('    ', track.encode('utf-8').decode(sys.stdout.encoding))
            print('')

    return

def file_list(file_name):
    """
    Create a text file with the content of the Mucic list in 'dict_artists'.
    """
    global dict_artists
    output = []

    print('Creating file "' + file_name + '"...')
    output.append("MUSIC LIST")
    output.append('----------\n')
    for k_artist in sorted(dict_artists.keys()):
        for  k_album in sorted(dict_artists[k_artist].keys()):
            output.append('ARTIST: ' + k_artist)
            output.append('ALBUM: ' + k_album)
            output.append('TRACKS:')
            for track in sorted(dict_artists[k_artist][k_album]):
                output.append("        " + track)
            output.append("")

    write_file(file_name, output)
    print('File created')

    return

def db_list(db_name):
    """
    Create a SQLite database with the content of the Mucic list in 'dict_artists'.
    Table format: artist text, album text, track text
    """
    global dict_artists

    print('Creating Database "' + db_name + '"...')

    # if DB exists then remove
    if os.path.exists(db_name):
        os.remove(db_name)

    # Create and connect to DB
    conn = sqlite3.connect(db_name)
    c = conn.cursor()
    c.execute('PRAGMA encoding = "UTF-8";')

    # Create table
    c.execute('''CREATE TABLE music
              (artist text, album text, track text)''')

    # Create index
    c.execute('''CREATE INDEX idx_music
                ON music (artist, album)''')

    # Insert rows of data
    for k_artist in sorted(dict_artists.keys()):
        for  k_album in sorted(dict_artists[k_artist].keys()):
            for track in sorted(dict_artists[k_artist][k_album]):
                row = [k_artist, k_album, track]
                c.execute("INSERT INTO music VALUES (?, ?, ?)", row)

    # Save (commit) the changes
    conn.commit()

    conn.close()
    print('Database created')

    return

def csv_list(csv_name):
    """
    Create a CSV file with the content of the Mucic list in 'dict_artists'.
    CSV format: artist, album, track
    """
    global dict_artists

    print('Creating CSV file "' + csv_name + '"...')
    with open(csv_name, 'w', encoding='utf-8', newline='') as csvfile:
        spamwriter = csv.writer(csvfile)
        for k_artist in sorted(dict_artists.keys()):
            for  k_album in sorted(dict_artists[k_artist].keys()):
                for track in sorted(dict_artists[k_artist][k_album]):
                    spamwriter.writerow([k_artist, k_album, track])
    print('CSV file created')

    return

def json_list_music(json_name):
    """
    Create a JSON (Music List) file with the content of the Mucic list in 'dict_artists'.
    JSON (Music List) format:
      {
          "format": "music-list",
          "music": [
              {
                  "artists": [
                      {
                          "name": "author-1",
                          "albums": [
                              {
                                  "title": "album-1_1",
                                  "tracks": [
                                      {
                                          "title": "track_1_1_1",
                                          "title": "track_1_1_2"
                                      }
                                  ]
                              }
                          ]
                      }
                  ]
              }
          ]
      }
    """
    global dict_artists

    print('Creating JSON (Music List) file "' + json_name + '"...')
    data = {}
    data['format'] = "music-list"
    data['music'] = []

    artists = {}
    artists['artists'] = []
    for k_artist in sorted(dict_artists.keys()):
        albums = {}
        albums['albums'] = []
        for  k_album in sorted(dict_artists[k_artist].keys()):
            tracks = {}
            tracks['tracks'] = []
            for track in sorted(dict_artists[k_artist][k_album]):
                tracks['tracks'].append({'title': track})
            albums['albums'].append({'title': k_album, 'tracks': tracks['tracks']})
        artists['artists'].append({'name': k_artist, 'albums': albums['albums']})
        data['music'].append({'artists': artists['artists']})

    write_json_file(json_name, data)
    print('JSON (Music List) file created')

    return

def json_list_tracks(json_name):
    """
    Create a JSON (Tracks List) file with the content of the Mucic list in 'dict_artists'.
    JSON (Tracks List) format:
      {
          "format": "tracks-list"
          "music": [
              {
                  "artist": "author-1",
                  "album": "album-1_1",
                  "tracks": "track_1_1_1"
              },
              {
                  "artist": "author-1",
                  "album": "album-1_1",
                  "tracks": "track_1_1_2"
              }
          ]
      }
    """
    global dict_artists

    print('Creating JSON (Tracks List) file "' + json_name + '"...')
    data = {}
    data['format'] = "tracks-list"
    data['music'] = []
    for k_artist in sorted(dict_artists.keys()):
        for  k_album in sorted(dict_artists[k_artist].keys()):
            for track in sorted(dict_artists[k_artist][k_album]):
                data['music'].append({
                    'artist': k_artist,
                    'album': k_album,
                    'track': track})

    write_json_file(json_name, data)
    print('JSON (Tracks List) file created')

    return

def xml_list_music(xml_name):
    """
    Create a XML (Music List) file with the content of the Mucic list in 'dict_artists'.
    XML (Music List) format:
      <music format="music-list">
          <artist name="author-1">
              <album title="album-1_1">
                  <track>track_1_1_1</track>
                  <track>track_1_1_2</track>
              </album>
          </artist>
      </music>
    """
    global dict_artists

    print('Creating (Music List) XML file "' + xml_name + '"...')
    music = ET.Element("music", {'format': 'music-list'})
    for k_artist in sorted(dict_artists.keys()):
        artist = ET.SubElement(music, "artist", {'name': k_artist})
        for  k_album in sorted(dict_artists[k_artist].keys()):
            album = ET.SubElement(artist, "album", {'title': k_album})
            for track in sorted(dict_artists[k_artist][k_album]):
                ET.SubElement(album, "track").text = track

    write_xml_file(xml_name, music)
    print('XML (Music List) file created')

    return

def xml_list_tracks(xml_name):
    """
    Create a XML (Tracks List) file with the content of the Mucic list in 'dict_artists'.
    XML (Tracks List) format:
      <music format="tracks-list">
          <item>
              <artist>"author-1"</artist>
              <album>"album-1_1"</album>
              <track>"track_1_1_1"</track>
          </item>
          <item>
              <artist>"author-1"</artist>
              <album>"album-1_1"</album>
              <track>"track_1_1_2"</track>
          </item>
      </music>
    """
    global dict_artists

    print('Creating XML (Tracks List) file "' + xml_name + '"...')
    music = ET.Element("music", {'format': 'tracks-list'})
    for k_artist in sorted(dict_artists.keys()):
        for  k_album in sorted(dict_artists[k_artist].keys()):
            for track in sorted(dict_artists[k_artist][k_album]):
                item = ET.SubElement(music, "item")
                ET.SubElement(item, "artist").text = k_artist
                ET.SubElement(item, "album").text = k_album
                ET.SubElement(item, "track").text = track

    write_xml_file(xml_name, music)
    print('XML (Tracks List) file created')

    return

def html_list(html_name):
    """
    Create a HTML file with the content of the Mucic list in 'dict_artists'.
    HTML format:

          <title>MUSIC</title>

MUSIC LIST

author-1

album-1_1

track_1_1_1

track_1_1_2

    """
    global dict_artists

    print('Creating HTML file "' + html_name + '"...')
    page = ET.Element('html')
    head = ET.SubElement(page, 'head')
    ET.SubElement(head, 'meta', {'charset': "UTF-8"})
    ET.SubElement(head, 'title').text = 'MUSIC LIST'
    body = ET.SubElement(page, 'body')
    ET.SubElement(body, 'h1').text = 'MUSIC LIST'

    for k_artist in sorted(dict_artists.keys()):
        ET.SubElement(body, 'h2').text = k_artist
        for  k_album in sorted(dict_artists[k_artist].keys()):
            ET.SubElement(body, 'h3').text = k_album
            ul = ET.SubElement(body, 'ul')
            for track in sorted(dict_artists[k_artist][k_album]):
                ET.SubElement(ul, "li").text = track

    write_html_file(html_name, page)
    print('HTML file created')

    return


# Create a class of pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.

class animals:
    type ="mammal"

class pets(animals):
    color = "white"

class dog(pets):
    @staticmethod
    def bark():
        print("i am barking")

d = dog()
d.bark()


import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QDialog, QVBoxLayout, QLineEdit, QPushButton, QTableWidgetItem, \
    QErrorMessage, QTableWidget, QCheckBox, QTableView, QMessageBox, QToolBar, QAbstractItemView, QHeaderView, \
    QDataWidgetMapper, QStyledItemDelegate
from PySide6.QtCore import QFile, Qt, QRegularExpression, Slot
from PySide6.QtGui import QRegularExpressionValidator, QIntValidator, QDoubleValidator, QKeySequence, QStandardItemModel
from ui_mainwindow import Ui_MainWindow
from PySide6 import QtCore, QtWidgets, QtGui
from PySide6.QtSql import QSqlRelation, QSqlRelationalTableModel, QSqlTableModel, QSqlRelationalDelegate, QSqlQuery
import createddb

from smart.design.ui_main_wisget import Ui_Form
from smart.design.ui_CategoryForm import Ui_CategoryForm
from smart.design.ui_SubCategoryForm import Ui_SubCategoryForm
from smart.design.ui_EquipmentForm import Ui_EquipmentForm
import config
from decimal import Decimal

class CategoryWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(CategoryWidget, self).__init__(parent)
        self.ui_category = Ui_CategoryForm()
        self.ui_category.setupUi(self)
        self.setWindowTitle('Категория')
        self.init_model()
        self.q = QSqlQuery()
        self.ui_category.table_category.setModel(self.model)

        self.ui_category.table_category.setSortingEnabled(True)

        self.setHeader()

        self.setColumnHidden()

        self.settings_table()

        self.ui_category.pushButton_save_category.clicked.connect(self.setCategory)

    def init_model(self):
        self.model = QSqlTableModel(self)
        self.model.setTable("categoryequipment")
        self.model.select()

    def setHeader(self):
        self.model.setHeaderData(self.model.fieldIndex("id"), Qt.Horizontal, self.tr("ID"))
        self.model.setHeaderData(self.model.fieldIndex("title"), Qt.Horizontal, self.tr("Название"))
        self.model.setHeaderData(self.model.fieldIndex("description"), Qt.Horizontal, self.tr("Описание"))
        self.model.setHeaderData(self.model.fieldIndex("time_created"), Qt.Horizontal, self.tr("Дата создания"))
        self.model.setHeaderData(self.model.fieldIndex("time_updated"), Qt.Horizontal, self.tr("Дата обновления"))

    def setColumnHidden(self):
        self.ui_category.table_category.setColumnHidden(self.model.fieldIndex("id"), True)
        self.ui_category.table_category.setColumnHidden(self.model.fieldIndex("time_created"), True)
        self.ui_category.table_category.setColumnHidden(self.model.fieldIndex("time_updated"), True)

    def settings_table(self):
        self.ui_category.table_category.setColumnHidden(self.model.fieldIndex("id"), True)
        self.ui_category.table_category.setSelectionMode(QAbstractItemView.SingleSelection)
        self.ui_category.table_category.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.ui_category.table_category.resizeColumnsToContents()
        self.ui_category.table_category.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def setCategory(self):
        title = self.ui_category.lineEdit_title_category.text()
        description = self.ui_category.lineEdit_desc_category.text()
        self.q.prepare("INSERT INTO categoryequipment (title, description) "
                       "VALUES (?, ?)")
        self.q.addBindValue(title)
        self.q.addBindValue(description)
        if self.q.exec():
            self.ui_category.lineEdit_title_category.setText('')
            self.ui_category.lineEdit_desc_category.setText('')
        self.model.select()

class SubCategoryWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(SubCategoryWidget, self).__init__(parent)
        self.ui_sub_category = Ui_SubCategoryForm()
        self.ui_sub_category.setupUi(self)

        self.setWindowTitle('Подкатегория')
        self.ui_sub_category.table_sub_category.setSortingEnabled(True)

        self.init_model()

        self.q = QSqlQuery()

        self.ui_sub_category.table_sub_category.setModel(self.model)
        self.ui_sub_category.table_sub_category.setItemDelegate(
            QSqlRelationalDelegate(self.ui_sub_category.table_sub_category))

        self.setHeader()
        self.settings_table()
        self.ui_sub_category.pushButton_sub_category.clicked.connect(self.setSubCategory)

        self.qwer()

    def init_model(self):
        self.model = QSqlRelationalTableModel(self.ui_sub_category.table_sub_category)
        self.model.setTable("subcategoryequipment")

        self.category_idx = self.model.fieldIndex("categoryequipmentid")
        self.model.setRelation(self.category_idx, QSqlRelation('categoryequipment', 'id', 'title'))

        self.model.setSort(self.category_idx, QtCore.Qt.SortOrder.AscendingOrder)
        self.model.select()

    def setHeader(self):
        self.model.setHeaderData(self.model.fieldIndex("id"), Qt.Horizontal, self.tr("ID"))
        self.model.setHeaderData(self.model.fieldIndex("title"), Qt.Horizontal, self.tr("Название"))
        self.model.setHeaderData(self.model.fieldIndex("description"), Qt.Horizontal, self.tr("Описание"))
        self.model.setHeaderData(self.model.fieldIndex("time_created"), Qt.Horizontal, self.tr("Дата создания"))
        self.model.setHeaderData(self.model.fieldIndex("time_updated"), Qt.Horizontal, self.tr("Дата обновления"))
        self.model.setHeaderData(self.category_idx, Qt.Horizontal, self.tr("Категория"))

    def settings_table(self):
        self.ui_sub_category.table_sub_category.setColumnHidden(self.model.fieldIndex("id"), True)
        self.ui_sub_category.table_sub_category.setColumnHidden(self.model.fieldIndex("time_created"), True)
        self.ui_sub_category.table_sub_category.setColumnHidden(self.model.fieldIndex("time_updated"), True)
        self.ui_sub_category.table_sub_category.setSelectionMode(QAbstractItemView.SingleSelection)
        self.ui_sub_category.table_sub_category.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.ui_sub_category.table_sub_category.resizeColumnsToContents()
        self.ui_sub_category.table_sub_category.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def qwer(self):
        self.model_combo = QSqlTableModel()
        self.model_combo.setTable('categoryequipment')

        column = self.model_combo.fieldIndex('title')

        self.model_combo.setSort(column, QtCore.Qt.SortOrder.AscendingOrder)
        self.model_combo.select()

        self.ui_sub_category.lineEdit_categoryid_sub_category.setModel(self.model_combo)
        self.ui_sub_category.lineEdit_categoryid_sub_category.setModelColumn(column)

    def setSubCategory(self):
        title = self.ui_sub_category.lineEdit_title_sub_category.text()
        description = self.ui_sub_category.lineEdit_desc_sub_category.text()
        categoryequipmentid = self.model_combo.index(
            self.ui_sub_category.lineEdit_categoryid_sub_category.currentIndex(),
            self.model_combo.fieldIndex('id')).data()
        self.q.prepare("INSERT INTO subcategoryequipment (title, description, categoryequipmentid) "
                       "VALUES (?, ?, ?)")
        self.q.addBindValue(title)
        self.q.addBindValue(description)
        self.q.addBindValue(categoryequipmentid)
        if self.q.exec():
            self.ui_sub_category.lineEdit_title_sub_category.setText('')
            self.ui_sub_category.lineEdit_desc_sub_category.setText('')
        self.model.select()

class EquipmentWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(EquipmentWidget, self).__init__(parent)
        self.ui_equipment = Ui_EquipmentForm()
        self.ui_equipment.setupUi(self)
        self.setWindowTitle('Список оборудования')

        self.init_model()
        self.ui_equipment.table_equipment.setSortingEnabled(True)
        self.ui_equipment.table_equipment.setModel(self.model)
        self.ui_equipment.table_equipment.setItemDelegate(
            QSqlRelationalDelegate(self.ui_equipment.table_equipment)
        )
        self.q = QSqlQuery()
        self.setHeader()
        self.settings_table()

        self.ui_equipment.pushButton_save_equipment.clicked.connect(self.setEquipment)

        self.qwer()

    def init_model(self):
        self.model = QSqlRelationalTableModel(self.ui_equipment.table_equipment)
        self.model.setTable('equipment')

        self.subcategory_idx = self.model.fieldIndex('subcategoryequipmentid')

        self.model.setRelation(self.subcategory_idx, QSqlRelation('subcategoryequipment', 'id', 'title'))
        self.model.select()

    def setHeader(self):
        self.model.setHeaderData(self.model.fieldIndex("id"), Qt.Horizontal, self.tr("ID"))
        self.model.setHeaderData(self.model.fieldIndex("title"), Qt.Horizontal, self.tr("Название"))
        self.model.setHeaderData(self.model.fieldIndex("pcs"), Qt.Horizontal, self.tr("Кол-во"))
        self.model.setHeaderData(self.model.fieldIndex("price"), Qt.Horizontal, self.tr("Цена"))
        self.model.setHeaderData(self.model.fieldIndex("time_created"), Qt.Horizontal, self.tr("Дата создания"))
        self.model.setHeaderData(self.model.fieldIndex("time_updated"), Qt.Horizontal, self.tr("Дата обновления"))
        self.model.setHeaderData(self.subcategory_idx, Qt.Horizontal, self.tr("Категория"))

    def settings_table(self):
        self.ui_equipment.table_equipment.setColumnHidden(self.model.fieldIndex("id"), True)
        self.ui_equipment.table_equipment.setColumnHidden(self.model.fieldIndex("time_created"), True)
        self.ui_equipment.table_equipment.setColumnHidden(self.model.fieldIndex("time_updated"), True)
        self.ui_equipment.table_equipment.setSelectionMode(QAbstractItemView.SingleSelection)
        self.ui_equipment.table_equipment.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.ui_equipment.table_equipment.resizeColumnsToContents()
        self.ui_equipment.table_equipment.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def qwer(self):
        self.model_combo = QSqlTableModel()
        self.model_combo.setTable('subcategoryequipment')

        column = self.model_combo.fieldIndex('title')
        self.model_combo.setSort(column, QtCore.Qt.SortOrder.AscendingOrder)
        self.model_combo.select()

        self.ui_equipment.comboBox_subcategory_equipment.setModel(self.model_combo)
        self.ui_equipment.comboBox_subcategory_equipment.setModelColumn(column)

    def setEquipment(self):
        title = self.ui_equipment.lineEdit_title_equipment.text()
        pcs = self.ui_equipment.lineEdit_pcs_equipment.text()
        price = self.ui_equipment.lineEdit_price_equipment.text()
        subcategoryequipmentid = self.model_combo.index(
            self.ui_equipment.comboBox_subcategory_equipment.currentIndex(),
            self.model_combo.fieldIndex('id')).data()
        self.q.prepare("INSERT INTO equipment (title, pcs, price, subcategoryequipmentid) "
                       "VALUES (?, ?, ?, ?)")
        self.q.addBindValue(title)
        self.q.addBindValue(pcs)
        self.q.addBindValue(price)
        self.q.addBindValue(subcategoryequipmentid)
        if self.q.exec():
            self.ui_equipment.lineEdit_title_equipment.setText('')
            self.ui_equipment.lineEdit_pcs_equipment.setText('')
            self.ui_equipment.lineEdit_price_equipment.setText('')
            self.model.select()

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.config = config.Config()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # Иницилизация базы данных
        db = createddb.init_db()
        # Окно в окне
        self.mdiArea = QtWidgets.QMdiArea()
        self.setCentralWidget(self.mdiArea)
        # Menu Bar
        self.create_menubar()

    def show_equipment(self):
        self.sub_equipment = QtWidgets.QMdiSubWindow()
        self.sub_equipment.setWidget(EquipmentWidget())
        self.mdiArea.addSubWindow(self.sub_equipment)
        self.size()
        self.sub_equipment.resize(self.size() / 2)
        self.sub_equipment.show()

    def show_sub_category(self):
        self.sub_category = QtWidgets.QMdiSubWindow()
        self.sub_category.setWidget(SubCategoryWidget())
        self.mdiArea.addSubWindow(self.sub_category)
        self.size()
        self.sub_category.resize(self.size() / 2)
        self.sub_category.show()

    def show_category(self):
        self.category = QtWidgets.QMdiSubWindow()
        self.category.setWidget(CategoryWidget())
        self.mdiArea.addSubWindow(self.category)
        self.category.resize(self.size() / 2)
        self.category.show()

    def create_menubar(self):
        self.ui.categorys = self.ui.menuFile.addAction(self.tr("&Категория"))
        self.ui.category = self.ui.menubar.addAction(self.tr("&Категория"))
        self.ui.category.triggered.connect(self.show_category)
        self.ui.categorys.triggered.connect(self.show_category)

        self.ui.subcategory = self.ui.menuFile.addAction(self.tr("Sub Категория"))
        self.ui.subcategory = self.ui.menubar.addAction(self.tr("Sub Категория"))
        self.ui.subcategory.triggered.connect(self.show_sub_category)

        self.ui.equipment = self.ui.menuFile.addAction(self.tr("Список оборудования"))
        self.ui.equipment = self.ui.menubar.addAction(self.tr("Список оборудования"))
        self.ui.equipment.triggered.connect(self.show_equipment)

        # self.ui.new = self.ui.menuFile.addAction(self.tr("&New"))

        self.ui.quit_action = self.ui.menuFile.addAction(self.tr("&Quit"))
        self.ui.quit_action.triggered.connect(qApp.quit)
        #
        self.ui.about_action = self.ui.menuHelp.addAction(self.tr("&About"))
        self.ui.about_action.setShortcut(QKeySequence.HelpContents)
        self.ui.about_action.triggered.connect(self.about)
        self.ui.aboutQt_action = self.ui.menuHelp.addAction("&About Qt")
        self.ui.aboutQt_action.triggered.connect(qApp.aboutQt)

    # ------------------------------------------------------------------------------
    # -----Иницилизация приложения--------------------------------------------------

    @Slot()
    def about(self):
        QMessageBox.about(self, self.tr("About Books"),
                          self.tr("
The Books example shows how to use Qt SQL classes "
                                  "with a model/view framework."))

    def closeEvent(self, event):
        if not self.isMaximized():
            self.config.set_windowsize(self.width(), self.height())
        self.config.set_Maximized(self.isMaximized())

def application():
    app = QApplication(sys.argv)

    window = MainWindow()
    a, b = window.config.get_windowsize()
    window.resize(a, b)
    if window.config.get_Maximized():
        window.showMaximized()
    window.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    application()


from brownie import accounts, config, SimpleStorage, network

def deploy_simple_storage():
    # grab account from list
    account = get_account()
    simple_storage = SimpleStorage.deploy({"from": account})
    stored_value = simple_storage.retrieve()
    print(stored_value)
    transaction = simple_storage.store(15, {"from": account})
    transaction.wait(1)
    print("Updated:", simple_storage.retrieve())

    # Other methods to get an account
    # print(account)
    # load the account by name
    # account = accounts.load("first-account")
    # get private key from environment variables
    # account = accounts.add(os.getenv("PRIVATE_KEY"))
    # get account from config.yaml
    # account = accounts.add(config["wallets"]["from_key"])
    # print(account)

def get_account():
    if network.show_active() == "development":
        return accounts[0]
    else:
        return accounts.load("first-account")

def main():
    deploy_simple_storage()


class Node(object):

    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def reverse_list(head):
    new_head = None  # this is where we build the reversed list (reusing the existing nodes)
    while head:
        temp = head  # temp is a reference to a node we're moving from one list to the other
        head = temp.next  # the first two assignments pop the node off the front of the list
        temp.next = new_head  # the next two make it the new head of the reversed list
        new_head = temp
    return new_head

def printList(node):
    if node != None:
        print(node.data)
        printList(node.next)

a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')
a.next = b
b.next = c
c.next = d
d.next = e
printList(a)
new = reverse_list(a)
print()
printList(new)


# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Summarize to regions
# Author: Timm Nawrocki
# Last Updated: 2022-12-23
# Usage: Must be executed in an ArcGIS Pro Python 3.7 installation.
# Description: "Summarize to regions" is a function that summarizes a continuous raster to regions defined by a categorical raster.
# ---------------------------------------------------------------------------

# Define a function to summarize continuous rasters to categorical regions
def summarize_to_regions(**kwargs):
    """
    Description: summarizes a continuous raster to regions defined by a categorical raster
    Inputs: 'work_geodatabase' -- a geodatabase to store temporary results
            'input_array' -- an array containing the area raster (must be first), the continuous raster, and the categorical raster
            'output_array' -- an array containing the output raster
    Returned Value: Returns a raster to disk
    Preconditions: requires a continuous raster and categorical raster
    """

    # Import packages
    import arcpy
    from arcpy.sa import Int
    from arcpy.sa import Raster
    from arcpy.sa import RegionGroup
    from arcpy.sa import ZonalStatistics
    import datetime
    import time
    import os

    # Parse key word argument inputs
    work_geodatabase = kwargs['work_geodatabase']
    area_raster = kwargs['input_array'][0]
    continuous_raster = kwargs['input_array'][1]
    categorical_raster = kwargs['input_array'][2]
    output_raster = kwargs['output_array'][0]

    # Define intermediate datasets
    input_integer = os.path.join(os.path.split(categorical_raster)[0], 'integer.tif')

    # Set overwrite option
    arcpy.env.overwriteOutput = True

    # Specify core usage
    arcpy.env.parallelProcessingFactor = '0'

    # Set workspace
    arcpy.env.workspace = work_geodatabase

    # Set snap raster and extent
    arcpy.env.snapRaster = area_raster
    arcpy.env.extent = Raster(area_raster).extent

    # Set output coordinate system
    arcpy.env.outputCoordinateSystem = Raster(area_raster)

    # Set cell size environment
    cell_size = arcpy.management.GetRasterProperties(area_raster, 'CELLSIZEX', '').getOutput(0)
    arcpy.env.cellSize = int(cell_size)

    # Calculate regions
    print(f'\tCalculating regions...')
    iteration_start = time.time()
    # Copy raster to integer
    arcpy.management.CopyRaster(categorical_raster,
                                input_integer,
                                '',
                                '',
                                '-128',
                                'NONE',
                                'NONE',
                                '8_BIT_SIGNED',
                                'NONE',
                                'NONE',
                                'TIFF',
                                'NONE',
                                'CURRENT_SLICE',
                                'NO_TRANSPOSE')
    arcpy.management.CalculateStatistics(input_integer)
    arcpy.management.BuildRasterAttributeTable(input_integer, 'Overwrite')
    # Calculate regions
    raster_regions = RegionGroup(Raster(input_integer),
                                 'FOUR',
                                 'WITHIN',
                                 'NO_LINK')
    # End timing
    iteration_end = time.time()
    iteration_elapsed = int(iteration_end - iteration_start)
    iteration_success_time = datetime.datetime.now()
    # Report success
    print(
        f'\tCompleted at {iteration_success_time.strftime("%Y-%m-%d %H:%M")} (Elapsed time: {datetime.timedelta(seconds=iteration_elapsed)})')
    print('\t----------')

    # Summarize continuous raster to regions
    print(f'\tCalculating zonal statistics...')
    iteration_start = time.time()
    raster_statistics = ZonalStatistics(raster_regions,
                                        'VALUE',
                                        Raster(continuous_raster),
                                        'MEAN',
                                        'DATA',
                                        'CURRENT_SLICE')
    raster_int = Int(raster_statistics)
    # Export final raster
    arcpy.management.CopyRaster(raster_int,
                                output_raster,
                                '',
                                '',
                                '-128',
                                'NONE',
                                'NONE',
                                '8_BIT_SIGNED',
                                'NONE',
                                'NONE',
                                'TIFF',
                                'NONE',
                                'CURRENT_SLICE',
                                'NO_TRANSPOSE')
    # End timing
    iteration_end = time.time()
    iteration_elapsed = int(iteration_end - iteration_start)
    iteration_success_time = datetime.datetime.now()
    # Report success
    print(
        f'\tCompleted at {iteration_success_time.strftime("%Y-%m-%d %H:%M")} (Elapsed time: {datetime.timedelta(seconds=iteration_elapsed)})')
    print('\t----------')

    # Delete intermediate datasets
    if arcpy.Exists(input_integer) == 1:
        arcpy.management.Delete(input_integer)

    # Return success message
    out_process = f'Successfully summarized continuous raster.'
    return out_process


from math import asin, cos, radians, sin, sqrt

def get_distance_between_two_lat_lon(*args):
    lat1, lat2, long1, long2 = map(radians, args)

    dist_lats = abs(lat2 - lat1)
    dist_longs = abs(long2 - long1)
    a = sin(dist_lats / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dist_longs / 2) ** 2
    c = asin(sqrt(a)) * 2
    radius_earth = 6378  # the "Earth radius" R varies from 6356.752 km at the poles to 6378.137 km at the equator.

    return c * radius_earth


from .base_sensor import BaseSensor
from typing import Dict
from misc.units import Temp
import adafruit_sgp30
from busio import I2C
import time
from misc.config import Config

class SGP30(BaseSensor):

    def __init__(self, i2c: I2C, config: Config):
        super().__init__(self.__class__.__name__, config)
        try:
            self.sensor = adafruit_sgp30.Adafruit_SGP30(i2c)
            self.sensor.iaq_init()
            self.sensor.set_iaq_baseline(0x8973, 0x8AAE)
            self.enabled = True
        except:
            self.enabled = False

    def calibrate(self, iterations: int):
        if self.enabled:
            for x in range(iterations):
                self.sensor.eCO2
                self.sensor.TVOC
            self.logger.info("Done calibrating SGP30")
        else:
            self.logger.error("SGP30 disabled as a result of an i2c error")

    def debug(self):
        if self.enabled:
            self.logger.debug("calibrating...")
            self.logger.info(f"eCO2: {self.sensor.eCO2} ppm")
            self.logger.info(f"TVOC: {self.sensor.TVOC} ppb")
        else:
            self.logger.error("sgp30 disabled as a result of an i2c error")

    def read(self) -> Dict:
        if not self.enabled:
            return []
        timestamp = time.time_ns()
        return [
                {
                    "measurement": "co2",
                    "tags": {
                        "location": self.location.to_string(),
                        "sensor": self.name,
                        "reading": "co2"
                        },
                    "time": timestamp,
                    "fields": {
                        "field": self.sensor.eCO2
                        }
                    },
                {
                    "measurement": "tvoc",
                    "tags": {
                        "location": self.location.to_string(),
                        "sensor": self.name,
                        "reading": "tvoc"
                        },
                    "time": timestamp,
                    "fields": {
                        "field": self.sensor.TVOC
                        }
                    }
                ]


import sys
sys.path.append("..")

import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from ..misc import ModuleWrapper

from metrics import calculate_kl as KL_DIV

class BBBLinear(ModuleWrapper):
    def __init__(self, in_features, out_features, bias=True, priors=None):
        super(BBBLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.use_bias = bias

        if priors is None:
            priors = {
                'prior_mu': 0,
                'prior_sigma': 0.1,
                'posterior_mu_initial': (0, 0.1),
                'posterior_rho_initial': (-3, 0.1),
            }
        self.prior_mu = priors['prior_mu']
        self.prior_sigma = priors['prior_sigma']
        self.posterior_mu_initial = priors['posterior_mu_initial']
        self.posterior_rho_initial = priors['posterior_rho_initial']

        x = paddle.empty([in_features,out_features])
        self.W_mu = paddle.create_parameter(shape=x.shape,
                        dtype=str(x.numpy().dtype),
                        default_initializer=paddle.nn.initializer.Normal(*self.posterior_mu_initial))

        self.W_rho = paddle.create_parameter(shape=x.shape,
                        dtype=str(x.numpy().dtype),
                        default_initializer=paddle.nn.initializer.Normal(*self.posterior_rho_initial))

        if self.use_bias:
            y = paddle.empty([out_features])
            self.bias_mu = paddle.create_parameter(shape=y.shape,
                        dtype=str(y.numpy().dtype),
                        default_initializer=paddle.nn.initializer.Normal(*self.posterior_mu_initial))
            self.bias_rho = paddle.create_parameter(shape=y.shape,
                        dtype=str(y.numpy().dtype),
                        default_initializer=paddle.nn.initializer.Normal(*self.posterior_rho_initial))

    def forward(self, input, sample=True):
        if self.training or sample:
            W_eps = paddle.normal(mean = 0.0,std = 1.,shape=self.W_mu.shape)
            self.W_sigma = paddle.log1p(paddle.exp(self.W_rho))

            weight = self.W_mu + W_eps * self.W_sigma

            if self.use_bias:
                bias_eps = paddle.normal(mean = 0.0,std = 1.,shape=self.bias_mu.shape)
                self.bias_sigma = paddle.log1p(paddle.exp(self.bias_rho))

                bias = self.bias_mu + bias_eps * self.bias_sigma
            else:
                bias = None
        else:
            weight = self.W_mu
            bias = self.bias_mu if self.use_bias else None

        return F.linear(input, weight, bias)

    def kl_loss(self):
        kl = KL_DIV(self.prior_mu, self.prior_sigma, self.W_mu, self.W_sigma)
        if self.use_bias:
            kl += KL_DIV(self.prior_mu, self.prior_sigma, self.bias_mu, self.bias_sigma)
        return kl


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May  5 13:32:56 2017

@author: squall
"""

import os
import numpy as np
import nltk

from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

class Embeddings:

    def __init__(self, max_nb_words = 20000, max_sequence_length = 1000):

        self.GLOVE_DIR = "glove"
        self.EMBEDDING_DIM = 100

        self.max_number_of_words = max_nb_words
        self.max_sequence_length = max_sequence_length

        self.create_glove_dictionnary()

    def tokenize(self, text):

        return nltk.word_tokenize(text.lower())

    def create_glove_dictionnary(self):
        self.embeddings_index = {}
        f = open(os.path.join(self.GLOVE_DIR, 'glove.6B.100d.txt'), encoding="utf8")
        for line in f:
            values = line.split()
            word = values[0]
            coefs = np.asarray(values[1:], dtype='float32')
            self.embeddings_index[word] = coefs
        f.close()

        print('Found %s word vectors.' % len(self.embeddings_index))

    def tokens_to_glove_matrix(self, tokens, padded = False):

        rows_number = self.max_sequence_length if padded else len(tokens)
        self.embedding_matrix = np.zeros((rows_number, self.EMBEDDING_DIM))
        for i in range(min(len(tokens), rows_number)):
            word = tokens[i]
            embedding_vector = self.embeddings_index.get(word)
            if embedding_vector is not None:
                # words not found in embedding index will be all-zeros.
                self.embedding_matrix[i] = embedding_vector

        return self.embedding_matrix

    def create_embedding_matrix(self, text, padded = True):
        return self.tokens_to_glove_matrix(self.tokenize(text), padded)


# evaluation of toplevel results
# in the value undefined if the
# stash is empty
C = [{'tag': 'push_undefined_if_needed_i'},
     {'tag': 'blk',
      'body': loads(json_prelude)}]

# machine loops until control is empty
while True:
    if not C:
        break
    cmd = C.pop()
    cse_microcode[cmd['tag']](cmd)

if len(S) > 1 or len(S) < 1:
    raise Exception('internal error: stash must be singleton but is: ', S)
print("prelude loaded")
del json_prelude

# Free up as much memory as possible by triggering
# garbage collection when >5% of remaining free heap space is occupied
gc.collect()
gc.threshold(gc.mem_free() // 20 + gc.mem_alloc())


#!/usr/bin/env python
# Copyright (c) 2016, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.

"""
Composition
^^^^^^^^^^^

Combine data from different radar locations on one common set of locations

.. autosummary::
   :nosignatures:
   :toctree: generated/

   extract_circle
   togrid
   compose_ko
   compose_weighted

"""
import numpy as np

# from scipy.spatial import KDTree
# def extract_circle(center, radius, coords):
#     """
#     Extract the indices of coords which fall within a circle
#     defined by center and radius
#
#     Parameters
#     ----------
#     center : float
#     radius : float
#     coords : array of float with shape (numpoints,2)
#
#     Returns
#     -------
#     output : 1-darray of integers
#        index array referring to the coords array
#
#     """
#     print 'Building tree takes:'
#     t0 = dt.datetime.now()
#     tree = KDTree(coords)
#     print dt.datetime.now() - t0
#     print 'Query tree takes:'
#     t0 = dt.datetime.now()
#     ix = tree.query(center, k=len(coords), distance_upper_bound=radius)[1]
#     print dt.datetime.now() - t0
#     ix = ix[np.where(ix<len(coords))[0]]
#     return ix

def extract_circle(center, radius, coords):
    """
    Extract the indices of coords which fall within a circle
    defined by center and radius

    Parameters
    ----------
    center : float
    radius : float
    coords : array of float with shape (numpoints,2)

    Returns
    -------
    output : 1-darray of integers
        index array referring to the coords array

    """
    return np.where(((coords - center) ** 2).sum(axis=-1) < radius ** 2)[0]

def togrid(src, trg, radius, center, data, interpol, *args, **kwargs):
    """
    Interpolate data from a radar location to the composite grid or set of
    locations

    Parameters
    ----------
    src : ndarray of float of shape (numpoints, ndim)
        cartesian x / y coordinates of the radar bins
    trg : ndarray of float of shape (numpoints, ndim)
        cartesian x / y coordinates of the composite
    radius : float
        the radius of the radar circle (same units as src and trg)
    center : array of float
        the location coordinates of the radar
    data : ndarray of float
        the data that should be transferred to composite
    interpol : an interpolation class name from :meth:`wradlib.ipol`
        e.g. :class:`~wradlib.ipol.Nearest` or :class:`~wradlib.ipol.Idw`

    Other Parameters
    ----------------
    *args : arguments of Interpolator (see class documentation)

    Keyword Arguments
    -----------------
    **kwargs : keyword arguments of Interpolator (see class documentation)

    Returns
    -------
    output : ndarray of float
        data of the radar circle which is interpolated on the composite grid

    Examples
    --------

    See :ref:`notebooks/basics/wradlib_workflow.ipynb#Gridding`.

    """
    # get indices to select the subgrid from the composite grid
    ix = extract_circle(center, radius, trg)
    # interpolate on subgrid
    ip = interpol(src, trg[ix], *args, **kwargs)
    data_on_subgrid = ip(data).reshape((len(ix)))
    # create container for entire grid
    composegridshape = [len(trg)]
    composegridshape.extend(data.shape[1:])
    compose_grid = np.repeat(np.nan, len(trg) *
                             np.prod(data.shape[1:])).reshape(composegridshape)
    # push subgrid results into the large grid
    compose_grid[ix] = data_on_subgrid
    return compose_grid

def compose_ko(radargrids, qualitygrids):
    """Composes grids according to quality information using quality \
    information as a knockout criterion.

    The value of the composed pixel is taken from the radargrid whose
    quality grid has the highest value.

    Parameters
    ----------
    radargrids : list of arrays
        radar data to be composited. Each item in the list corresponds to the
        data of one radar location. All items must have the same shape.
    qualitygrids : list of arrays
        quality data to decide upon which radar site will contribute its pixel
        to the composite. Then length of this list must be the same as that
        of `radargrids`. All items must have the same shape and be aligned with
        the items in `radargrids`.

    Returns
    -------
    composite : array

    """
    # first add a fallback array for all pixels having missing values in all
    # radargrids
    radarfallback = (np.repeat(np.nan, np.prod(radargrids[0].shape))
                     .reshape(radargrids[0].shape))
    radargrids.append(radarfallback)
    radarinfo = np.array(radargrids)
    # then do the same for the quality grids
    qualityfallback = (np.repeat(-np.inf, np.prod(radargrids[0].shape))
                       .reshape(radargrids[0].shape))
    qualitygrids.append(qualityfallback)
    qualityinfo = np.array(qualitygrids)

    select = np.nanargmax(qualityinfo, axis=0)
    composite = (radarinfo.reshape((radarinfo.shape[0], -1))
                 [select.ravel(), np.arange(np.prod(radarinfo.shape[1:]))]
                 .reshape(radarinfo.shape[1:]))
    radargrids.pop()
    qualitygrids.pop()

    return composite

def compose_weighted(radargrids, qualitygrids):
    """Composes grids according to quality information using a weighted \
    averaging approach.

    The value of the composed pixel is the weighted average of all radar
    pixels with the quality values being the weights.

    Parameters
    ----------
    radargrids : list of arrays
    qualitygrids : list of arrays

    Returns
    -------
    composite : array

    Examples
    --------

    See :ref:`notebooks/workflow/recipe1.ipynb`.

    See Also
    --------
    compose_ko : for more description about the shape of the input arrays

    """
    radarinfo = np.array(radargrids)
    qualityinfo = np.array(qualitygrids)
    # overall nanmask
    nanmask = np.all(np.isnan(radarinfo), axis=0)
    # quality grids must contain values only where radarinfo does
    qualityinfo[np.isnan(radarinfo)] = np.nan

    qualityinfo /= np.nansum(qualityinfo, axis=0)

    composite = np.nansum(radarinfo * qualityinfo, axis=0)
    composite[nanmask] = np.nan

    return composite

if __name__ == '__main__':
    print('wradlib: Calling module <comp> as main...')


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

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from wagtail.wagtailcore import urls as wagtail_urls
from core import views as cv

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
    url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
    url(r'costs/$', TemplateView.as_view(template_name='core/costform.html'), name='costs'),
    url(r'risks/$', TemplateView.as_view(template_name='core/risks.html'), name='risks'),
    url(r'benefits/graph/$', TemplateView.as_view(template_name='core/benefits-graph.html'), name='benefits-summary'),
    url(r'summary/', TemplateView.as_view(template_name='core/summary-graph.html'), name='summary'),
    url(r'funding/graph/', cv.funding, name='funding-summary'),
    url(r'benefits/$', TemplateView.as_view(template_name='core/benefits.html'), name='benefits'),
    url(r'economics/$', TemplateView.as_view(template_name='core/economic-summary.html'), name='economics'),
    url(r'dashboard/$', TemplateView.as_view(template_name='core/dashboard.html'), name='dashboard'),
    url(r'testendpoint/$', cv.cost_items),
    # Django Admin, use {% url 'admin:index' %}
    url(settings.ADMIN_URL, include(admin.site.urls)),

    # User management
    url(r'^users/', include('businesscase.users.urls', namespace='users')),
    url(r'^accounts/', include('allauth.urls')),

    # Your stuff: custom urls includes go here
    url(r'^cms/', include(wagtailadmin_urls)),
    url(r'^documents/', include(wagtaildocs_urls)),
    url(r'^pages/', include(wagtail_urls)),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [
        url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
        url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
        url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
        url(r'^500/$', default_views.server_error),
    ]


t=int(input())
ls=[]
while t>0:
    this=input()
    t=t-1
    ls.append(this.split(" "))
    ls[len(ls)-1]=[int(x) for x in ls[len(ls)-1]]
#print(ls)
result=[]
for i in range(len(ls)):
    n=ls[i][0]
    L=ls[i][1]
    R=ls[i][2]
    s=str(bin(n))[2:]#二进制位
    while len(s)<R:
        s="0"+s
    left=len(s)-R
    right=len(s)-L
    for i in range(left,right+1):
        if s[i]=='0':
            s=s[:i]+'1'+s[i+1:]
        else:
            s=s[:i]+'0'+s[i+1:]
    result.append(eval("0b"+s))
for i in range(len(result)):
    print(result[i])


def copyRandomList_dict(self, head):  # O(n) and O(n) with a dictionary
    if not head: return
    # first pass copy the normal chain, remember the nodes
    memory = {None: None}
    new_root = ListNode(-1)
    new_node, node = new_root, head
    while node:
        # append new node
        new_node.next = ListNode(node.val)
        new_node = new_node.next
        # save to memory
        memory[node] = new_node
        # move forward
        node = node.next
    # second pass add random pointers
    new_node, node = new_root.next, head
    while node:
        random = node.random
        new_node.random = memory[random]
        # move forward
        node = node.next
        new_node = new_node.next
    return new_root.next

def copyRandomList_short(self, head): # O(n) both
    """
    Create a dictionary. Has to be with None, won't work otherwise
    It will have elements: node from the original list : newly created node with this value
    Keys (or new nodes) in this dictionary have "next" and "random." Need to fill them out
    At the end, return the key that corresponds to the head of the new list
    """
    d = {None : None}
    ptr = head
    while ptr:
        d[ptr] = ListNode(ptr.val)
        ptr = ptr.next
    ptr = head
    while ptr:
        d[ptr].next = d[ptr.next]
        d[ptr].random = d[ptr.random]
        ptr = ptr.next
    return d[head]

def copyRandomList_recursive(self, head): # O(n) and O(n)
    if head == None:
        return None
    # If we have already processed the current node, then we simply return the cloned version of it.
    if head in self.visitedHash:
        return self.visitedHash[head]
    # create a new node
    # with the value same as old node.
    node = Node(head.val, None, None)
    # Save this value in the hash map. This is needed since there might be
    # loops during traversal due to randomness of random pointers and this would help us avoid them.
    self.visitedHash[head] = node
    # Recursively copy the remaining linked list starting once from the next pointer and then from the random pointer.
    # Thus we have two independent recursive calls.
    # Finally we update the next and random pointers for the new node created.
    node.next = self.copyRandomList(head.next)
    node.random = self.copyRandomList(head.random)
    return node

def copyRandomList_iter(self, head): # O(n) and O(n)
    def getClonedNode(self, node):
        # If node exists then
        if node:
            # Check if its in the visited dictionary
            if node in self.visited:
                # If its in the visited dictionary then return the new node reference from the dictionary
                return self.visited[node]
            else:
                # Otherwise create a new node, save the reference in the visited dictionary and return it.
                self.visited[node] = Node(node.val, None, None)
                return self.visited[node]
        return None
    if not head:
        return head
    old_node = head
    # Creating the new head node.
    new_node = Node(old_node.val, None, None)
    self.visited[old_node] = new_node
    # Iterate on the linked list until all nodes are cloned.
    while old_node != None:
        # Get the clones of the nodes referenced by random and next pointers.
        new_node.random = self.getClonedNode(old_node.random)
        new_node.next = self.getClonedNode(old_node.next)
        # Move one step ahead in the linked list.
        old_node = old_node.next
        new_node = new_node.next
    return self.visited[head]

def copyRandomList_iter_efficient(self, head):  # O(n) and O(1)
    if not head:
        return head
    # Creating a new weaved list of original and copied nodes.
    ptr = head
    while ptr:
        # Cloned node
        new_node = Node(ptr.val, None, None)

        # Inserting the cloned node just next to the original node.
        # If A->B->C is the original linked list,
        # Linked list after weaving cloned nodes would be A->A'->B->B'->C->C'
        new_node.next = ptr.next
        ptr.next = new_node
        ptr = new_node.next
    ptr = head
    # Now link the random pointers of the new nodes created.
    # Iterate the newly created list and use the original nodes random pointers,
    # to assign references to random pointers for cloned nodes.
    while ptr:
        ptr.next.random = ptr.random.next if ptr.random else None
        ptr = ptr.next.next
    # Unweave the linked list to get back the original linked list and the cloned list.
    # i.e. A->A'->B->B'->C->C' would be broken to A->B->C and A'->B'->C'
    ptr_old_list = head # A->B->C
    ptr_new_list = head.next # A'->B'->C'
    head_old = head.next
    while ptr_old_list:
        ptr_old_list.next = ptr_old_list.next.next
        ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None
        ptr_old_list = ptr_old_list.next
        ptr_new_list = ptr_new_list.next
    return head_old


def bfs(lst):
    queue = deque()
    cnt = -1

    for t in lst:
        queue.append(t)

    while queue:
        cnt += 1
        for _ in range(len(queue)):
            vertex = queue.popleft()
            x = vertex[0]
            y = vertex[1]
            z = vertex[2]

            for move in range(6):
                nx = x + dx[move]
                ny = y + dy[move]
                nz = z + dz[move]

                if 0 <= nx < M and 0 <= ny < N and 0 <= nz < H and tomato[nz][nx][ny] == 0:
                    queue.append([nx, ny, nz])
                    tomato[nz][nx][ny] = 1

    return cnt

from collections import deque

N, M, H = map(int, input().split())

start = []
tomato = []

dx = [1, 0, 0, -1, 0, 0]
dy = [0, 1, 0, 0, -1, 0]
dz = [0, 0, 1, 0, 0, -1]

for h in range(H):
    plane = []

    for m in range(M):
        line = list(map(int, input().split()))

        for idx in range(N):
            if line[idx] == 1:
                start.append([m, idx, h])

        plane.append(line)

    tomato.append(plane)

res = True
res_cnt = bfs(start)

for k in range(H):
    for i in range(M):
        for j in range(N):
            if tomato[k][i][j] == 0:
                res = False
                break

if res:
    print(res_cnt)
else:
    print(-1)


import click
import requests
from app.models import User, db
from sqlalchemy import desc

from app.utils import map_user_data

URL = 'https://randomuser.me/api'

@click.command('sync')
def sync():
    try:
        response = requests.get(URL)
        data = response.json()

        users = [User(

            gender=result['gender'],
            name=result['name'],
            location=result['location'],
            email=result['email'],

        )
            for result in data['results']
        ]

        db.session.add_all(users)
        db.session.commit()
        print('Synchronization successful')
    except Exception:
        """
        In case of an unsuccessful synchronization attempt, the Connector should return
        data from the last successful synchronization
        """
        last_users = User.query.order_by(desc(User.timestamp)).limit(1).all()
        print('Synchronization failed')
        print('last successful synchronization data:')
        print(map_user_data(last_users))


# Напишите здесь свой код :-)
def poslat_nahui(name):
    """
    Print "poshel nahui"
    """
    print("Poshel nahui!\nTy pidor, " + name)

def summa(x, y):
   s = x + y
   return s

poslat_nahui("Vasya")
poslat_nahui("Petya")
poslat_nahui("Huesos")

print("Vasya soset y Peti " + str(summa(5, 15)) + " chasov")

#FACTORIZATION FUNCTION
def factor(x):
    """Calculate factorial"""
    otvet = 1
    for i in range(1, x+1):
        otvet = otvet * i
    return otvet

print(factor(1))
print(factor(5))

for i in range(1, 10):
   print(str(i) + "!\t = " + str(factor(i)))


from pyscfad.pbc import gto, scf

basis = 'gth-szv'
pseudo = 'gth-pade'

a = 5.431020511
lattice = [[0., a/2, a/2],
          [a/2, 0., a/2],
          [a/2, a/2, 0.]]
disp = 0.01
atom = [['Si', [0., 0., 0.]],
        ['Si', [a/4+disp, a/4+disp, a/4+disp]]]

cell = gto.Cell()
cell.atom = atom
cell.a = lattice
cell.basis = basis
cell.pseudo = pseudo
cell.verbose = 4
cell.build()

mf = scf.RHF(cell, exxdiv=None)
mf.kernel()
jac = mf.energy_grad()
print(f'Nuclaer gradient:\n{jac.coords}')


"""
Sample Hiew based Python statement prompt
"""
import hiew
import traceback

while True:
	s = hiew.GetString("Enter python statement", 100)
	if not s:
		break

	try:
	    r = exec(s, globals())

	except Exception as e:
	    hiew.Window.FromString(
	        'statement error',
	        str(e) + "\n" + traceback.format_exc())


#essa função foi criada para, verifica se os números que eu digitar estão corretas.
def validar_int(pergunta, nun, max):
    while True:
        try: #"perguntar" ta aqui pq ela substitui o texto que vc vai escreve
            x = int(input(pergunta))#esse opção substituir o input de sua pergunta com a variavel "pergunta'
            if nun <= x <= max: #aqui verificar se o numero foi escolhido certo
                return x #aqui retorna o valor la pra cimar
            else: #caso didite o valor invalido a p´ção vem pra car
                print('Opção inválida')
        except ValueError:
            print('Entrada inválida. Digite um número inteiro.')

def cria_Arquivo(nomeArquivo): #essa função vai criar um aquivo
    try:
        a = open(nomeArquivo, "wt+")
        a.close()
    except: #caso de algum erro de sintaxi
        print('erro na criação do arquivo!!!!!!!') #caso de algum erro  vai aparecer essa mensagem
    else:
        print(f'aquivo {nomeArquivo} criado com sucesso!!!!')# se não der vai aparece essa msg

def existe_Arquivo(nomeArquivo): #essa função foi criada para abrir o arquivo eu acho ksksksks
    try:
        a= open(nomeArquivo, 'rt') #aqui vc verifica se p arquivo existe, "r" de leitura e "t" de texto tipo de arquivo
        a.close() #fechar o arquivo
    except FileNotFoundError: #aqui se o arqui não existi vai dar erro, ai exeção ta ai pra isso, ai ele dar falso
        return False #se o arqui não exite
    else: #ele vai retorna verdadeiro se o arquivo existi
        return True #se arquivo existi

def listaArquivo(nomeArquivo):
    try:
        a = open(nomeArquivo, 'rt')
    except:
        print('erro ao ler o arquivo')
    else:
        print(a.read())
    finally:
        a.close()

def cadastraJogo (nomeArquivo, nomeJogo, nomeVideogame):
    try:
        a = open(nomeArquivo, 'at')
    except:
        print('erro de abrir o arquivo')
    else:
        a.write(f'{nomeJogo};{nomeVideogame}\n')
    finally:
        a.close()

#programa principal
arquivo='games.txt' #esse qo nome do arquivo, que vai ser criado ou não
if existe_Arquivo(arquivo): #aqui vai printa se o arquivo existe ou não
    print('arquivo localizado no computador')
else:
    print('Arquivo inexistente, criando aquivo...')
    cria_Arquivo(arquivo) #essa função vai criar o arquivo, caso ele não exista

while True:
    try:
        print('----MENU----')
        print('1 - Cadastra novo item')
        print('2 - Lista cadastro')
        print('3 - Sair')
        op= validar_int('Qual a opção desejada \n>> ', 1 , 3)

        if op == 1:
            print('opção de Cadastra novo item selecionada')
            nomeJogo= input('Qual o nome do Jogo? \n>> ')
            nomeVideogame= input('Qual o nome do Video Game? \n>> ')
            cadastraJogo (arquivo, nomeJogo, nomeVideogame)

        elif op ==2:
            print('opção de Lista cadastro selecionada')
            listaArquivo(arquivo)
        elif op == 3:
            print('encerrando programa...')
            break
    except ValueError:
        print('digite apenas números inteiros')


import discord
from discord.ext import commands
import asyncio

description = '''Beep boop.'''
bot = commands.Bot(command_prefix='?', description=description)

@bot.event
@asyncio.coroutine
def on_ready():
    global server_data
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    #yield from bot.say('Beep boop.')

@bot.group(pass_context=True, invoke_without_command=True)
@asyncio.coroutine
def stack(context, command=None):
    global bot
    global help_message
    """Execute a Stack-related command."""
    if command is None:
        yield from bot.say(help_message)
    else:
        yield from bot.say('Invalid stack command.')

@stack.command(pass_context=True)
@asyncio.coroutine
def regchannel(context, channel: str=None):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    target_channel = None
    for server_channel in context.message.channel.server.channels:
        if server_channel.mention == channel or server_channel.name == channel or server_channel.id == channel:
            if context.message.author.permissions_in(server_channel).administrator:
                target_channel = server_channel
                break
    if target_channel != None:
        server_data[server]['stack_channel'] = target_channel
        yield from bot.say('Registered channel ' + server_data[server]['stack_channel'].mention + ' as stack channel.')
    else:
        yield from bot.say('Error, no channel was registered.')

from copy import deepcopy

@stack.command(pass_context=True)
@asyncio.coroutine
def lock(context):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    if not context.message.author.permissions_in(context.message.channel.server.default_channel).administrator:
        yield from bot.say('You must be an admin to use this command.')
    elif len(server_data[server]['stored_overwrites']) > 0:
        yield from bot.say('The channel is already locked.')
    elif server_data[server]['stack_channel'] == None:
        yield from bot.say('A channel must be registered first.')
    elif server_data[server]['stack_role'] == None:
        yield from bot.say('A role must be registered first.')
    else:
        for target, overwrite in server_data[server]['stack_channel'].overwrites:
            server_data[server]['stored_overwrites'].append((target, deepcopy(overwrite)))
            overwrite.send_messages = False
            yield from bot.edit_channel_permissions(server_data[server]['stack_channel'], target, overwrite)
        overwrite = discord.PermissionOverwrite()
        overwrite.send_messages = True
        yield from bot.edit_channel_permissions(server_data[server]['stack_channel'], server_data[server]['stack_role'], overwrite)
        yield from bot.say('Channel locked.')

@stack.command(pass_context=True)
@asyncio.coroutine
def unlock(context):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    if not context.message.author.permissions_in(context.message.channel.server.default_channel).administrator:
        yield from bot.say('You must be an admin to use this command.')
    elif server_data[server]['stack_channel'] == None:
        yield from bot.say('A channel must be registered first.')
    elif server_data[server]['stack_role'] == None:
        yield from bot.say('A role must be registered first.')
    else:
        for target, overwrite in server_data[server]['stored_overwrites']:
            yield from bot.edit_channel_permissions(server_data[server]['stack_channel'], target, overwrite)
        server_data[server]['stored_overwrites'].clear()
        yield from bot.delete_channel_permissions(server_data[server]['stack_channel'], server_data[server]['stack_role'])
        yield from bot.say('Channel unlocked.')

# TODO check that the bot has the perms to assign the permission
@stack.command(pass_context=True)
@asyncio.coroutine
def regrole(context, role: str=None):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    target_role = None
    if server_data[server]['stack_channel'] == None:
        yield from bot.say('A channel must be registered first.')
    else:
        for server_role in context.message.channel.server.roles:
            if server_role.mention == role or server_role.name == role or server_role.id == role:
                if context.message.author.permissions_in(context.message.channel.server.default_channel).administrator:
                    target_role = server_role
                    break
        if target_role != None:
            if True:
                server_data[server]['stack_role'] = target_role
                yield from bot.say('Registered role ' + server_data[server]['stack_role'].name + ' as stack role for ' + server_data[server]['stack_channel'].mention + '.')
            else:
                yield from bot.say('Could not register role ' + target_role.name + ', as I do not have the permissions to apply it.')
        else:
            yield from bot.say('Error, no role was found with the given name/id.')

@stack.command(pass_context=True)
@asyncio.coroutine
def join(context):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    if context.message.author.permissions_in(server_data[server]['stack_channel']).read_messages:
        if context.message.author not in server_data[server]['queue_members']:
            server_data[server]['speaking_queue'].append(context.message.author)
            server_data[server]['queue_members'].add(context.message.author)
            if len(server_data[server]['speaking_queue']) == 1:
                yield from bot.add_roles(server_data[server]['speaking_queue'][0], server_data[server]['stack_role'])
                yield from bot.send_message(server_data[server]['stack_channel'], server_data[server]['speaking_queue'][0].mention + ', it is your turn to speak.')
            else:
                yield from bot.say('You have been placed on the queue.')
        else:
            yield from bot.say('You are already on the queue.')
    else:
        yield from bot.say('You do not have read permissions in the appropriate channel to join the stack.')

@stack.command(pass_context=True)
@asyncio.coroutine
def leave(context):
    global bot
    global server_data
    server = context.message.channel.server
    if context.message.author in server_data[server]['queue_members']:
        index = server_data[server]['speaking_queue'].index(context.message.author)
        server_data[server]['speaking_queue'].pop(index)
        server_data[server]['queue_members'].remove(context.message.author)
        yield from bot.say('You have been removed from the stack.')
        if index == 0:
            yield from bot.remove_roles(context.message.author, server_data[server]['stack_role'])
            if len(server_data[server]['speaking_queue']) > 0:
                yield from bot.send_message(server_data[server]['stack_channel'], server_data[server]['speaking_queue'][0].mention + ', it is your turn to speak.')
            else:
                yield from bot.send_message(server_data[server]['stack_channel'], 'The speaking queue is empty. Please use the join command to place yourself on the queue.')
    else:
        yield from bot.say('You cannot leave the stack because you are not in it.')

@stack.command(pass_context=True)
@asyncio.coroutine
def next(context):
    """"""
    global bot
    global server_data
    server = context.message.channel.server
    if context.message.channel == server_data[server]['stack_channel']:
        if len(server_data[server]['speaking_queue']) != 0 and (context.message.author.permissions_in(context.message.channel.server.default_channel).administrator or context.message.author == server_data[server]['speaking_queue'][0]):
            yield from bot.remove_roles(server_data[server]['speaking_queue'][0], server_data[server]['stack_role'])
            queue_member = server_data[server]['speaking_queue'].pop(0)
            server_data[server]['queue_members'].remove(queue_member)
            if len(server_data[server]['speaking_queue']) > 0:
                yield from bot.add_roles(server_data[server]['speaking_queue'][0], server_data[server]['stack_role'])
                yield from bot.send_message(server_data[server]['stack_channel'], server_data[server]['speaking_queue'][0].mention + ', it is your turn to speak.')
            else:
                yield from bot.say('The speaking queue is empty. Please use the join command to place yourself on the queue.')
        elif len(server_data[server]['speaking_queue']) == 0:
            yield from bot.say('The speaking queue is empty. Please use the join command to place yourself on the queue.')
        else:
            yield from bot.say('You do not have the permissions necessary to move to the next speaker.')
    else:
        pass # Ignore the message.

from collections import defaultdict

def default():
    return {'stack_channel': None, 'stack_role': None, 'speaking_queue': [], 'queue_members': set(), 'stored_overwrites': []}

help_message = """```
?stack regchannel [channel-name]: registers the stack channel.
?stack regrole [role-name]: registers the role channel.
?stack join: puts the author of the message on the stack, if they are not already.
?stack leave: takes the author out of the stack, if they are on it.
?stack next: only recognized in the stack channel itself. Used by the current speaker or admins (when appropriate), removes the current speaker from the stack and lets the next person speak.
```"""
from pickle import load, dump
from pathlib import Path
save_location = Path('server_data.pickle')
try:
    with save_location.open('rb') as save_fp:
        server_data = load(save_fp)
except FileNotFoundError:
    server_data = defaultdict(default)
try:
    with open('turing-machine-token.dat') as token_fp:
        bot.run(token_fp.read().strip())
except FileNotFoundError:
    print('No token file was found.')
finally:
    try:
        for server in server_data:
            server_data[server]['speaking_queue'].clear()
            server_data[server]['queue_members'].clear()
        with save_location.open('wb') as save_fp:
            dump(server_data, save_fp)
    except:
        print('Failed to save data.')
        raise


# Django
from django.utils import timezone

# Standard Library
from datetime import date, timedelta

# Third Party
import pytest
from dateutil.relativedelta import relativedelta

# Squarelet
from squarelet.organizations import tasks
from squarelet.organizations.models import Charge, Subscription
from squarelet.organizations.tests.factories import SubscriptionFactory

@pytest.mark.django_db()
def test_restore_organization(organization_plan_factory, mocker):
    patched = mocker.patch("squarelet.organizations.tasks.send_cache_invalidations")
    mocker.patch("stripe.Plan.create")
    today = date.today()
    organization_plan = organization_plan_factory()

    subsc_update_cancel = SubscriptionFactory(
        update_on=today - timedelta(1), plan=organization_plan, cancelled=True
    )
    subsc_update_later = SubscriptionFactory(
        update_on=today + timedelta(1), plan=organization_plan
    )
    subsc_update = SubscriptionFactory(
        update_on=today - timedelta(1), plan=organization_plan
    )

    tasks.restore_organization()

    subsc_update_later.refresh_from_db()
    subsc_update.refresh_from_db()

    # update cancel should have been deleted
    assert not Subscription.objects.filter(pk=subsc_update_cancel.pk).exists()

    # update later should have not been changed
    assert subsc_update_later.plan == organization_plan
    assert subsc_update_later.update_on == today + timedelta(1)

    assert subsc_update.plan == organization_plan
    assert subsc_update.update_on == today + relativedelta(months=1)

    assert patched.call_args[0][0] == "organization"
    assert set(patched.call_args[0][1]) == set(
        [subsc_update.organization.uuid, subsc_update_cancel.organization.uuid]
    )

class TestHandleChargeSucceeded:
    """Unit tests for the handle_charge_succeeded task"""

    @pytest.mark.django_db()
    def test_with_invoice(self, organization_factory, mocker):
        timestamp = timezone.now().replace(microsecond=0)
        charge_data = {
            "amount": 2500,
            "created": int(timestamp.timestamp()),
            "customer": "cus_Bp0Alb14pfVB9D",
            "description": "Payment for invoice E28A672-0040",
            "id": "ch_EwJiGXbaafREhT",
            "invoice": "in_EwIgmFCn7cnZFB",
            "metadata": {},
            "object": "charge",
        }
        organization = organization_factory(
            customer__customer_id=charge_data["customer"]
        )
        invoice = {
            "id": "in_EwIgmFCn7cnZFB",
            "lines": {
                "data": [
                    {
                        "amount": 2500,
                        "plan": {"id": "org", "product": "prod_BTLmRCZ5cpxsPH"},
                    }
                ]
            },
        }
        product = {"name": "Organization"}
        mocker.patch(
            "squarelet.organizations.tasks.stripe.Invoice.retrieve",
            return_value=invoice,
        )
        mocker.patch(
            "squarelet.organizations.tasks.stripe.Product.retrieve",
            return_value=product,
        )
        mocked = mocker.patch("squarelet.organizations.models.Charge.send_receipt")

        tasks.handle_charge_succeeded(charge_data)

        charge = Charge.objects.get(charge_id=charge_data["id"])
        assert charge.amount == charge_data["amount"]
        assert charge.fee_amount == 0
        assert charge.organization == organization
        assert charge.created_at == timestamp
        assert charge.description == product["name"]
        mocked.assert_called_once()

    @pytest.mark.django_db()
    def test_without_invoice(self, organization_factory, mocker):
        timestamp = timezone.now().replace(microsecond=0)
        charge_data = {
            "amount": 2500,
            "created": int(timestamp.timestamp()),
            "customer": "cus_Bp0Alb14pfVB9D",
            "description": "Payment for request #123",
            "id": "ch_EwJiGXbaafREhT",
            "invoice": None,
            "metadata": {},
            "object": "charge",
        }
        organization = organization_factory(
            customer__customer_id=charge_data["customer"]
        )
        mocked = mocker.patch("squarelet.organizations.models.Charge.send_receipt")

        tasks.handle_charge_succeeded(charge_data)

        charge = Charge.objects.get(charge_id=charge_data["id"])
        assert charge.amount == charge_data["amount"]
        assert charge.fee_amount == 0
        assert charge.organization == organization
        assert charge.created_at == timestamp
        assert charge.description == charge_data["description"]
        mocked.assert_called_once()

    def test_without_customer(self):
        timestamp = timezone.now().replace(microsecond=0)
        charge_data = {
            "amount": 2500,
            "created": int(timestamp.timestamp()),
            "customer": None,
            "description": "Payment for request #123",
            "id": "ch_EwJiGXbaafREhT",
            "invoice": None,
            "metadata": {},
            "object": "charge",
        }

        tasks.handle_charge_succeeded(charge_data)

    def test_crowdfund(self):
        timestamp = timezone.now().replace(microsecond=0)
        charge_data = {
            "amount": 2500,
            "created": int(timestamp.timestamp()),
            "customer": "cus_Bp0Alb14pfVB9D",
            "description": "Payment for request #123",
            "id": "ch_EwJiGXbaafREhT",
            "invoice": None,
            "metadata": {"action": "crowdfund-payment"},
            "object": "charge",
        }

        tasks.handle_charge_succeeded(charge_data)

    def test_recurring_donation(self, mocker):
        timestamp = timezone.now().replace(microsecond=0)
        charge_data = {
            "amount": 2500,
            "created": int(timestamp.timestamp()),
            "customer": "cus_Bp0Alb14pfVB9D",
            "description": "Payment for invoice E28A672-0040",
            "id": "ch_EwJiGXbaafREhT",
            "invoice": "in_EwIgmFCn7cnZFB",
            "metadata": {},
            "object": "charge",
        }
        invoice = {
            "id": "in_EwIgmFCn7cnZFB",
            "lines": {
                "data": [
                    {
                        "amount": 2500,
                        "plan": {"id": "donate", "product": "prod_BTLmRCZ5cpxsPH"},
                    }
                ]
            },
        }
        mocker.patch(
            "squarelet.organizations.tasks.stripe.Invoice.retrieve",
            return_value=invoice,
        )

        tasks.handle_charge_succeeded(charge_data)

@pytest.mark.django_db()
def test_handle_invoice_failed(organization_factory, user_factory, mailoutbox):
    user = user_factory()
    customer_id = "cus_123"
    organization = organization_factory(
        admins=[user], customer__customer_id=customer_id
    )
    invoice_data = {"id": 1, "customer": customer_id, "attempt_count": 2}
    tasks.handle_invoice_failed(invoice_data)
    organization.refresh_from_db()
    assert organization.payment_failed
    mail = mailoutbox[0]
    assert mail.subject == "Your payment has failed"
    assert mail.to == [user.email]


import logging

class LoggingFramework:
    """ Yara Learner Logging Framework """
    def __init__(self):
        self.logger = logging.getLogger('yLogger')
        self.logger.setLevel(logging.INFO)
        formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")

        fHandle = logging.FileHandler("yaralearn.log")
        sHandle = logging.StreamHandler()

        fHandle.setFormatter(formatter)
        sHandle.setFormatter(formatter)

        self.logger.addHandler(fHandle)
        self.logger.addHandler(sHandle)

    def __del__(self):
        del self


import asyncio
import logging
import re
from datetime import datetime
from typing import Dict, List

from aiohttp import ClientSession, ClientTimeout
from bs4 import BeautifulSoup

from structs import ScheduleForTheDay, Lesson

class SsauAPI:
    HEADERS = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0'
    }
    HOST = 'https://ssau.ru'

    async def _request(self, url: str, tries_count=10) -> str:
        async with ClientSession(timeout=ClientTimeout(total=500), headers=self.HEADERS) as session:
            status = None
            while status != 200:
                if tries_count == 0:
                    raise ConnectionError('Не удалось получить данные')
                async with session.get(f'{self.HOST}{url}') as response:
                    status = response.status
                    logging.info(f'Запрос к {self.HOST}{url}. Статус {status}')
                    if status != 200:
                        await asyncio.sleep(.5)
                        tries_count -= 1
                        continue
                    return await response.text()

    async def get_institutes_and_faculties(self) -> Dict[str, int]:
        page = await self._request('/rasp')
        soup = BeautifulSoup(page, features='html.parser')
        return {item.a.text.strip(): int(re.search(r'\d+', item.a.attrs['href']).group())
                for item in soup.find_all('div', class_='faculties__item')}

    async def get_groups(self, faculty: int, course: int) -> Dict[str, int]:
        page = await self._request(f'/rasp/faculty/{faculty}?course={course}')
        soup = BeautifulSoup(page, features='html.parser')
        return {container.text.strip(): int(re.search(r'\d+', container.attrs['href']).group())
                for container in soup.find_all('a', class_='group-catalog__group')}

    async def get_timetable_by(self, group_id: int, week: int) -> List[ScheduleForTheDay]:
        page = await self._request(f'/rasp?groupId={group_id}&selectedWeek={week}')
        soup = BeautifulSoup(page, features='html.parser')
        raw_table = soup.find('div', class_='schedule__items')

        cells = iter(raw_table.find_all('div', class_='schedule__item'))
        time = [next(cells).text.strip()]
        table = [[] for _ in range(6)]
        for i, cell in enumerate(cells):
            table[i % 6].append(cell)

        time.extend([tuple(t.text.strip() for t in cell.find_all('div', class_='schedule__time-item'))
                     for cell in raw_table.find_all('div', class_='schedule__time')])

        timetable = []

        for day in table:
            day = iter(day)
            title = next(day)
            date_container = title.find('div', class_='schedule__head-date')
            date = datetime.strptime(date_container.text.strip(), '%d.%m.%Y').date()
            lessons = []
            for i, raw_lesson in enumerate(day, start=1):
                if not raw_lesson.text:
                    break
                start, end = time[i]
                place = raw_lesson.find('div', class_='schedule__place').text.strip()

                lessons.append(Lesson(
                    title=raw_lesson.find('div', class_='schedule__discipline').text.strip(),
                    is_online='online' in ''.join(filter(str.isalpha, place)).lower(),
                    place=place,
                    teacher=raw_lesson.find('div', class_='schedule__teacher').a.text.strip(),
                    groups=[c.text.strip() for c in
                            raw_lesson.find('div', class_='schedule__groups').find_all(class_='caption-text')],
                    start=start,
                    end=end
                ))
            timetable.append(ScheduleForTheDay(date=date,
                                               lessons=lessons))

        return timetable


import itertools
import torch
import pytest
from typing import Mapping, List, Callable, Optional, Tuple

__all__ = ["device_dtype_float_test"]

def device_dtype_float_test(only64: int = False, onlycpu: bool = False,
                            additional_kwargs: Mapping[str, List] = {},
                            skip_fcn: Optional[Callable[..., Tuple[bool, str]]] = None) -> Callable:

    dtypes = [torch.float, torch.float64]
    devices = [torch.device("cpu"), torch.device("cuda")]
    if only64:
        dtypes = [torch.float64]
    if onlycpu or not torch.cuda.is_available():
        devices = [torch.device("cpu")]
    kwargs_vals = additional_kwargs.values()
    argnames = ",".join(["dtype", "device"] + list(additional_kwargs.keys()))
    iters = itertools.product(dtypes, devices, *kwargs_vals)

    # decide which one to skip
    if skip_fcn is None:
        params = [*iters]
    else:
        params = []
        for p in iters:
            skip, reason = skip_fcn(*p)
            param = pytest.param(*p, marks=pytest.mark.skipif(skip, reason=reason))
            params.append(param)
    return pytest.mark.parametrize(argnames, params)


import lockable_resource.constants as const
import rqueue.constants as const_rqueue
from django.contrib import messages
from django.shortcuts import render, redirect, HttpResponse
from lockable_resource.models import *
from lockable_resource.query_param_manager import QueryParamManager
from lockable_resource.action_manager import LRActionObjectsHandler

def lockable_resources_page(request):
    if request.method == "GET":
        query_params = request.GET
        if query_params:
            qp_key = list(dict(query_params).keys())[0]
            qp_val = list(dict(query_params).values())[0][0]
            q_manager = QueryParamManager(qp_key, qp_val)
            data = q_manager.handle_key()

            return HttpResponse(data, content_type="text/plain")

        # Display regularly the page if no query_params added
        lockable_resources = LockableResource.objects.all().order_by("name")
        return render(
            request,
            template_name="lockable_resource/all.html",
            context={"lockable_resources": lockable_resources},
        )

    if request.method == "POST":
        # Get Desired Action:
        desired_action = request.POST.get("action")
        action_handler = LRActionObjectsHandler.SUPPORTED_ACTION_OBJECTS.get(
            desired_action
        )
        # Create an instance of the desired action handler
        action_obj = action_handler(request)
        action_obj.complete_action()

        return redirect("lockable_resources_page")

def lockable_resource_more_info(request, slug):
    lr = LockableResource.objects.get(id=slug)
    # Gather the next & previous Lockable resource and send as context
    # This is useful in this template only for navigating
    next_lr = lr.next_obj()
    previous_lr = lr.previous_obj()
    return render(
        request,
        template_name="lockable_resource/lockable_resource_more_info.html",
        context={
            "lockable_resource": lr,
            "next_lockable_resource": next_lr,
            "previous_lockable_resource": previous_lr,
        },
    )


from unittest.mock import patch
from task_warrior.task_warrior import TaskWarrior, Projects
from .helper import Helper

class TestTasks(object):

    def test_task_is_hydrated_into_a_task_object(self):
        task_properties = [
            "id", "uuid", "project","description","due", "entry", "modified",
            "project", "start", "status","urgency"]

        with patch.object(TaskWarrior, 'search',
                          return_value=Helper.load_fixture('tasks')) as \
                mocked_search:

            tasks = TaskWarrior('')

            mocked_search.assert_called()

            assert hasattr(tasks.tasks['a1a'], 'id')

            for task_property in task_properties:
                assert hasattr(tasks.tasks['a1a'], task_property)


import pickle

from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer

from data.feature import clean_text_data

def train_sentimental_analysis_model(df, text_column_name='body',
                                     label_column_name='nltk_sentiment_label',
                                     model_name='model/pipe.pickle') -> None:

    tfidf = TfidfVectorizer(tokenizer=clean_text_data)
    classifier = LinearSVC()

    X = df[text_column_name]
    Y = df[label_column_name]

    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=25)
    clf_pipe = Pipeline([('tfidf', tfidf), ('clf', classifier)], verbose=True)
    clf_pipe.fit(X_train, y_train)

    # store the trained model
    with open(model_name, 'wb') as pickle_file:
        pickle.dump(clf_pipe, pickle_file)

def predict_sentimental_analysis(df, text_column_name='body', model_name='model/pipe.pickle', text=''):
    # load the trained model
    with open(model_name, 'rb') as pickle_file:
        stored_pipe = pickle.load(pickle_file)

    if text == '':
        text = df[text_column_name]
        prediction = stored_pipe.predict(text)
    else:
        prediction = stored_pipe.predict(text)

    return prediction


import unittest

import ocr_service

class TestMLService(unittest.TestCase):
    """
    Tests all different possible feedbacks from the vehicle registration plate
    model.
    """

    def test_plate_reader(self):

        # Predict normal European plate
        car_1 = ocr_service.plate_reader("/src/tests/cartest1.jpg")
        self.assertEqual(car_1, "RO B396JOY")

        # Predict European plate with text under the plate and with e-mail
        car_2 = ocr_service.plate_reader("/src/tests/cartest2.jpg")
        self.assertEqual(car_2, "BG CA7552PP")

        # Predict European plate with text above and under the plate
        car_3 = ocr_service.plate_reader("/src/tests/cartest3.jpg")
        self.assertEqual(car_3, "UA AA6888KI")

        # Predict European plate with an angle and separated
        car_4 = ocr_service.plate_reader("/src/tests/cartest4.jpg")
        self.assertEqual(car_4, "NL BT4732")

        # Predict European plate with unclear characters
        car_5 = ocr_service.plate_reader("/src/tests/cartest5.jpg")
        self.assertEqual(
            car_5,
            "There is no European vehicle registration plate or the characters are unclear",
        )

        # Predict no European plate
        car_6 = ocr_service.plate_reader("/src/tests/cartest6.jpg")
        self.assertEqual(
            car_6,
            "There is no European vehicle registration plate or the characters are unclear",
        )

if __name__ == "__main__":
    unittest.main()


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.rnn as torchrnn
import torch.optim as optim

class DLModel(nn.Module):
    """
        Parameters:
        - feature_nums: list of feature num for every detector.
        - hidden_size: number of hidden units
        - output_size: number of output
        - num_layers: layers of LSTM to stack
    """
    def __init__(self):
        super().__init__()
        hidden_size = 2
        num_layers = 2

        self.fc1 = nn.Linear(1,2)
        self.relu1 = nn.LeakyReLU()
        self.fc2 = nn.Linear(3,4)
        self.relu2 = nn.LeakyReLU()
        self.fc3 = nn.Linear(4,2)

        self.lstm = nn.LSTM(input_size=1, hidden_size=hidden_size, num_layers=num_layers, batch_first=True)
        self.noiseLstm = nn.LSTM(input_size=1,hidden_size=1, num_layers=num_layers, batch_first=True)
        self.forwardCalculation = nn.Linear(hidden_size, 2)

        self.noiseFc = nn.Linear(1, 1)

        self.B = 1250  # 连铸坯宽度
        self.W = 230  # 连铸坯厚度
        self.L = 1  # 结晶器内液面高度
        self.c2h = 1  # c2(h)：流量系数
        self.A = 11313  # 下水口侧孔面积
        self.Ht = 10  # 计算水头高
        self.H1t = 1  # 中间包液面高度
        self.H2 = 1300  # 下水口水头高度
        self.H3 = 2  # 下侧孔淹没高度，需要计算
        self.h = 1  # 塞棒高度
        self.startLv = 350

    def forward(self, x, context, lengths, preLv):
        offset = 6
        hs = x
        aLengths = (lengths).reshape(-1).tolist()
        lengths = (lengths-offset).reshape(-1).tolist()

        # packX = torchrnn.pack_padded_sequence(x, aLengths, True)
        # ls, _ = self.lstm(x)

        # padX, _ = torchrnn.pad_packed_sequence(packX, True)

        x = self.fc1(x)  # _x is input, size (seq_len, batch, input_size)
        # x = self.relu1(x)
        # x = self.fc2(x)
        # x = self.relu2(x)
        # x = self.fc3(x)

        ts = torch.zeros(x.shape[1], device=torch.device('cuda'))
        ts[:] = 0.5
        pre_lv_act = torch.zeros(x.shape[0], 1, 1, device=torch.device('cuda'))
        pre_lv_act[:] = preLv
        deltaLvs, totalLvs = self.calculate_lv_acts_tensor(hs, ts, x, x.shape[0], 0, pre_lv_act)

        totalLvs = torchrnn.pack_padded_sequence(hs, lengths, batch_first=True)

        noise_out, (h, c) = self.noiseLstm(totalLvs)
        firstNoiseOutput, (h,c) = self.noiseLstm(h[-1,:,:].reshape([-1,1,1]), (h, c))
        noiseOutput = torch.zeros([x.shape[0],0,1], device=torch.device('cuda'))
        for i in range(x.shape[1] - offset):
            singleNoiseOutput, (h, c) = self.noiseLstm(h[-1,:,:].reshape([-1,1,1]), (h, c))
            noiseOutput = torch.cat((noiseOutput, singleNoiseOutput), 1)
        noiseOutput = self.noiseFc(noiseOutput)

        totalLvs, _ = torchrnn.pad_packed_sequence(totalLvs, True)
        # finalOutput = noiseOutput + deltaLvs
        # noise_out, _ = torchrnn.pad_packed_sequence(noise_out, True)

        #ctotalLvs = totalLvs - self.startLv
        output = noiseOutput + deltaLvs[:,offset: deltaLvs.shape[1]]
        # deltaLvs = torchrnn.pack_padded_sequence(deltaLvs, lengths, batch_first=True)
        # deltaLvs, _ = torchrnn.pad_packed_sequence(deltaLvs, batch_first=True)
        # totalLvs = torchrnn.pack_padded_sequence(totalLvs, lengths, batch_first=True)
        # totalLvs, _ = torchrnn.pad_packed_sequence(totalLvs, batch_first=True)

        return deltaLvs[:,offset: deltaLvs.shape[1]], totalLvs, noiseOutput

    def stp_pos_flow_tensor(self, h_act, lv_act, t, dt=0.5, params=[0,0,0,0]):
        H1t = params[:,0] # H1：中间包液位高度，t的函数，由LSTM计算
        g = 9.8                 # 重力
        # c2h = lpm(torch.tensor(h_act).reshape(-1))  # C2：和钢种有关的系数，由全网络计算
        c2h = params[:,1]

        # 引锭头顶部距离结晶器底部高度350+结晶器液位高度（距离引锭头）283
        # if lv_act < 63.3:
        #     H3 = 0
        # else:
        #     H3 = lv_act-63.3  # H3下侧出口淹没高度
        H3 = 0
        Ht = H1t+self.H2-H3
        dL = (pow(2 * g * Ht, 0.5) * c2h * self.A * dt) / (self.B * self.W)
        return dL

    def calculate_lv_acts_tensor(self, hs, ts, params, batch_first = True, previousTime = 0, pre_lv_act = 0):
        sampleRate = 2  # 采样率是2Hz。
        # 维度为（时间，数据集数量，特征数）
        deltaLvs = torch.zeros(hs.shape, device=torch.device('cuda'))
        totalLvs = torch.zeros(hs.shape, device=torch.device('cuda'))
        batchSize = hs.shape[0]
        lv = pre_lv_act
        sample_count = 0
        for stage in range(params.shape[1]):
            # stopTimeSpan = ts[stage]
            if stage > 0:
                previousTime += ts[stage-1]
            time = stage
            current_lv = self.stp_pos_flow_tensor(hs[:,stage,:], lv, previousTime + time / 2, 1 / sampleRate, params[:, stage, :])
            # print(current_lv.reshape([-1]).item())
            current_lv = current_lv.reshape(batchSize, 1, 1)
            lv += current_lv
            deltaLvs[:,time:time+1, 0:1] = current_lv
            if time == 0:
                curTotalLv = pre_lv_act
            else:
                curTotalLv = totalLvs[:,time-1:time, 0:1]
            totalLvs[:,time:time+1, 0:1] = (curTotalLv + current_lv)
            sample_count += 1
        # if batch_first:
        #     tlvs = tlvs.reshape([tlvs.shape[1], tlvs.shape[0], -1])

        return deltaLvs, totalLvs