import os
from xmind import XMindDocument
from xmind.document import SHAPE_RECTANGLE, SHAPE_ROUND_RECTANGLE, SHAPE_ELLIPSIS
from requirements import Attribute

import config

class AttributeNotRenderable(Exception):
    pass

class AttributeRenderer:
    markers = config.getAttributeMarkers()

    def __init__(self, attr):
        if not attr.isValid():
            raise AttributeNotRenderable("Attribute '%s' with value '%s' is not valid" % (attr.getName(), attr.getValue()))

        self.attribute = attr

    def isValid(self):
        return (self.attribute.getName() in AttributeRenderer.markers.keys()) and (self.attribute.getOrder() <= len(AttributeRenderer.markers[self.attribute.getName()]) )

    def render(self):
        order = self.attribute.getOrder()

        return AttributeRenderer.markers[self.attribute.getName()][order]

class Renderer:
    def __init__(self, chapters, requirements, doc=None, renderOrphans=True, renderFolded=True, maxDepth=999, verbose=False):
        self.requirements = requirements
        self.verbose = verbose
        self.chapters = chapters
        self.maxDepth = maxDepth
        self.xmindDoc = doc
        if self.xmindDoc is None:
            self.xmindDoc = XMindDocument.create(u"ReqTrees", u"text")

        self.levelsProgression = ['system', 'user', 'business']

        self._renderOrphans = renderOrphans
        self.renderFolded = renderFolded

        self.topicStyle = {}
        if doc is None:
            self.topicStyle['unknown'] = Renderer.setupStyle(self.xmindDoc, "unknown")
            self.topicStyle['business'] = Renderer.setupStyle(self.xmindDoc, "business")
            self.topicStyle['user'] = Renderer.setupStyle(self.xmindDoc, "user")
            self.topicStyle['system'] = Renderer.setupStyle(self.xmindDoc, "system")
        else:
            self.topicStyle = self.xmindDoc.get_styles()

        self.issues = []

    @staticmethod
    def setupStyle(xmindDoc, what):
        style = config.getMapStyle(what)
        return xmindDoc.create_topic_style( style['fill'], styleid=what, shape=style['shape'], line_color=style['lineColor'], line_width=style['lineWidth'])

    def setStyle(self, requirement, topic):
        style = 'unknown'
        if requirement.getCategory() in self.topicStyle.keys():
            style = requirement.getCategory()
        else:
            print("WARNING: Unknown category: %s" % requirement.getCategory())

        topic.set_style( self.topicStyle[ style ] )

    def setupSheet(self, rootSheet, rootTopic):
        pass

    def render(self, filename, sheet=None):
        rootSheet = sheet
        if rootSheet is None:
            rootSheet = self.xmindDoc.get_first_sheet()

        rootTopic = rootSheet.get_root_topic()

        cat = self.setupSheet(rootSheet, rootTopic)
        self.renderContent(rootSheet, cat )

        if self._renderOrphans:
            self.renderOrphans(rootTopic)
            self.renderNoLinks(rootTopic)

        if sheet is None:
            self.xmindDoc.save(filename)

    def renderContent(self, rootSheet, category ):
        self.attributeIssues = {}
        rootTopic = rootSheet.get_root_topic()

        for chapter in self.chapters:
            if chapter['category'] == category and len(chapter['reqs']) > 0:
                newTopic = rootTopic.add_subtopic(chapter['name'], folded=True)
                newTopic.set_style(self.topicStyle[category])

                children = self.sortLinks(chapter['reqs'])
                for reqID in children:
                    self.renderTopic(None, newTopic, reqID )

    def renderOrphans(self, rootTopic):
        for cat in self.levelsProgression[:-1]: # skip the business requirements
            orphans = []
            for key, req in self.requirements.items():
                if req.getCategory() == cat:
                    found = False
                    for key2, req2 in self.requirements.items():
                        for link in self.getNextLevel(req2):
                            if link == req.getID():
                                found = True
                                break

                        if found:
                            break

                    if not found and (key not in orphans):
                        orphans.append(key)

            if len(orphans) > 0:
                topic = rootTopic.add_subtopic("Orphaned %s Requirements" % cat )
                for key in orphans:
                    req = self.requirements[key]
                    self.createTopic(topic, req)

    def renderNoLinks(self, rootTopic):
        for cat in self.levelsProgression[1:]:   # skip the system requirements
            orphans = []
            for key, req in self.requirements.items():
                if req.getCategory() == cat and len(req.getLinks()) == 0:
                    orphans.append(key)

            if len(orphans) > 0:
                topic = rootTopic.add_subtopic("%s Requirements without links" % cat )
                for key in orphans:
                    req = self.requirements[key]
                    self.createTopic(topic, req)

    def createTopic(self, root, requirement):
        newTopic = root.add_subtopic(requirement.getText(), folded=self.renderFolded)
        self.setStyle(requirement, newTopic)

        note = ("%s\n%s" % (requirement.getID(), requirement.getFullText()))
        newTopic.set_note(note)

        for a in requirement.getAttributes():
            renderer = AttributeRenderer(a)
            if renderer.isValid():
                newTopic.add_marker(renderer.render())
            else:
                if a.getValue() is not None and len(a.getValue()) > 1 and requirement.getID() not in self.attributeIssues.keys():
                    msg = "WARNING: unknown attribute value ('%s') for '%s' in requirement %s" % (a.getValue(), a.getName(), requirement.getID())
                    self.attributeIssues[requirement.getID()] = msg
                    if self.verbose:
                        print(msg)

        return newTopic

    # sort the links attributed to a requirement.
    # use the 3 attributes priority, risk and difficulty
    def sortLinks(self, reqList):
        reqs = []
        for l in reqList:
          r = self.getLinkedRequirement(l)
          if r is not None:
              reqs.append(r)

        def reqOrder(req):
            order = []
            attrs = req.getAttributes()
            for attributeOrder in ['Priority', 'Risk', 'Difficulty']:
                for attribute in attrs:
                    if attribute.getName() == attributeOrder:
                       order.append( attribute.getOrder() )
                       break

            return order

        reqs.sort(key=reqOrder)
        return [x.getID() for x in reqs]

    def renderTopic(self, root, rootTopic, link ):
        linked = self.getLinkedRequirement(link)
        valid = (linked is not None )  # do we have valid links (consdiering the asymmetry between business and system)?

        if valid:
            newTopic = self.createTopic(rootTopic, linked)
            children = self.sortLinks(self.getNextLevel(linked))
            for l in children:
                self.renderTopic(linked, newTopic, l)

    def getNextLevel(self, requirement):
        pass

    def getLinkedRequirement(self, link):
        req = None
        if link in self.requirements.keys():
            req = self.requirements[link]

        return req

class BottomUpRenderer(Renderer):
    def setupSheet(self, rootSheet, rootTopic):
        rootSheet.set_title(u"BottomUp" )
        rootTopic.set_title(u"BottomUp Requirements tree" )

        return self.levelsProgression[0]

    def getNextLevel(self, requirement):
        links = []
        for i in range(0, len(self.levelsProgression)):
            if requirement.getCategory() == self.levelsProgression[i] and i< (len(self.levelsProgression) - 1):
                category = self.levelsProgression[i+1]
                for reqID, req in self.requirements.items():
                    if req.getCategory() == category and requirement.getID() in req.getLinks():
                        links.append(reqID)

        return links

class TopDownRenderer(Renderer):
    def setupSheet(self, rootSheet, rootTopic):
        rootSheet.set_title(u"TopDown" )
        rootTopic.set_title(u"TopDown Requirements tree" )

        return self.levelsProgression[-1]

    def getNextLevel(self, requirement):
        return requirement.getLinks()

class UnifiedRenderer:
    def __init__(self, chapters, requirements, renderFolded=True, maxDepth=999, verbose=False):
        self.xmindDoc = XMindDocument.create(u"ReqTrees", u"text")
        self.topicStyle = {}

        self.topicStyle['unknown'] = Renderer.setupStyle(self.xmindDoc, "unknown")
        self.topicStyle['business'] = Renderer.setupStyle(self.xmindDoc, "business")
        self.topicStyle['user'] = Renderer.setupStyle(self.xmindDoc, "user")
        self.topicStyle['system'] = Renderer.setupStyle(self.xmindDoc, "system")

        self.topdown = TopDownRenderer(chapters, requirements, doc=self.xmindDoc, renderOrphans=False, renderFolded=True, maxDepth=maxDepth, verbose=verbose)
        self.bottomup = BottomUpRenderer(chapters, requirements, doc=self.xmindDoc, renderOrphans=False, renderFolded=True, maxDepth=maxDepth, verbose=verbose)

    def render(self, filename ):

        # topdown is the first sheet
        sheet = self.xmindDoc.get_first_sheet()
        self.topdown.render(None, sheet=sheet )

        # bottomup is the first sheet
        newsheet = self.xmindDoc.create_sheet(u"ReqTrees", u"text")
        self.bottomup.render(None, sheet=newsheet)

        # now render orphans
        newsheet = self.xmindDoc.create_sheet(u"Issues", u"Issues")
        root = newsheet.get_root_topic()
        self.topdown.renderOrphans(root)
        self.topdown.renderNoLinks(root)

        # add a legend. the XMind legend creation does not seem to work properly anymore, so we create a dedicated sheet with all info
        newsheet = self.xmindDoc.create_sheet(u"Conventions", u"Conventions")
        root = newsheet.get_root_topic()
        self.renderLegend(root)

        # save our precious work!
        self.xmindDoc.save(filename)

    def renderLegend(self, root):
        # render topic styles legend
        rootTypes = root.add_subtopic("Requirement types", folded=False)

        for name, style in self.topicStyle.items():
            if name != "unknown":
                t = rootTypes.add_subtopic("%s Requirements" % name)
                t.set_style(style)

        # render markers legend
        rootMarkers = root.add_subtopic("Requirement attributes", folded=False)

        attributeMappings = config.getAttributeMappings()
        attributeTypes = attributeMappings.keys()

        for markerType in attributeTypes:
            generic = Attribute.getDescription(markerType)
            rootType = rootMarkers.add_subtopic(markerType, folded=True)
            rootType.set_note(generic)

            #levels = AttributeRenderer.getAttributeMapping(markerType)
            #levels = config.getAttributeMapping(markerType)
            for levelname, levelvalue in attributeMappings[markerType].items():
                descr = "indicates %s" % levelname
                m = rootType.add_subtopic(descr)
                m.add_marker(levelvalue)

        # render orphans + nolinks
        rootIssues = root.add_subtopic("Requirements Issues", folded=False)
        orphans = rootIssues.add_subtopic("Orphans: requirements that are not linked by any other requirement")
        orphans.set_style(self.topicStyle['unknown'])
        orphans.set_note("If a user requirement is not linked by any business requirement, this implies that this user requirement has no foundation in any business need and thus should not be implemented. If a system requirement is not linked by any user requirement, this implies that this system requirement is not related to any user feature, and thus may not be needed at all")

        nolinks = rootIssues.add_subtopic("NoLinks: requirements that do not link to any other requirement")
        nolinks.set_style(self.topicStyle['unknown'])
        nolinks.set_note("If a business requirement is not linked to any other requirement, the conclusion is that the requirement is NOT going to be implemented. In other words, any business requirement that is not linked to other (user) requirement results in a need that will not be addressed by the project. This situation should be avoided as much as possible: each business requirement is expected to have at least one link.\n If a user requirement has no link to any system requirement, this implies that, while there is a business need that was converted into a user requirement, this will not be implemented. This situation should be avoided as much as possible: each user requirement is expected to be linked to at least one system requirement.")

        # render traceability
        rootTrace = root.add_subtopic("Requirements traceability", folded=False)
        orphans = rootTrace.add_subtopic("TopDown: from business requirements down to system requirements traceability")
        orphans.set_style(self.topicStyle['unknown'])

        nolinks = rootTrace.add_subtopic("BottmUp: from system requirements up to business requirements traceability")
        nolinks.set_style(self.topicStyle['unknown'])


# This has to be imported before requests module to prevent warning
#   MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors,
#   including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7.
#   Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016
from rocket_league.authentication.steam_authentication import steam_login, encode_steam_encrypted_app_ticket
from rocket_league.authentication.rocket_league_authentication import rl_auth
from rocket_league.requests import get_game_server_find_private_game_server_request
from rocket_league import rocket_league_constants
import getpass
import json
import logging
import websocket
import _thread as thread
import time

def rocket_league_connect_to_websocket(url, psy_token, session_id):
    def on_message(_, message):
        start = message.index('\r\n\r\n')
        start += 4
        message_length = len(message) - start
        if message_length == 0:
            print('[ROCKET LEAGUE] Message received with length 0')
        else:
            message = message[start:]
            message = json.loads(message)
            if len(message['Responses'][0]['Result']['Servers']) > 0:
                print('[MATCH FOUND] Match found!')

    def on_error(_, error):
        print(error)

    def on_close(_):
        print("[ROCKET LEAGUE] Websocket closed!")

    def on_open(_):
        print('[ROCKET LEAGUE] Connected to websocket!')

        def run(*_):
            brute_force(web_socket)

            time.sleep(1)
            web_socket.close()
            print("[ROCKET LEAGUE] Closing websocket...")

        thread.start_new_thread(run, ())

    websocket.enableTrace(True)
    web_socket = websocket.WebSocketApp(url,
                                        header={
                                            'PsyToken': psy_token,
                                            'PsySessionID': session_id,
                                            'PsyBuildID': rocket_league_constants.RLBuildId,
                                            'PsyEnvironment': rocket_league_constants.RLEnvironment,
                                            'User-Agent': rocket_league_constants.RLUserAgent
                                        },
                                        on_message=on_message,
                                        on_error=on_error,
                                        on_close=on_close,
                                        on_open=on_open)
    logging.getLogger('websocket').setLevel(logging.INFO)
    web_socket.run_forever()

def brute_force(web_socket):
    with open('rocket_league_private_server_wordlist') as file:
        for line in file:
            word = line.strip()
            print('[BRUTE FORCE] Testing {}:{}'.format(word, word))
            web_socket.send(get_game_server_find_private_game_server_request(word, word))
            rocket_league_constants.increase_id()
            time.sleep(1)

def main():
    print('[STEAM] Parsing config file...')
    with open('steam_login.config') as steam_login_config_file:
        steam_login_config = json.load(steam_login_config_file)

    print('[STEAM] Logging in...')
    two_factor_code = getpass.getpass('Enter 2FA> ')
    steam_client = steam_login(steam_login_config['username'], steam_login_config['password'], two_factor_code)
    print('[STEAM] Successfully logged in!')

    print('[STEAM] Getting id_64, encrypted_app_ticket and display_name...')
    steam_id_64 = steam_client.user.steam_id.as_64
    steam_encrypted_app_ticket = \
        steam_client.get_encrypted_app_ticket(rocket_league_constants.RLAppId, b'').encrypted_app_ticket
    steam_encoded_encrypted_app_ticket = encode_steam_encrypted_app_ticket(steam_encrypted_app_ticket)
    steam_display_name = steam_client.user.name

    print('[ROCKET LEAGUE] Authenticating with RL servers...')
    rl_auth_response = rl_auth(steam_id_64, steam_encoded_encrypted_app_ticket, steam_display_name)
    if rl_auth_response.get('Error', None) is not None:
        print('[ERROR][ROCKET LEAGUE] Failed to authenticate with the RL servers. Exiting.')
        exit(1)
    print('[ROCKET LEAGUE] Successfully authenticated with the RL servers!')

    print('[ROCKET LEAGUE] Grabbing per_con_url, psy_token and session_id...')
    per_con_url = rl_auth_response['Responses'][0]['Result']['PerConURL']
    psy_token = rl_auth_response['Responses'][0]['Result']['PsyToken']
    session_id = rl_auth_response['Responses'][0]['Result']['SessionID']

    print('[ROCKET LEAGUE] Connecting to websocket...')
    rocket_league_connect_to_websocket(per_con_url, psy_token, session_id)

if __name__ == '__main__':
    main()


depths = []

try:
    with open('depthmeasures.txt', 'r') as depth_file:
        line = depth_file.readline()
        depths.append(int(line))
        while line != '':
            line = depth_file.readline()
            try:
                depths.append(int(line))
            except:
                continue
finally:
    depth_file.close()

counter = 0
blocks = []
j = 0
while (j < len(depths) - 2):
    sum = depths[j] + depths[j+1] + depths[j+2]
    blocks.append(sum)
    j = j + 1

prev_block = blocks[0]
for i in range(1, len(blocks)):
    block = blocks[i]
    if (block > prev_block):
        counter = counter + 1
    prev_block = block

print(counter)


import tkinter as tk
import time

# Function to update the click count
def update_count():
    global click_count
    click_count += click_multiplier
    count_label.config(text=f"Click Count: {click_count}")
    save_click_count()

# Function to increase click multiplier
def buy_multiplier():
    global click_multiplier, click_count
    cost = 10  # Cost to buy the multiplier
    if click_count >= cost:
        click_count -= cost
        click_multiplier += 1
        count_label.config(text=f"Click Count: {click_count}")
        multiplier_label.config(text=f"Click Multiplier: {click_multiplier}")
        save_click_count()

# Function to reset the click count and timer
def reset_game():
    save_click_count()
    exit()

# Function to save the click count and multiplier to a file
def save_click_count():
    with open("click_data.txt", "w") as file:
        file.write(f"{click_count}\n{click_multiplier}")

# Function to load the click count and multiplier from a file
def load_click_data():
    try:
        with open("click_data.txt", "r") as file:
            data = file.read().splitlines()
            if len(data) >= 1:
                return int(data[0]), int(data[1])
            else:
                return 0, 1  # Default values if data is incomplete
    except FileNotFoundError:
        return 0, 1  # Default values if the file doesn't exist

# Function to update the timer
def update_timer():
    elapsed_time = time.time() - start_time
    timer_label.config(text=f"Time Elapsed: {int(elapsed_time)} seconds")
    root.after(1000, update_timer)  # Update timer every 1000 milliseconds (1 second)

# Create the main window
root = tk.Tk()
root.title("PyClicker")

# Initialize the click count, click multiplier, and start time
click_count, click_multiplier = load_click_data()
start_time = time.time()

# Create and configure the count label
count_label = tk.Label(root, text=f"Click Count: {click_count}", font=("Arial", 24))
count_label.pack(pady=20)

# Create and configure the multiplier label
multiplier_label = tk.Label(root, text=f"Click Multiplier: {click_multiplier}", font=("Arial", 18))
multiplier_label.pack()

# Create and configure the timer label
timer_label = tk.Label(root, text="Time Elapsed: 0 seconds", font=("Arial", 18))
timer_label.pack()

# Create the click button
click_button = tk.Button(root, text="Click Me!", command=update_count, font=("Arial", 18))
click_button.pack()

# Create the buy button
buy_button = tk.Button(root, text="Buy Multiplier (Cost: 10)", command=buy_multiplier, font=("Arial", 18))
buy_button.pack()

# Create the reset button
reset_button = tk.Button(root, text="I'm Feeling Lucky", command=reset_game, font=("Arial", 18))
reset_button.pack()

# Start the timer
update_timer()

# Run the main loop
root.mainloop()


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import emailmerge_lib

sender_name = emailmerge_lib.sender_email[0]
sender_email = emailmerge_lib.sender_email[1]
failed_emails = list()

#opening connection to server
try:
    server = smtplib.SMTP('smtp.gmail.com',587)
    server.starttls()
    server.ehlo()
except SMTPHeloError:
    print ("couldnt say ehlo to the server")
try:
    server.login(sender_email, emailmerge_lib.sender_email[2])
except smtplib.SMTPAuthenticationError:
    print("trouble with authentication ")

#looping through all in email_list
print("Sending email to:")
for email in emailmerge_lib.email_list:
    if emailmerge_lib.email_list.index(email) == 0:
        continue

    # drafting email
    target_email = email[2]
    first_name = email[0]
    last_name = email[1]
    subject = emailmerge_lib.email_subject
    email_body = emailmerge_lib.email_body.format(f_name = first_name, l_name = last_name)
    msg = MIMEMultipart()

    msg['From'] = sender_name
    msg['To'] = target_email
    msg['Subject'] = subject

    msg.attach(MIMEText(email_body, 'html'))

    # adding attachments
    msg.attach(emailmerge_lib.attachment_part)

    # sending email
    print("\t{} {}".format(first_name, last_name)) # name of the recieptant
    try:
        message = msg.as_string()
        server.sendmail(sender_email, target_email, message)
    except SMTPException:
        # adding emails to the failed list
        failed_emails.append(target_email)

server.close()

if len(failed_emails) > 0:
    print ("\n{0} of {1} could not be sent".format(len(failed_emails), len(emailmerge_lib.email_list)))
    for email in failed_emails:
        print("\t" + email)
else:
    print ("Emails sent")


from bs4 import BeautifulSoup
import time

class Seguidores():
    def __init__(self, dados, driver):
        self.dados = dados
        self.driver = driver

    def get_dados(self):
        self.scroll_final_page()
        self.salva_dados()

    def scroll_final_page(self):
        print('Realizando scroll da pagina.')
        SCROLL_PAUSE_TEMPO = 1.5
        ultima_altura_pagina = self.driver.browser.execute_script(
            "return document.body.scrollHeight")

        while True:
            self.driver.browser.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(SCROLL_PAUSE_TEMPO)
            nova_altura_pagina = self.driver.browser.execute_script(
                "return document.body.scrollHeight")
            if nova_altura_pagina == ultima_altura_pagina:
                break
            ultima_altura_pagina = nova_altura_pagina

    def get_html(self):
        print("Gerando HTML")
        time.sleep(2)
        element = self.driver.busca_css(self.dados["css_box_dados"])
        html_content = element.get_attribute('outerHTML')
        diretorio = self.dados["diretorio_html"]
        arquivo_html = open(diretorio, "w")
        arquivo_html.write(html_content)
        print('Pagina HTML salva com sucesso.')
        return html_content

    def salva_dados(self):
        html_content = self.get_html()
        bs = BeautifulSoup(html_content, 'html.parser')
        linhas = bs.findAll(
            'span', {'class': 'entity-result__title-text t-16'})

        lista = []
        diretorio = self.dados["diretorio_txt"]
        arquito_txt = open(diretorio, "w")

        for item in linhas:
            link = item.findChildren("a")
            url = link[0]['href']
            lista.append(url)
            arquito_txt.write(f'{url}\n')
        print('Dados salvos com sucesso.')


import os
import csv
import random
from typing import *
import io

col_num = 270
sql = '''
DROP TABLE IF EXISTS test_table_local;
DROP TABLE IF EXISTS test_table;

CREATE TABLE IF NOT EXISTS test_table_local (
    %s
)ENGINE = MergeTree()
PARTITION BY date
order by date
SETTINGS index_granularity=8192;

CREATE TABLE IF NOT EXISTS test_table AS test_table_local
ENGINE = Distributed(cluster_7shard_1replicas, default,
                     test_table_local, id);
'''

def rand_csv_data(col_num, row_num):
    date = '2019-01-01'
    col_names = ['date', 'id', 'time']
    for i in range(col_num):
        col_names.append('p' + str(i))
    rows = []
    for i in range(row_num):
        id = random.randint(0, 30)
        rows.append([date, id, ''])

        for j in range(col_num):
            rows[i].append(random.randint(0, 2 ** 20))
    return (col_names, rows)

def write_csv(path: str, col_names: List, rows: List):
    with open(path, 'w') as file:
        writer = csv.writer(file)
        # writer.writerow(col_names)
        writer.writerows(rows)

def create_types(col_names: List, col_types: List):
    s = ''
    for i in range(len(col_names)):
        s += '\t' + col_names[i] + ' ' + col_types[i] + ',\n'
    return s[:-2]

def create_sql(path: str, col_names: List, col_types: List):
    s = create_types(col_names, col_types)
    with open(path, 'w') as file:
        file.write(sql % (s))

col_types = ['Date', 'Int64', 'DateTime default now()']

if __name__ == '__main__':
    (col_names, rows) = rand_csv_data(col_num, 1000)
    write_csv('./temp/rand.csv', col_names, rows)
    for i in range(len(col_names) - 2):
        col_types.append('Int64')
    create_sql('./temp/autogen.sql', col_names, col_types)


import asyncio
import collections
import copy
import json
import random
import secrets

import socketio
from sanic import Sanic, response
from sanic.exceptions import abort

from diagnosis import Diagnosis
from nearest import getNearest
from sentiment import asyncAnalyze

app = Sanic(__name__)
sio = socketio.AsyncServer(async_mode="sanic", cors_allowed_origins=[])
sio.attach(app)

sessionSidStorage = {}

with open("./badwords.json", "r", encoding="utf-8") as fp:
    badwordsFilter = json.load(fp)

@app.middleware("response")
async def allowCors(_, response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Methods"] = [
        "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    ]

@app.options("/nearest")
async def __(request):
    return response.empty()

@app.post("/nearest")
async def nearestAPI(request):
    return response.json(
        getNearest(
            tuple(map(float, request.form["Pos"].pop().split(","))),
            request.form["type"].pop(),
        )
    )

def getQuestion(session):
    if not session.get("Sections"):
        session["Sections"] = [
            (copy.deepcopy(Diagnosis.Negative), "Negative"),
            (copy.deepcopy(Diagnosis.Positive), "Positive"),
            (copy.deepcopy(Diagnosis.Useless), "Useless"),
        ]

    if not session.get("Results"):
        session["Results"] = collections.defaultdict(list)

    if not session.get("Count"):
        session["Count"] = 0

    while True:
        Sections = list(filter(lambda x: bool(x[0]), session["Sections"]))

        if not Sections:
            break

        Section, SectionName = random.choice(Sections)
        random.shuffle(Section)

        if not Section:
            continue

        session["current"] = (Section.pop(), SectionName)
        return True

    return False

@sio.on("connect", namespace="/chatBot")
async def connect(sid, _):
    await sio.emit(
        "botMessage",
        {
            "content": f"""{random.choice(Diagnosis.Introduction)}

마음의 숲은 문맥속에 담긴 감정으로 우울증을 진단하는 서비스입니다.

정확한 분석을 위해서 예/아니오와 같은 단답보다는 글로 답변해주세요.""",
            "waitForNext": False,
        },
        to=sid,
        namespace="/chatBot",
    )

    async with sio.session(sid, namespace="/chatBot") as session:
        if getQuestion(session):
            await sio.emit(
                "botMessage",
                {"content": session["current"][0], "waitForNext": True},
                to=sid,
                namespace="/chatBot",
            )

@sio.on("clientMessage", namespace="/chatBot")
async def clientMessage(sid, data):
    async with sio.session(sid, namespace="/chatBot") as session:
        if any(filter(lambda x: x in data["content"].lower(), badwordsFilter)):
            return await sio.emit(
                "messageDenied",
                {"content": data["content"]},
                to=sid,
                namespace="/chatBot",
            )

        await sio.emit(
            "messageAccepted",
            {"content": data["content"], "isDelivered": True},
            to=sid,
            namespace="/chatBot",
        )

        Sentiment = await asyncAnalyze(data["content"], app.loop)

        if session.get("current"):
            session["Count"] += 1
            session["Results"][session["current"][1]].append(Sentiment)

        NewQuestion = getQuestion(session)

        if NewQuestion:
            return await sio.emit(
                "botMessage",
                {"content": session["current"][0], "waitForNext": True},
                to=sid,
                namespace="/chatBot",
            )

        Score = 0
        TotalScore = session["Count"] * 4

        for Result in session["Results"]["Positive"]:
            Operators = {
                "POS": lambda x: 4 - x,
                "NEUT": lambda _: 2,
                "NEG": lambda x: x,
            }

            Type, Value = max(Result.items(), key=lambda x: x[1])
            Value = Operators[Type](round(Value / 25))

            Score += Value

        for Result in session["Results"]["Negative"]:
            Operators = {
                "POS": lambda x: x,
                "NEUT": lambda _: 2,
                "NEG": lambda x: 4 - x,
            }

            Type, Value = max(Result.items(), key=lambda x: x[1])
            Value = Operators[Type](round(Value / 25))

            Score += Value

        return await sio.emit(
            "returnResult",
            {"score": Score, "totalScore": TotalScore},
            to=sid,
            namespace="/chatBot",
        )

Meetings = []

@app.options("/1")
async def __(request):
    return response.empty()

@app.post("/1")
async def _(request):
    print(request.form)
    Score, TotalScore = float(request.form["Score"].pop()), float(
        request.form["TotalScore"].pop()
    )

    Percentage = round(Score / TotalScore * 100)

    if Meetings:
        if Percentage >= 60:
            abort(403, message="Score is too high.")

        Matched = sorted(
            Meetings, keys=lambda x: abs(x[0] - Percentage), reverse=True
        ).pop()

        roomId = secrets.token_hex()

        Matched[1].put_nowait(roomId)
        return response.text(roomId)

    event = asyncio.Queue(maxsize=1)

    Meetings.append([Percentage, event])

    try:
        roomId = await asyncio.wait_for(
            event.get(), timeout=float(request.form.get("timeout", ["30.0"]))
        )
    except asyncio.TimeoutError:
        abort(408, message="Matching Timed out.")
    finally:
        Meetings.remove([Percentage, event])

    return response.text(roomId)

@sio.on("setRoom", namespace="/chat")
async def setRoom(sid, data):
    async with sio.session(sid, namespace="/chat") as session:
        session["roomId"] = data["roomId"]

        sio.enter_room(sid, session["roomId"], namespace="/chat")

        await sio.emit(
            "userJoined", room=session["roomId"], skip_sid=sid, namespace="/chat"
        )

@sio.on("sendMessage", namespace="/chat")
async def sendMessage(sid, data):
    async with sio.session(sid, namespace="/chat") as session:
        roomId = session.get("roomId")

        if not roomId or any(
            filter(lambda x: x in data["content"].lower(), badwordsFilter)
        ):
            return await sio.emit(
                "messageDenied",
                {"content": data["content"]},
                to=sid,
                namespace="/chat",
            )

        await sio.emit(
            "messageAccepted",
            {"content": data["content"], "isDelivered": True},
            to=sid,
            namespace="/chat",
        )

        await sio.emit(
            "userMessage",
            {"content": data["content"]},
            room=roomId,
            skip_sid=sid,
            namespace="/chat",
        )

@sio.on("disconnect", namespace="/chat")
async def disconnectRoom(sid):
    async with sio.session(sid, namespace="/chat") as session:
        roomId = session.get("roomId")

        if not roomId:
            return

        await sio.emit("userLeft", room=roomId, skip_sid=sid, namespace="/chat")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)


from typing import Dict, Callable

from kallisticore.lib.action import Action
from kallisticore.lib.credential import Credential
from kallisticore.lib.expectation import Expectation

class PrometheusAction(Action):
    def __init__(self, module_func: Callable, arguments: Dict,
                 expectations: [Expectation] = None,
                 name: str = None, credential: Credential = None):
        super(PrometheusAction, self).__init__(
            module_func=module_func, arguments=arguments,
            expectations=expectations, name=name, credential=credential)

        self.arguments['configuration'] = {
            'prometheus_base_url': arguments.pop('base_url')}

__action_class__ = PrometheusAction

__actions_modules__ = ['chaosprometheus.probes']


import copy
import unittest2

from savanna.conductor import resource as r
from savanna.utils import types

SAMPLE_DICT = {
    'first': [1, 2],
    'second': {'a': 1, 'b': 2}
}

SAMPLE_NESTED_LISTS_DICT = {
    'a': [[{'b': 123}]]
}

SAMPLE_CLUSTER_DICT = {
    'name': 'test-cluster',
    'cluster_configs': {
        'general': {
            'some_overridden_config': 'somevalue'
        }
    },
    'node_groups': [
        {
            'name': 'master',
        },
        {
            'name': 'worker',
            'node_processes': ['tasktracker', 'datanode'],
            'node_configs': {},
            'instances': [
                {
                    'name': 'test-cluster-001',
                    'ip': '1.1.1.1'
                }
            ]
        }
    ]
}

class TestResource(unittest2.TestCase):
    def test_resource_creation(self):
        res = r.Resource(SAMPLE_DICT)

        self.assertIsInstance(res.first, list)
        self.assertEqual(res.first, [1, 2])
        self.assertIsInstance(res.second, r.Resource)
        self.assertEqual(res.second.a, 1)
        self.assertEqual(res.second.b, 2)

    def test_resource_immutability(self):
        res = r.Resource(SAMPLE_DICT)

        with self.assertRaises(types.FrozenClassError):
            res.first.append(123)

        with self.assertRaises(types.FrozenClassError):
            res.first = 123

        with self.assertRaises(types.FrozenClassError):
            res.second.a = 123

    def test_nested_lists(self):
        res = r.Resource(SAMPLE_NESTED_LISTS_DICT)
        self.assertEqual(res.a[0][0].b, 123)

    def test_cluster_resource(self):
        cluster = r.ClusterResource(SAMPLE_CLUSTER_DICT)

        self.assertEqual(cluster.name, 'test-cluster')

        self.assertEqual(cluster.node_groups[0].name, 'master')
        self.assertIsInstance(cluster.node_groups[0], r.NodeGroupResource)
        self.assertEqual(cluster.node_groups[0].cluster.name, 'test-cluster')

        self.assertEqual(cluster.node_groups[1].instances[0].name,
                         'test-cluster-001')
        self.assertIsInstance(cluster.node_groups[1].instances[0],
                              r.InstanceResource)
        self.assertEqual(
            cluster.node_groups[1].instances[0].node_group.name,
            'worker')

    def test_to_dict(self):
        cluster = r.ClusterResource(SAMPLE_CLUSTER_DICT)
        self.assertEqual(cluster.to_dict(), SAMPLE_CLUSTER_DICT)

    def test_to_dict_filtering(self):
        cluster_dict = copy.deepcopy(SAMPLE_CLUSTER_DICT)
        cluster_dict['private_key'] = 'abacaba'
        cluster_dict['node_groups'][0]['id'] = 'some_id'

        cluster = r.ClusterResource(cluster_dict)
        self.assertEqual(cluster.to_dict(), SAMPLE_CLUSTER_DICT)

    def test_to_wrapped_dict(self):
        cluster = r.ClusterResource(SAMPLE_CLUSTER_DICT)
        wrapped_dict = cluster.to_wrapped_dict()
        self.assertEqual(len(wrapped_dict), 1)
        self.assertEqual(wrapped_dict['cluster'], SAMPLE_CLUSTER_DICT)

    def test_init_doesnt_mangle_input(self):
        initial_dict = copy.deepcopy(SAMPLE_CLUSTER_DICT)
        r.ClusterResource(SAMPLE_CLUSTER_DICT)
        self.assertEqual(initial_dict, SAMPLE_CLUSTER_DICT)

    def test_re_init_doesnt_mangle_input(self):
        res = r.ClusterResource(SAMPLE_CLUSTER_DICT)

        changed_dict = copy.deepcopy(SAMPLE_CLUSTER_DICT)
        changed_dict['name'] = 'abcdcwdw'
        changed_dict_copy = copy.deepcopy(changed_dict)

        res.re_init(changed_dict)

        self.assertEqual(changed_dict, changed_dict_copy)

    def test_re_init(self):
        cluster = r.ClusterResource(SAMPLE_CLUSTER_DICT)

        cluster.cluster_configs

        cluster_dict = copy.deepcopy(SAMPLE_CLUSTER_DICT)
        cluster_dict['name'] = 'somenewname'
        del cluster_dict['cluster_configs']

        cluster.re_init(cluster_dict)

        self.assertEqual('somenewname', cluster.name)
        with self.assertRaises(KeyError):
            cluster.cluster_configs
        self.assertEqual(cluster_dict, cluster.to_dict())

    def test_re_init_nested(self):
        cluster = r.ClusterResource(SAMPLE_CLUSTER_DICT)
        ng1_new_dict = copy.deepcopy(SAMPLE_CLUSTER_DICT['node_groups'][1])
        ng1_new_dict['instances'].append({
            'name': 'test_cluster_002',
            'ip': '2.2.2.2'})
        ng1_new_dict['name'] = 'new-ng-name'

        ng1 = cluster.node_groups[1]
        ng1.re_init(ng1_new_dict)

        self.assertEqual(ng1.cluster.name, cluster.name)
        self.assertEqual(cluster.node_groups[1].name, ng1.name)
        self.assertEqual(ng1.to_dict(), ng1_new_dict)


import logging
import os
import pathlib
import subprocess
import time
import uuid

from django.db import models
from django.db.models import IntegerChoices
from django.db.models.signals import pre_delete
from django.dispatch import receiver

from base.base_model import BaseModel
from common.models.User import User
from website.applications.app_factory import AppFactory
from website.applications.core.application import Application
from website.applications.core.dataclass import (
    DataBaseDict,
    MariaDBConfig,
    MySQLDBConfig,
    SSLConfig,
    WebServerTypeEnum,
    WebSiteConfig,
)
from website.models.utils import (
    disable_section,
    enable_section,
    get_section,
    insert_section,
    update_nginx_server_name,
)

nginx_config_example = """
server {
    ########BASIC########

    listen 80;
    listen [::]:80;
    root {dir_path};
    server_name {domain};

    ########BASIC########

    ########SSL########

    #**#listen 443 ssl http2;
    #**#listen [::]:443 ssl http2;
    #**#ssl_certificate      /etc/letsencrypt/live/{domain}/fullchain.pem;
    #**#ssl_certificate_key     /etc/letsencrypt/live/{domain}/privkey.pem;
    #**#ssl_trusted_certificate /etc/letsencrypt/live/{domain}/chain.pem;

    #**#ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    #**#ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    #**#ssl_prefer_server_ciphers on;
    #**#ssl_session_cache shared:SSL:10m;
    #**#ssl_session_timeout 10m;
    #**#error_page 497  https://$host$request_uri;

    ########SSL########

    ########USER########

    ########USER########

}"""

class WebsiteManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().select_related("user")

class WebsiteMethod:
    @staticmethod
    def get_ssl_config_default() -> dict:
        return {
            "certbot": {
                "email": "",
                "provider": None,
            },
            "path": {
                "certificate": "",
                "key": "",
            },
            "method": "http-01",
        }

class WebsiteModel(BaseModel):
    """website model"""

    APP_FACTORY = AppFactory

    class StatusType(IntegerChoices):
        READY = 0, "准备中"
        VALID = 1, "有效"
        SUSPEND = 2, "暂停"
        EXPIRED = 3, "过期"
        DISABLED = 4, "禁用"
        ERROR = 5, "错误"

    class WebServerType(IntegerChoices):
        # WebServerTypeEnum
        # from website.applications.core.dataclass import WebServerTypeEnum
        Nginx = 1
        Apache = 2
        Lighttpd = 3
        IIS = 4
        Tomcat = 5
        Caddy = 6

    user = models.ForeignKey(
        User,
        related_name="user",
        blank=True,
        on_delete=models.CASCADE,
        verbose_name="用户",
    )
    name = models.CharField(verbose_name="名称", max_length=32)
    domain = models.CharField(max_length=1024, verbose_name="域名", unique=True)
    extra_domain = models.CharField(
        max_length=1024,
        null=True,
        blank=True,
        verbose_name="additional domain name",
        help_text='use "," split domain name',
    )
    # 配置说明
    # 证书签发主要依赖于 certbot ，需要定义
    # --preferred-challenges "验证方式"，其中验证方式为
    #   dns-01(自动处理DNS验证，请参考 User Guide https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins,
    #   tls-sni-01 (443端口验证), http (80端口验证)
    # --email "邮件地址"
    # -----------------------------------------------------------------------------------------------------------------|
    # | --server "SERVER"                 The three parameters here mainly define the authentication information       |
    # |                                      of different issuing agencies.                                            |
    # | --eab-kid "EAB_KID"               To be abstracted as an optional field letsencrypt, ZeroSSL,                  |
    # |                                      or a custom issuing authority                                             |
    # | --eab-hmac-key "EAB_HMAC_KEY"     These three items should be in the system configuration, and the user should |
    # |                                      not be differentiated globally.                                           |
    # -----------------------------------------------------------------------------------------------------------------|
    # certbot certonly -n --nginx --agree-tos -m email@gmail.com -d "domain.com"
    # specific reference：https://www.moec.top/archives/2544.
    #
    # ssl_config configuration instructions
    # certbot
    #  - email: Email, required
    #  - server: optional
    # path: The certificate path, the subsequent nginx configuration files will be based on this path
    #  - certificate: fullchain.pem file absolute path
    #  - key: privkey.pem file absolute path
    ssl_config = models.JSONField(
        default=WebsiteMethod.get_ssl_config_default,
        blank=True,
        null=True,
        verbose_name="证书配置",
    )
    ssl_enable = models.BooleanField(default=False, verbose_name="enable SSL")
    index_root = models.CharField(
        default="/var/www/html", max_length=4096, verbose_name="站点目录"
    )
    status = models.IntegerField(
        choices=StatusType.choices,
        default=StatusType.READY,
        verbose_name="状态",
        help_text=StatusType.labels,
    )
    status_info = models.CharField(
        default="", blank=True, null=True, max_length=2048, verbose_name="status info"
    )

    web_server_type = models.IntegerField(
        default=WebServerType.Nginx, choices=WebServerType.choices
    )
    application = models.CharField(max_length=64, verbose_name="application")
    application_config = models.JSONField(
        default=dict, verbose_name="application config"
    )

    valid_web_server_config = models.TextField(
        max_length=102400,
        default=None,
        blank=True,
        null=True,
        verbose_name="valid configuration",
    )

    class Meta:
        unique_together = ["name"]
        verbose_name = "website"
        verbose_name_plural = "websites"

    def __str__(self):
        return self.name

    def get_application(self, app_config: dict = None) -> Application:
        if self.APP_FACTORY.MODULES == {}:
            self.APP_FACTORY.load()
        app = self.APP_FACTORY.get_application_module(
            self.application, self.get_app_website_config(), app_config
        )
        return app

    def or_create_ssl_config(self):
        if self.ssl_config is None or self.ssl_config["certbot"]["email"] == "":
            self.log("debug", f"{self.name} - {self.domain} ssl is first enable.")
            ssl_config = {
                "certbot": {
                    "email": self.user.email,
                    "provider": "default",
                },
                "path": {
                    "certificate": f"/etc/letsencrypt/live/{self.domain}/fullchain.pem",
                    "key": f"/etc/letsencrypt/live/{self.domain}/privkey.pem",
                },
                "method": "http-01",
            }

            ssl_folder = pathlib.Path(f"/etc/letsencrypt/live/{self.domain}")
            if not ssl_folder.exists():
                ssl_folder.mkdir(parents=True, exist_ok=True)

            self.ssl_config = ssl_config

    def get_app_website_config(self) -> WebSiteConfig:
        config = WebSiteConfig(
            domain=self.domain,
            root_dir=self.index_root,
            web_server_type=WebServerTypeEnum.Nginx,
        )

        # Get database config.
        logging.debug(f"get {self.name} - {self.domain} database config.")

        if hasattr(self, "databasemodel") and self.databasemodel:
            from database.models.database import DataBaseModel

            database: DataBaseModel = self.databasemodel
            if database.database_type == database.DBType.MariaDB:
                config.databases = DataBaseDict(
                    mariadb=MariaDBConfig(
                        self.databasemodel.name,
                        self.databasemodel.username,
                        self.databasemodel.password,
                    )
                )
            else:
                config.databases = DataBaseDict(
                    mariadb=MySQLDBConfig(
                        self.databasemodel.name,
                        self.databasemodel.username,
                        self.databasemodel.password,
                    )
                )
        # TODO:Get redis config.

        if self.ssl_enable:
            logging.debug(f"enable {self.name} - {self.domain} ssl toggle.")
            self.or_create_ssl_config()
            config.ssl_config = SSLConfig(
                ssl_certificate_path=self.ssl_config["path"]["certificate"],
                ssl_key_path=self.ssl_config["path"]["key"],
            )
            logging.debug(config.ssl_config.__str__())

        if self.valid_web_server_config is not None:
            config.web_server_config = self.valid_web_server_config

        return config

    def get_application_module(self, config: WebSiteConfig) -> Application:
        app_factory = AppFactory
        app_factory.load()
        return app_factory.get_application_module(self.application, config)

    def is_valid_configuration_001(self) -> subprocess.CompletedProcess:
        logging.info(
            f"001:verify {self.domain} configuration...\n\n{self.valid_web_server_config}"
        )

        minimum_config = f"""user www-data;
              worker_processes auto;
              pid /run/nginx.pid;
              include /etc/nginx/modules-enabled/*.conf;
              events {{
                      worker_connections 768;
              }}

              http {{
                      sendfile on;
                      tcp_nopush on;
                      types_hash_max_size 2048;
                      include /etc/nginx/mime.types;
                      default_type application/octet-stream;
                      ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
                      ssl_prefer_server_ciphers on;
                      gzip on;
                      {self.valid_web_server_config}

              }}
              """

        tmp_config = pathlib.Path(f"/tmp/{uuid.uuid4().hex}.conf")
        tmp_config.write_text(minimum_config)
        cmd = f"nginx -t -c {tmp_config.absolute()}"
        r = subprocess.run(cmd, shell=True, capture_output=True)

        return r

    def is_valid_configuration_002(self, web_server_config) -> bool:
        nginx_config_path = f"/etc/nginx/sites-available/{self.domain}.conf"
        enable_nginx_config_path = f"/etc/nginx/sites-enabled/{self.domain}.conf"

        old_web_server_config = ""
        if pathlib.Path(nginx_config_path).exists():
            with open(nginx_config_path, "r") as f:
                old_web_server_config = f.read()

        with open(nginx_config_path, "w") as f:
            f.write(web_server_config)

        if not pathlib.Path(enable_nginx_config_path).exists():
            os.system(f"ln -s {nginx_config_path} {enable_nginx_config_path}")
        res = os.system("nginx -t")
        if res == 0:
            os.system("systemctl reload nginx")
            return True
        else:
            if old_web_server_config:
                with open(nginx_config_path, "w") as f:
                    f.write(old_web_server_config)
            return False

    def get_nginx_config(self):
        # set domain and ssl path.
        data = nginx_config_example.replace("{domain}", self.domain)

        # set extra domain.
        if self.extra_domain:
            extra_domain = " ".join(self.extra_domain.split(","))
            server_name = f"{extra_domain}"
            data = update_nginx_server_name(data, self.domain, server_name)

        # set nginx root field.
        data = data.replace("{dir_path}", self.index_root)
        # set enter folder.
        app = self.get_application_module(self.get_app_website_config())
        app_config = app.read()
        logging.debug(app_config)
        if hasattr(app_config, "enter_folder_name") and app_config.enter_folder_name:
            old_field = f"root {self.index_root};"
            new_field = f"root {self.index_root}/{app_config.enter_folder_name};"
            if new_field not in data:
                data = data.replace(old_field, new_field)
        # set ssl
        if self.ssl_enable:
            data = enable_section(data, "ssl")
        else:
            data = disable_section(data, "ssl")
        return data

    def get_default_config(self):
        app = self.get_application_module(self.get_app_website_config())
        nginx_data = self.get_nginx_config()
        app_config = app.read()

        if not isinstance(app_config, str):
            app_config = app.read().nginx

        nginx_data = insert_section(nginx_data, app_config, "user")
        return nginx_data

    def sync_web_config(self, save=False):
        data = self.get_nginx_config()
        user_config = get_section(self.valid_web_server_config, "user")
        data = insert_section(data, user_config, "user")
        self.valid_web_server_config = data
        self.is_valid_configuration_002(self.valid_web_server_config)
        if save:
            self.save()


"""silanization of the nanoparticles"""

import re
import sys
import numpy as np
import pandas as pd
import set_masses_name
import write_lmp as wrlmp
import bond_check as bchek
import static_info as stinfo
import make_chains as mkchin
import update_coords as upcord
from colors_text import TextColor as bcolors

class ConcatAll:
    """append all the aminopropyle to the silicon data file"""
    def __init__(self,
                 silica: upcord.UpdateCoords,  # Silica updated
                 aminos: mkchin.PrepareAmino  # Update aminos
                 ) -> None:
        self.Nmols: int  # Number in the data file
        self.NAtoms: int  # Number in the data file
        self.NBonds: int  # Number in the data file
        self.NAngles: int  # Number in the data file
        self.NDihedrals: int  # Number in the data file
        self.NAtomTyp: int  # Number in the data file
        self.NBondTyp: int  # Number in the data file
        self.NAngleTyp: int  # Number in the data file
        self.NDihedralTyp: int  # Number in the data file
        self.concate_all(silica, aminos)
        self.print_infos()
        self.__wrt_si_index(silica.si_df)

    def concate_all(self,
                    silica: upcord.UpdateCoords,  # Silica updated
                    aminos: mkchin.PrepareAmino  # Update aminos
                    ) -> None:
        """concate the all atoms, bonds, angles, diedrlas"""
        self.Atoms_df: pd.DataFrame  # DF in write_lmp format
        self.Atoms_df = self.__concate_atoms(silica.Atoms_df,
                                             aminos.All_amino_atoms)
        self.Bonds_df = self.__concate_bonds(silica.Bonds_df,
                                             aminos.All_amino_bonds)
        self.Angles_df = self.__concate_angles(silica.Angles_df,
                                               aminos.All_amino_angles)
        self.Dihedrals_df = self.__concate_dihedrals(silica.Dihedrals_df,
                                                     aminos.All_amino_dihedrals
                                                     )
        self.Masses_df = self.__concate_masses(silica.Masses_df,
                                               aminos.Masses_df)
        self.max_radius: float = self.__get_max_radius()  # Max radius of NP
        print(f'{bcolors.OKBLUE}{self.__class__.__name__}: '
              f'({self.__module__})\n'
              f'\tConcatenating all the atoms, max radius: '
              f'"{self.max_radius:.3f}"'
              f'{bcolors.ENDC}')
        self.__set_attrs()

    def __concate_atoms(self,
                        silica_atoms: pd.DataFrame,  # Silica atoms
                        aminos_atoms: pd.DataFrame  # Aminos atoms
                        ) -> pd.DataFrame:
        """concate all the atoms, make sure they all have same columns"""
        columns: list[str]  # Name of the wanted columns
        columns = ['atom_id', 'mol', 'typ', 'charge', 'x', 'y', 'z',
                   'nx', 'ny', 'nz', 'cmt', 'name']
        si_df = pd.DataFrame(columns=columns)
        amino_df = pd.DataFrame(columns=columns)
        for col in columns:
            si_df[col] = silica_atoms[col]
            amino_df[col] = aminos_atoms[col]
        df_i: pd.DataFrame  # All atoms dataframe
        df_i = pd.concat([si_df, amino_df], ignore_index=True)
        df_i.index += 1
        del si_df
        del amino_df
        return df_i

    def __concate_bonds(self,
                        silica_bonds: pd.DataFrame,  # Silica bonds
                        aminos_bonds: pd.DataFrame  # Aminos bonds
                        ) -> pd.DataFrame:
        """concate all the bonds in the write_lmp format"""
        columns: list[str]  # Name of the columns
        columns = ['typ', 'ai', 'aj', 'cmt', 'name']
        si_df = pd.DataFrame(columns=columns)
        amino_df = pd.DataFrame(columns=columns)
        for col in columns:
            si_df[col] = silica_bonds[col]
            amino_df[col] = aminos_bonds[col]
        df_i: pd.DataFrame  # All atoms dataframe
        df_i = pd.concat([si_df, amino_df], ignore_index=True)
        df_i.index += 1
        del si_df
        del amino_df
        return df_i

    def __concate_angles(self,
                         silica_angles: pd.DataFrame,  # Silica bonds
                         aminos_angles: pd.DataFrame  # Aminos bonds
                         ) -> pd.DataFrame:
        """concate all the angles in the write_lmp format"""
        columns: list[str]  # Name of the columns
        columns = ['typ', 'ai', 'aj', 'ak']
        si_df = pd.DataFrame(columns=columns)
        amino_df = pd.DataFrame(columns=columns)
        if not aminos_angles.empty:
            for col in columns:
                si_df[col] = silica_angles[col]
                amino_df[col] = aminos_angles[col]
            df_i: pd.DataFrame  # All atoms dataframe
            df_i = pd.concat([si_df, amino_df], ignore_index=True)
            df_i.index += 1
            del si_df
            del amino_df
        else:
            df_i = silica_angles
        return df_i

    def __concate_dihedrals(self,
                            silica_dihedrals: pd.DataFrame,  # Silica bonds
                            aminos_dihedrals: pd.DataFrame  # Aminos bonds
                            ) -> pd.DataFrame:
        """concate all the angles in the write_lmp format"""
        columns: list[str]  # Name of the columns
        columns = ['typ', 'ai', 'aj', 'ak', 'ah']
        si_df = pd.DataFrame(columns=columns)
        amino_df = pd.DataFrame(columns=columns)
        if not aminos_dihedrals.empty:
            for col in columns:
                si_df[col] = silica_dihedrals[col]
                amino_df[col] = aminos_dihedrals[col]
            df_i: pd.DataFrame  # All atoms dataframe
            df_i = pd.concat([si_df, amino_df], ignore_index=True)
            df_i.index += 1
            del si_df
            del amino_df
        else:
            df_i = silica_dihedrals
        return df_i

    def __concate_masses(self,
                         silica_masses: pd.DataFrame,  # Silica masses
                         amino_masses: pd.DataFrame  # Aminos masses
                         ) -> pd.DataFrame:
        """update and make total masses df"""
        columns: list[str] = ['typ', 'mass', 'cmt', 'name']
        df_silica = pd.DataFrame(columns=columns)
        df_amino = pd.DataFrame(columns=columns)
        if 'name' not in silica_masses:
            try:
                silica_masses['name'] = silica_masses['names']
            except KeyError:
                  sys.exit(f'{bcolors.FAIL}\tError!\n There is `name` or '
                           f'`names` column in `silica_masses`\n{bcolors.ENDC}'
                           )
        for col in columns:
            df_silica[col] = silica_masses[col]
            df_amino[col] = amino_masses[col]

        df_c = pd.DataFrame(columns=columns)
        df_c = pd.concat([df_silica, df_amino], ignore_index=True)
        df_c.index += 1
        df_c = set_masses_name.SetMasses(df_c).df_masses
        return df_c

    def __get_max_radius(self) -> float:
        """find the maximum radius of the NP
        Doing it in a simple way, find the maximum of the absolute
        values in each direction and return the maximum one."""
        axis: list[str] = ['x', 'y', 'z']
        max_list: list[float] = []  # All the max along each direction
        for a_x in axis:
            i_max: float = np.max([np.abs(np.max(self.Atoms_df[a_x])),
                                   np.abs(np.min(self.Atoms_df[a_x]))])
            max_list.append(i_max)
        return np.max(max_list)

    def __set_attrs(self) -> None:
        """set attributes to object(self)"""
        self.Nmols = np.max(self.Atoms_df['mol'])
        self.NAtoms = len(self.Atoms_df)
        self.NBonds = len(self.Bonds_df)
        if not self.Angles_df.empty:
            self.NAngles = len(self.Angles_df)
            self.NAngleTyp = np.max(self.Angles_df['typ'])
        else:
            self.NAngles = 0
            self.NAngleTyp = 0
        if not self.Angles_df.empty:
            self.NDihedrals = len(self.Dihedrals_df)
            self.NDihedralTyp = np.max(self.Dihedrals_df['typ'])
        else:
            self.NDihedrals = 0
            self.NDihedralTyp = 0
        self.NAtomTyp = np.max(self.Masses_df['typ'])
        self.NBondTyp = np.max(self.Bonds_df['typ'])

    def print_infos(self) -> None:
        """print info on the stderr"""
        print(f'{bcolors.OKGREEN}\tData Summary after silanization:\n'
              f'\t\t# Atoms: {self.NAtoms}, # Atom`s types: {self.NAtomTyp}\n'
              f'\t\t# Bonds: {self.NBonds}, # Bond`s types: {self.NBondTyp}\n'
              f'\t\t# Angles: {self.NAngles}, '
              f'# Angle`s types: {self.NAngleTyp}\n'
              f'\t\t# Dihedrals: {self.NDihedrals}, '
              f'# Dihedral`s types: {self.NDihedralTyp}\n'
              f'\t\tTotal charge: {self.Atoms_df["charge"].sum():.4f}\n'
              f'\t\tMin charge: {self.Atoms_df["charge"].min()}\n'
              f'\t\tMax charge: {self.Atoms_df["charge"].max()}'
              f'{bcolors.ENDC}'
              )

    def __wrt_si_index(self,
                       si_df: pd.DataFrame  # Si with APTES attach to them
                       ) -> None:
        """write si_df to the file to keep track of SI information"""
        si_df.to_csv(stinfo.DataFile.SI_DF, sep=' ', index=True)
        columns: list[str]  # Columns to write to a different file
        columns = ['atom_id', 'mol', 'typ', 'charge',
                   'x', 'y', 'z', 'name', 'phase']
        si_df.to_csv(stinfo.DataFile.SI_XYZ,
                     sep=' ',
                     index=False,
                     columns=columns)
        print(f'{bcolors.OKBLUE}\tWriting si_df in file in `SI_DF`\n'
              f'\tWriting selected columns of si_df in `SI_XYZ`')

if __name__ == '__main__':
    F_NAME = sys.argv[1]
    update = upcord.UpdateCoords(F_NAME)  # Updated data for silica
    amino_pro = mkchin.GetAmino(stinfo.DataFile.APTES)
    amino_unp = mkchin.GetAmino(stinfo.DataFile.APTUN)
    up_aminos = mkchin.PrepareAmino(update, amino_pro, amino_unp)
    silanized_data = ConcatAll(update, up_aminos)
    CHECK_BOND: bool = False  # To check the bonds
    if CHECK_BOND:
        bchek.CheckBond(silanized_data)
    np_size: int = int(re.findall(r'\d+', F_NAME)[0])
    fout: str = f'silanized_{np_size}nm_g{stinfo.Constants.Coverage}.data'
    wrt = wrlmp.WriteLmp(obj=silanized_data, output=fout)
    wrt.write_lmp()


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

class Production:
		"""Class that represents a production of a grammar"""
		Left=[]
		Right=[]
		def __init__(self,left,right):
			self.Left=left
			self.Right=right

		def getLeftPart(self):
			"""Returns the left part of the production"""
			return self.Left
		def getRightPart(self):
			"""Returns the right part of the production"""
			return self.Right

		def Equals(self,other):
			"""Check if this production is equivalent to other production"""
			return self.Left==other.Left and self.Right==other.Right

		def __str__(self):
			string=''
			for  var in self.Left:
				string+='"'+var+'" '
			string+='-->'

			for  var in self.Right:
				if type(var)==list:
					for unit in var:
						string+='"'+str(unit)+'" '
					string+="|"
				else:
					string+='"'+var+'" '
			return string

		def copy(self):
			"""Copy method for the Production object"""

			if type(self.Left)!=list:
				if type(self.Right)!=list:
					return Production(self.Left,self.Right)
				else:
					return Production(self.Left,self.Right[:])
			else:
				if type(self.Right)!=list:
					return Production(self.Left[:],self.Right[:])

				else:
					return Production(self.Left[:],self.Right)

		def factorize(self):
			"""Factorizes the production"""

			factors=[]
			common=[]

			A=self.Left[0]
			for P in self.Right:
				if A in P:
					factors.append(P.replace(A,''))
					common.append(P)

			for c in common:
				if c in self.Right:
					self.Right.remove(c)

			print(factors)

			if len(factors)>=2:
				self.Right.append(''+' | '.join(factors)+' '+A)

			if len(factors)==1:
				self.Right.append(factors[0]+A)

		def dotInit(self):
			"""Returns a production with a dot at the beginning"""
			c=Production(self.Left[:],self.Right[:])
			c.Right.insert(0,"·")
			# print(c.Right)
			# print(c.Left)
			return c

		def dotAdvance(self):
			"""Returns a production with the dot in the next position"""
			c=Production(self.Left[:],self.Right[:])
			if "·" in c.Right:
				index=c.Right.index("·")
				if index+1<len(c.Right):
					c.Right.insert(index,c.Right[index+1])
					c.Right.pop(index+2)
					# print(c.Right)
					return c

				else:
					print("dot at the end")
					return False

		def dotNextChar(self):
			"""Returns the symbol ath the right of the dot"""
			if "·" in self.Right:
				index=self.Right.index("·")
				if index+1<len(self.Right):
					return self.Right[index+1]
				else:
					return ""
			else:
				return False

		def getDotAlpha(self):
			"""Returns the symbol at the left of the dot"""
			if "·" in self.Right:
				index=self.Right.index("·")
				if index>0:
					return self.Right[index-1]
				else:
					return""
			else:
				return False

		def getDotBetha(self):
			"""Returns the symbol at the second position at the right of the dot"""
			if "·" in self.Right:
				index=self.Right.index("·")
				if index+2<len(self.Right):
					return self.Right[index+2]
				else:
					return ""
			else:
				return False

		def getDotIndex(self):
			"""Returns the index of the dot in the production"""
			if "·" in self.Right:
				return self.Right.index("·")
			else:
				return -1


import winsound
import time

def playsound(word):
    ting = list(word)
    h=0
    for i in ting:
      word = ting[h]
      h = h+1
      if word == "-":
          print("long beep")
          winsound.Beep(500, 300)
      elif word ==".":
          print("short beep")
          winsound.Beep(500, 75)
      elif word =='/':
          print("space")
          winsound.Beep(37,700)
      else:
        print("not owkring")

morse_code_dict = { 'A':'.-', 'B':'-...',
                    'C':'-.-.', 'D':'-..', 'E':'.',
                    'F':'..-.', 'G':'--.', 'H':'....',
                    'I':'..', 'J':'.---', 'K':'-.-',
                    'L':'.-..', 'M':'--', 'N':'-.',
                    'O':'---', 'P':'.--.', 'Q':'--.-',
                    'R':'.-.', 'S':'...', 'T':'-',
                    'U':'..-', 'V':'...-', 'W':'.--',
                    'X':'-..-', 'Y':'-.--', 'Z':'--..',
                    '/':'/'
                    }

userInp = input("write a word: ").upper()
userInp1 = list(userInp)
print(userInp1)

x=0
print(len(userInp1))
for i in userInp1:
    word1 = morse_code_dict[userInp1[x]]
    print(userInp1[x])
    print(word1)
    playsound(word1)
    x = x+1
    time.sleep(1)
    print("\n")


"""Metrics base."""
import abc
from dataclasses import dataclass
from typing import Tuple

import tensorflow as tf

class PerformanceMetrics(tuple):
    """A set of performance metrics.

    NOTE:
    As python versions older than 3.9 does not support using
    tuple as a generic type hint, we still need to use typing.Tuple.
    Then the following does not work as an initializer:
        PerformanceMetrics = Tuple[tf.keras.metrics.Metric, ...]
    Therefore, this class is a wrapper around tuple, working both
    as a type hint and a type, until python version is updated.
    """

    def __new__(cls, *args: tf.keras.metrics.Metric):
        """Construct an instance."""
        assert all(isinstance(arg, tf.keras.metrics.Metric) for arg in args)
        return args

@dataclass(frozen=True)
class ObjectiveTerm:
    """A loss term in the loss formulation."""

    loss_func: tf.keras.losses.Loss
    loss_metric: tf.keras.metrics.Mean
    weight: float

    @classmethod
    def build(cls, name: str, loss_func: tf.keras.losses.Loss, weight: float = 1.0):
        """Create an objective term."""
        return cls(
            loss_func=loss_func, loss_metric=tf.keras.metrics.Mean(name), weight=weight
        )

@dataclass(frozen=True)
class ObjectiveFormulation:
    """A neural network loss formulation."""

    terms: Tuple[ObjectiveTerm]
    cumulative_loss_metric: tf.keras.metrics.Mean

    def calculate(self, labels, predictions):
        """Calculate the loss value given labels and predictions."""
        losses = []
        for objective_term in self.terms:
            loss = objective_term.loss_func(labels, predictions)
            objective_term.loss_metric(loss)
            losses.append(loss)

        cumulative_loss = tf.reduce_sum(
            tf.math.multiply(
                losses,
                [term.weight for term in self.terms],
            )
        )
        self.cumulative_loss_metric(cumulative_loss)
        return cumulative_loss

class Objective(abc.ABC):
    """Interface class for losses and performance metrics."""

    def __init__(self):
        """Create an objective."""
        self._objective_formulation = self._build_objective_formulation()
        self._performance_metrics = self._build_performance_metrics()

    def __call__(self, labels, predictions):
        """Calculate the cumulative loss value of labels and predictions."""
        cumulative_loss = self._objective_formulation.calculate(labels, predictions)

        for metric in self._performance_metrics:
            metric(labels, predictions)

        return cumulative_loss

    @property
    def formulation(self) -> ObjectiveFormulation:
        """Get the loss formulation."""
        return self._objective_formulation

    @property
    def performance_metrics(self) -> PerformanceMetrics:
        """Get the performance metric."""
        return self._performance_metrics

    @abc.abstractmethod
    def _build_objective_formulation(self) -> ObjectiveFormulation:
        pass

    @abc.abstractmethod
    def _build_performance_metrics(self) -> PerformanceMetrics:
        pass


"""Implementations of different loss functions or loss utilities in PyTorch."""

import torch

def reinforce(loss, logits, baseline):
    """Return the simple REINFORCE loss with a baseline.

    NOTE: This does not add the loss tensor to the returned loss so make sure
          to add it separately!

    Arguments
    ---------
        loss: The tensor that contains the per-sample loss
        logits: The tensor that contains the per-sample logits
        baseline: The tensor that contains the baseline loss used to reduce the
                  variance of the gradient estimator
    """
    B = loss.shape[0]
    assert loss.shape == (B,) or loss.shape == (B, 1)
    assert baseline.numel() == 1
    assert logits.shape[0] == B

    return (
        (loss.view(-1, 1) - baseline.view(-1)).detach() * logits.view(B, -1)
    ).mean(1)

class Reinforce(torch.nn.Module):
    """Compute the simple REINFORCE loss with a exponential moving average
    baseline.

    Arguments
    ---------
        alpha: float, the parameter for the exponential moving
               average (default: 0.9)
    """
    def __init__(self, alpha=0.9):
        super().__init__()

        self.alpha = alpha
        self.baseline = None

    def forward(self, loss, logits):
        if self.baseline is None:
            self.baseline = torch.zeros(1, device=loss.device)
            with torch.no_grad():
                self.baseline[...] = loss.mean()

        rloss = reinforce(loss, logits, self.baseline)
        with torch.no_grad():
            self.baseline[...] = (
                self.alpha * self.baseline +
                (1-self.alpha)*loss.mean()
            )

        return rloss


import re
def reading_list(way):
    text = open(way, 'r', encoding = 'utf-8')
    text1 = text.read()
    text1 = text1.lower()
    text1 = text1.replace('\n', ' ')
    text1 = text1.replace('\t', ' ')
    for smth in range(0,10):
        text2 = text1.replace('  ', ' ')
    text_list = text2.split(' ')
    text.close()
    text_list1 = []
    for sym in text_list:
        sym = sym.strip('!.,?;:{}[]()<>:+_-"–=*/\ ' )
        if sym != '' or sym != ' ':
            text_list1.append(sym)
    return text_list1

def searching_forms(words):
    forms = []
    for element in words:
        word_bordered = '<'+element+'>' #в этом месте я предпринял все попытки заставить программу находить ТОЛЬКО правильные формы
        if re.search('<откр((((о(й|ют|е(шь|м|т))|ы((ть|л)\
|(вш((и(е|й|х|ми?))|(е(е|го|му?))|ую|ая))))(ся)?)|(((о(ю|\
(й|е)те))|(ыл(а|и|о)))(сь)?)|(ыв(шись)?))|((ыт(ы(й|е|х|ми?\
)|ая|о(й|е|го|му?)|ую))))>', word_bordered):
            if element not in forms:
                forms.append(element)
    return forms

def main():
    print('\nMATVEY SOKOLOVSKIY   GROUP:152   HOMEWORK 8   VARIANT:1\n')
    way = input('введите название текстового файла (после этого желательно скопировать): ')
    try:
        val = reading_list(way)
        val1 = searching_forms(val)
        print('формы глагола "открыть" встречающиеся в документе:\n')
        for element in val1:
            print(element)
    except FileNotFoundError:
        print('извините, файл не найден')

if __name__ == '__main__':
    main()


class Category:

    def __init__(self, name):
        self.ledger=[]
        self.name = name

    def display(self):
        title=""+self.name
        while len(title)<30:
            title="*"+title+"*"
        title+="\n"
        for x in self.ledger:
            for value in x.values():
                if len(str(value))>23:
                    title+= (str(value))[:23]
                else:
                   title+= (str(value).ljust(23, ' '))
            title+="\n"
        balance = self.get_balance()
        title += f"Total: {balance}"
        return title

    def deposit(self, amount, description= ""):
        dict_deposit= {"amount": amount, "description": description}
        self.ledger.append(dict_deposit)
        return amount

    def withdraw(self, amount, description = ""):
        if self.check_funds(amount):
            item = {"amount": -amount, "description": description}
            self.ledger.append(item)
            return True
        return False

    def get_balance(self):
        balance = 0
        for x in self.ledger:
            balance += float(x["amount"])
        return balance

    def transfer(self, amount, category):
        if self.check_funds(amount):
            self.withdraw(amount, f"Transfer to {category.name}")
            category.deposit(amount, f"Transfer from {self.name}")
            return True
        return False

    def check_funds(self, amount):
            if amount > self.get_balance():
                return False
            return True

    def __repr__(self):
        return f"({self.name})"

def create_spend_chart(category1, category2, category3):
    print("Percentage spent by category")
    category_money_spend1= []
    category_money_spend2= []
    category_money_spend3= []
    #enter in categories to find dictionary
    for y in category1.ledger:
        for value in y.values():
            for character in str(value):
                if str(character).isdigit()==True and value not in category_money_spend1:
                    category_money_spend1.append(value)
    cost1= sum(category_money_spend1[1:])
    total1=-(category_money_spend1[0]//cost1)
    #enter in categories to find dictionary
    for y in category2.ledger:
        for value in y.values():
            for character in str(value):
                if str(character).isdigit()==True and value not in category_money_spend2:
                    category_money_spend2.append(value)
    cost2= sum(category_money_spend2[1:])
    total2=-(category_money_spend2[0]//cost2)
    #enter in categories to find dictionary
    for y in category3.ledger:
        for value in y.values():
            for character in str(value):
                if str(character).isdigit()==True and value not in category_money_spend3:
                    category_money_spend3.append(value)
    cost3= sum(category_money_spend3[1:])
    total3=-(category_money_spend3[0]//cost3)
    x=100
    while x>=0:
        if x==100:
            output=f"{x}| "
        elif x==0: output=f"  {x}| "
        else: output=f" {x}| "
        if total1>x:
            output+=" °"
        else: output+="  "
        if total2>x:
            output+=" °"
        else: output+="  "
        if total3>x:
            output+=" °"
        else: output+="  "
        x-=10
        print(output)
    print("    -------")

#test
if __name__ == "__main__":
    food=Category("food")
    food.deposit(1000, "initial deposit")
    food.withdraw(10.15, "groceries")
    food.withdraw(15.89, "restaurant and more food for dessert")
    print(food.display())
    clothing = Category("Clothing")
    food.transfer(50, clothing)
    clothing.withdraw(25.55)
    clothing.withdraw(100)
    auto = Category("Auto")
    auto.deposit(1000, "initial deposit")
    auto.withdraw(15)
    print(clothing.display())
    print(auto.display())

    create_spend_chart(food, clothing, auto)


import numpy as np

def SaveToFile(fileName, date):
    with(open(fileName+".txt", "w")) as f:
        if fileName == "measursment_list":
            for i in date:
                f.write(str(i[0]) + " " + str(i[1])+ " " + str(i[2]) + " " + str(i[3])+ "\n")
        else:
            nr = len(date)
            for i in range(0, nr):
                for d in date[i]:
                    f.write(str(d[0]) + " " + str(d[1])+ ";")
                f.write("\n")

def ReadFromFile(fileName, location):
    with(open(location + "\\" + fileName + ".txt", "r")) as f:
        point_x = []
        point_y = []
        if fileName == "measursment_list":
            for line in f:
                temp = line.split(' ')
                point_x.append(temp[0])
                point_y.append(temp[1])
                print(line)
            return point_x, point_y
        else:
            for line in f:
                temp = line.split(';')
                for point in temp:
                    res = point.split(' ')
                    point_x.append(res[1] * np.cos(np.radians(res[0])) + p_x[nr])
                    point_y.append(res[1] * np.sin(np.radians(res[0])) + p_y[nr])


import random

# random_integer = random.randint(1, 10)
# print(random_integer)
#
# # 0.000000... - 0.999999...
# random_float = random.random()
# print(random_float)
#
# #0.000... - 4.999...
# random_float = random_float * 5
# print(random_float)
#
# love_score = random.randint(1, 100)
# print(f"Your love socre is {love_score}")

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

# states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland",
#                      "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island"]
#
# print(states_of_america[3])
# print(states_of_america[-3])
#
# states_of_america[1] = "pencilvania"
#
# states_of_america.append("Angelaland")
# states_of_america.extend(["Jack Bauer Land", "Apololand"])
#
# print(states_of_america)

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

# states_of_america = ["Delaware", "Pennsylvania", "New Jersey", "Georgia", "Connecticut", "Massachusetts", "Maryland",
#                      "South Carolina", "New Hampshire", "Virginia", "New York", "North Carolina", "Rhode Island"]
#
# num_of_states = len(states_of_america)
#
# print(states_of_america[num_of_states - 1])

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

# dirty_dozen = ["Strawberries", "Spinach", "Kale", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears",
#                "Tomatoes", "Celery", "Potatoes"]

fruits = ["Strawberries", "Nectarines", "Apples", "Grapes", "Peaches", "Cherries", "Pears"]
vegetables = ["Spinach", "Kale", "Tomatoes", "Celery", "Potatoes"]

dirty_dozen = [fruits, vegetables]

print(dirty_dozen)

print(dirty_dozen[1][1])

100 Days Of Code/Day 4 - Begginer - Randomisation and Python Lists/classroom_tables/day-4-end.py


#!/usr/bin/python
#coding=utf-8

"""
auth: wuqichao、suguoxin
mail: wuqichao@playcrab.com、suguoxin@playcrab.com
create_time: 2015-9-17 10:00:00
usege: 用于hadoop下载文件任务操作

last_update: 2016-04-28 14:45:00
"""

from __future__ import absolute_import
import os

from download.celery import app
from custom.command import Custom_Command as cmd
from custom.db.mysql import Custom_MySQL
from custom.db.redis_tools import Custom_Redis
from celery.utils.log import get_task_logger

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

logger = get_task_logger(__name__)

'''
hadoop服务器集群中启动下载任务程池，由此脚本完成
'''
@app.task(bind=True, max_retries=5, default_retry_delay=6, soft_time_limit=270, time_limit=280)
def run_task(self, task_param):

    redis = Custom_Redis(using='etl_manage')
    mysql = Custom_MySQL(using='etl_manage')
    mysql.begin()
    datas = {'download_status': 0}
    where = {'id': int(task_param['id'])}

    local_log_dir = ""
    lzo_file_name = ""

    try:
        dir_param = {'game': task_param['game'], 'platform': task_param['platform'],
                     'log_date': task_param['log_date'], 'log_name': task_param['log_name']}
        filename_dict = {'log_name': task_param['log_name'], 'log_time': task_param['log_time'], 'source_ip': task_param['source_ip']}
        log_dir = "/%(game)s/%(platform)s/%(log_date)s/%(log_name)s/" % dir_param

        txt_file_name = "%(log_name)s_%(source_ip)s_%(log_time)s.txt" % filename_dict
        lzo_file_name = "%(log_name)s_%(source_ip)s_%(log_time)s.txt.lzo" % filename_dict
        md5_file_name = "%(log_name)s_%(source_ip)s_%(log_time)s.txt.lzo.md5" % filename_dict

        lzo_download_url = task_param['download_url'].rstrip('/') + log_dir + lzo_file_name
        md5_download_url = task_param['download_url'].rstrip('/') + log_dir + md5_file_name

        #从redis中，获取当前数据对应存储到哪块磁盘
        if redis.get("disk_xml") is None:
            disk_tmp = open('/data/etl_manage/conf/disk_game.xml', 'r')
            redis.set("disk_xml", str(disk_tmp.read()))

        disk_list = str(redis.get("disk_xml"))
        root = ET.fromstring(disk_list)
        disk = ""
        for gameinfo in root.findall('game'):
            if gameinfo.get('name') == task_param['game']:
                disk = gameinfo.get('disk')
                continue

        #local_log_dir = '/disk1/tmp_data' + log_dir
        local_log_dir = '/'+disk+'/data' + log_dir
        #创建本地目录
        if not os.path.exists(local_log_dir):
            os.makedirs(local_log_dir)

        #排除同名文件存在的可能，同时为修复执行提供方便
        if os.path.exists('%s%s' % (local_log_dir, txt_file_name)):
            cmd_remove = 'rm -f %s%s*' % (local_log_dir, txt_file_name)
            logger.info('remove history file: {0}'.format(cmd_remove))
            remove_result = cmd.run(cmd_remove)
            if remove_result['status'] != 0:
                logger.error('Error Code %s : %s  Cmd: %s' % (remove_result['status'], remove_result['output'], cmd_remove))

        '''
        下载md5文件,如果md5文件不存在则退出，不再继续执行程序，同时不向数据库写入任何标示
        '''
        md5_line = ' wget -o /tmp/log/wget_log -O %s%s %s' % (local_log_dir, md5_file_name, md5_download_url)
        logger.info('md5 info: {0}'.format(md5_line))
        md5_result = cmd.run(md5_line)

        if md5_result['status'] != 0:
            logger.error('Error Code %s : %s  Cmd: %s' % (md5_result['status'], md5_result['output'], md5_line))

        else:
            '''
            将任务标识为开始执行：1
            '''
            datas['download_status'] = 1
            mysql.update('etl_data_log', ' id = %(id)d' % where, **datas)
            mysql.commit()

            '''
            下载数据文件
            '''
            lzo_line = ' wget -o /tmp/log/wget_log -O %s%s %s' % (local_log_dir, lzo_file_name, lzo_download_url)
            logger.info('file info: {0}'.format(lzo_line))
            lzo_result = cmd.run(lzo_line)

            if lzo_result['status'] != 0:
                logger.error('Error Code %s : %s  Cmd: %s' % (lzo_result['status'], lzo_result['output'], lzo_line))
                datas['download_status'] = 0
            else:
                '''
                将任务标识为下载完成：2
                '''
                datas['download_status'] = 2
                mysql.update('etl_data_log', ' id = %(id)d' % where, **datas)
                mysql.commit()

                '''
                md5校验，如果未通过则不再继续执行程序
                '''
                check_line = "cat %s%s |grep `md5sum %s%s|cut -d ' ' -f 1`" % (local_log_dir, md5_file_name, local_log_dir, lzo_file_name)
                logger.info('md5 or md5 info: {0}'.format(check_line))
                check_result = cmd.run(check_line)

                if check_result['status'] != 0:
                    logger.error('Error Code %s : %s Cmd: %s' % (check_result['status'], check_result['output'], check_line))
                    datas['download_status'] = 0
                else:
                    '''
                    lzop解压缩
                    '''
                    cmd_line = ' lzop -dP %s%s' % (local_log_dir, lzo_file_name)
                    logger.info('file info: {0}'.format(cmd_line))
                    cmd_result = cmd.run(cmd_line)
                    if cmd_result['status'] != 0:
                        logger.error('Lzop Code %s : %s Cmd: %s' % (cmd_result['status'], cmd_result['output'], cmd_line))
                        datas['download_status'] = 0
                    else:
                        '''
                        将任务标识md5一致，完成下载任务：3
                        '''
                        datas['download_status'] = 3

        '''
        将任务标示为：(模拟) 已从任务队列中移除
        '''
        datas['in_download_queue'] = 0
        update_result = mysql.update('etl_data_log', ' id = %(id)d' % where, **datas)
        # 如果更新失败，则再调用一次，如果还是失败，则等待自动修复机制，但这种概率很小了
        if update_result != 1:
            mysql.update('etl_data_log', ' id = %(id)d' % where, **datas)

        mysql.commit()
        mysql.close()
        return True

    except Exception as exc:
        print (exc)
        logger.error('download error : %s' % exc)
        mysql.rollback()

        kill_proces = "kill -9 `ps -ef |grep wget |grep -v grep |grep '%s%s'|awk '{print $2}'`" % (local_log_dir, lzo_file_name)
        cmd.run(kill_proces)

        datas = {'in_download_queue': 0, 'download_status': 0}
        mysql.update('etl_data_log', ' id = %(id)d' % where, **datas)
        mysql.commit()

        mysql.close()
        raise self.retry(exc=exc, countdown=60)


import requests
from lxml import html
import json
import time
import random
import hashlib
import sys

sys.path.insert(0, '/home/chaos/PycharmProjects/Crawler')
from page import user_agent

movie_index = 3878007
sortkey = "new_score"

def get_one_page(url, retry=0):
    while retry >= 0:
        headers = {
            'User-Agent':user_agent.UserAgents.get_agent()
        }

        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        elif retry == 0:
            print("==> response code : " + str(response.status_code))
            return None

        time.sleep(3)
        retry -= 1

def parse_one_page(html):

    data = json.loads(html)['cmts']

    for item in data:
        yield{
            'comment': item['content'],
            'date': item['time'].split(' ')[0],
            'rate': item['score'],
            'city': item['cityName'],
            'nickname': item['nickName']
        }

def save_to_txt(filename):
    with open(filename, 'w+', encoding='utf-8') as f:
        uniq_list = []
        md5str = ''
        md5str.encode(encoding='utf-8')

        i = 0
        while i < 1001:
            i += 1
            url = 'http://m.maoyan.com/mmdb/comments/movie/1216365.json?_v_=yes&offset=' + str(i)
            html = get_one_page(url)
            print('saving %d page' % i)

            for item in parse_one_page(html):
                md5str = hashlib.md5(item['comment'].encode(encoding='utf-8')).hexdigest()

                if md5str not in uniq_list:
                    print(item['date'] + ',' + item['city'] + ',' + item['nickname'] + ',' + str(item['rate'])+','+item['comment'])
                    f.write(item['date'] + ',' + item['city'] + ',' + item['nickname'] + ',' + str(item['rate'])+','+item['comment']+'\n')
                    uniq_list.append(md5str)

            if len(uniq_list) > 10000:
                        uniq_list.clear()

            time.sleep(1 + float(random.randint(1, 100)) / 50)

def get_user_location(urls):
    locations = []
    for url in urls:
        page = get_one_page(url, 5)

        if page is None:
            locations.append("secrect")
            continue

        tree = html.fromstring(page)
        t = tree.xpath('//div[@class="user-info"]/a/text()')
        if len(t) > 0:
            locations += t
        else:
            locations.append("secrect")

        time.sleep(1 + float(random.randint(1, 50) / 50))
    return locations

def fetch_douban(filename):
    step = 20
    page_index = -1

    url_prefix = 'https://movie.douban.com/subject/' + str(movie_index) + '/comments?start='
    with open(filename, 'w+', encoding='utf-8') as f:
        while page_index < 1500:
            page_index += 1
            url = url_prefix + str(page_index*step) + '&limit= 20&sort='+ sortkey +'&status=P'
            url2 = 26985127
            page = get_one_page(url, 5)
            if page is None:
                continue
            tree = html.fromstring(page)

            names = tree.xpath('//div[@class="avatar"]/a/@title')
            comment_times = tree.xpath('//span[@class="comment-info"]/span[last()]/@title')
            locations = get_user_location(tree.xpath('//div[@class="avatar"]/a/@href'))
            comments = tree.xpath('//span[@class="short"]/text()')

            print("==> page " + str(page_index) + ", names: " + str(len(names)) + ", comment_times: " + str(len(comment_times)) + ", locations: " + str(len(locations)) + ", comments: " + str(len(comments)))
            for i in range(0, step - 1):
                print(comment_times[i] + ', ' + names[i] + ', ' + locations[i] + ', ' + comments[i] + '\n')
                f.write(comment_times[i] + ', ' + names[i] + ', ' + locations[i] + ', ' + comments[i] + '\n')

if __name__ == '__main__':
    movie_index = int(sys.argv[1])
    fetch_douban(sys.argv[2])


from pyxmolpp2 import PdbFile, rId, Frame, ResidueId, mName, rName
import os

# specify mutant complexes for renumbering
mutants = ["wt+mp3", "alpha+mp3", "delta+mp3", "delta_plus+mp3", "omicron+mp3", "delta_p+mp3_d37r", "delta_p+mp3_d37r_t10w"]

# read rcsb reference structure
path_to_rcsb_ref = "../../0_prepare_structures/structures/7jzm.pdb"
rcsb_model = PdbFile(path_to_rcsb_ref).frames()[0]
rcsb_molnames = [mol.name for mol in rcsb_model.molecules.filter(mName.is_in("A", "B"))]

for mutant in mutants:
    # read ref trj pdb
    path_to_trj_ref = f"../../2_MD_Amber/{mutant}/0_prepare/protein.pdb"
    trj_ref = PdbFile(path_to_trj_ref).frames()[0]
    trj_ref_mols = [rcsb_model.molecules.filter(mName == mol_name)[0] for mol_name in rcsb_molnames]

    # specify output
    out_dir = f"../../2_MD_Amber/{mutant}/0_prepare/"
    out_name = "protein_named.pdb"

    # create Frame
    new_frame = Frame()

    for ind_mol, mol_rcsb in enumerate(rcsb_model.molecules.filter(mName.is_in("A", "B"))):

        # create Molecule
        new_frame.add_molecule()
        new_molecule = new_frame.molecules[ind_mol]
        new_molecule.name = mol_rcsb.name

        for ind_res, (res_rcsb, res_trj_ref) in enumerate(zip(mol_rcsb.residues, trj_ref.molecules[ind_mol].residues)):
            # create Residue
            new_molecule.add_residue()
            new_residue = new_molecule.residues[ind_res]
            new_residue.name = res_trj_ref.name
            new_residue.id = res_rcsb.id

            for ind_atom, atom_trj_ref in enumerate(res_trj_ref.atoms):
                # create Atom
                new_residue.add_atom()
                new_atom = new_residue.atoms[ind_atom]
                new_atom.name = atom_trj_ref.name
                new_atom.id = atom_trj_ref.id
                new_atom.r = atom_trj_ref.r

    print(new_frame)
    os.makedirs(out_dir, exist_ok=True)
    new_frame.to_pdb(os.path.join(out_dir, out_name))

    del new_frame