import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

type_of_feature = "mwmd"

# per album heatmap
mwmd = pd.read_csv(f"general_results_mwmd.csv")
mse = pd.read_csv(f"general_results_mse.csv")
spec_flux = pd.read_csv(f"general_results_spectral_flux.csv")

feature_to_plot = "False Negatives"

mwmd["Accuracy"] = mwmd["True Positives"] / mwmd["Total beats"]
mwmd["F1-Score"] = 2*mwmd["True Positives"] / (2*mwmd["True Positives"] + mwmd["False Negatives"] + mwmd["False Positives"])
mwmd["Rush plus drag"] = mwmd["Drag mean"] + mwmd["Rush mean"]

mse["Accuracy"] = mse["True Positives"] / mse["Total beats"]
mse["F1-Score"] = 2*mse["True Positives"] / (2*mse["True Positives"] + mse["False Negatives"] + mse["False Positives"])
mse["Rush plus drag"] = mse["Drag mean"] + mse["Rush mean"]

spec_flux["Accuracy"] = spec_flux["True Positives"] / spec_flux["Total beats"]
spec_flux["F1-Score"] = 2*spec_flux["True Positives"] / (2*spec_flux["True Positives"] + spec_flux["False Negatives"] + spec_flux["False Positives"])
spec_flux["Rush plus drag"] = spec_flux["Drag mean"] + spec_flux["Rush mean"]

names = ["MSE", "Spectral Flux", "MWMD"]

mwmd_val = mwmd[feature_to_plot].mean()
mse_val = mse[feature_to_plot].mean()
spec_flux_val = spec_flux[feature_to_plot].mean()

plt.plot(names, [mse_val, spec_flux_val, mwmd_val])
plt.ylabel(feature_to_plot)
plt.savefig(f"plots/{feature_to_plot}_comparative.png")
plt.close()


from random import randrange, choice
from math import floor, ceil

OPERATORS = ["+","-","*"]

class TreeNode:

    def __init__(self, left, right, operator):
        self.left = left
        self.right = right
        self.operator = operator

    def __str__(self) -> str:
        return str(self.left) + " " + self.operator + " " + str(self.right)

def generate_equation(numNodes, maxNumber=10):
    if numNodes == 1:
        return randrange(maxNumber-10, maxNumber)

    numLeft = floor(numNodes / 2)
    leftSubTree = generate_equation(numLeft, maxNumber)
    numRight = ceil(numNodes / 2)
    rightSubTree = generate_equation(numRight, maxNumber)

    op = choice(OPERATORS)

    return TreeNode(leftSubTree, rightSubTree, op)

if __name__ == "__main__":
    print(str(generate_equation(3)))


# Zachary Hoover || Create Formated File v1.0
# 10-17-22

import shutil
from datetime import datetime

template = r'baseTemplate.py'

print("\n    File Creator")
print(" --------+---------   \n")
fileName = input(" Enter the name of the file: ")
AssignmentName = input(" Enter the assignment title: ")
path = input(" Enter file path(leave blank for current dir): ")

if path == "":
    path = (fileName + ".py")

shutil.copyfile(template, path)

with open(path, 'r') as file :
  filedata = file.read()

date = datetime.today().strftime('%m-%d-%y')
# Replace the target string
filedata = filedata.replace('{date}', date)
filedata = filedata.replace('{assignmentName}', AssignmentName)
filedata = filedata.replace('# import {moduleName} as foo', f"import {fileName} as foo")
filedata = filedata.replace('# {list = getmembers(foo, isfunction)}', "list = getmembers(foo, isfunction)")

header = r"\n    " + AssignmentName + r"   "
filedata = filedata.replace('{assignmentTitle}', header)
bottom = r" "

i = 0
while i < (len(header)/2):
	bottom += r"-"
	i += 1
bottom += r"+"
i = 0
while i < (len(header)/2):
	bottom += r"-"
	i += 1

filedata = filedata.replace('{dashThing}', bottom)

# Write the file out again
with open(path, 'w') as file:
  file.write(filedata)


import time

from tensorflow.core.lib.core import error_codes_pb2
from tensorflow.python.compat import v2_compat
from tensorflow.python.distribute import multi_process_runner
from tensorflow.python.distribute import multi_worker_test_base
from tensorflow.python.distribute import parameter_server_strategy_v2
from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib
from tensorflow.python.distribute.coordinator import cluster_coordinator
from tensorflow.python.distribute.coordinator import utils
from tensorflow.python.eager import context
from tensorflow.python.eager import test
from tensorflow.python.framework import errors
from tensorflow.python.training import server_lib

_PULL_FREQ_IN_SEC = 2
_COORDINATION_ERROR_PAYLOAD_KEY = (
    "type.googleapis.com/tensorflow.CoordinationServiceError"
)

class GetTaskStatesTest(object):  # pylint: disable=missing-docstring

  def setUp(self, num_workers, num_ps):
    super().setUp()

    self._cluster = multi_worker_test_base.create_multi_process_cluster(
        num_workers=num_workers, num_ps=num_ps, rpc_layer="grpc")
    self._cluster_def = self._cluster.cluster_resolver.cluster_spec().as_dict()
    self._cluster_def["chief"] = [
        "localhost:%d" % multi_worker_test_base.pick_unused_port()
    ]
    cluster_resolver = cluster_resolver_lib.SimpleClusterResolver(
        server_lib.ClusterSpec(self._cluster_def), rpc_layer="grpc")

    context.context().configure_coordination_service(
        service_type="standalone",
        service_leader="/job:ps/replica:0/task:0",
        heartbeat_timeout_in_ms=_PULL_FREQ_IN_SEC * 1000,
        allow_new_incarnation_to_reconnect=True)
    self.strategy = parameter_server_strategy_v2.ParameterServerStrategyV2(
        cluster_resolver)
    self.cluster_coord = cluster_coordinator.ClusterCoordinator(self.strategy)

    self.num_workers = num_workers
    self.num_ps = num_ps

    self.states = None
    self.polling_thread = utils.RepeatedTimer(
        interval=_PULL_FREQ_IN_SEC, function=self.get_task_states)

  def tearDown(self):
    super().tearDown()
    self.polling_thread.stop()
    self._cluster.stop()
    self._cluster = None

  def get_task_states(self):
    self.states = context.context().get_task_states([("worker",
                                                      self.num_workers),
                                                     ("ps", self.num_ps)])

  def testAllTasksHealthy(self):
    time.sleep(_PULL_FREQ_IN_SEC * 1.5)
    self.assertLen(self.states, self.num_workers + self.num_ps)
    for state in self.states:
      self.assertIsNone(state)

  def testWorkerPreempted(self):
    self._cluster.kill_task("worker", 0)
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    self.assertLen(self.states, self.num_workers + self.num_ps)
    self.assertIsInstance(self.states[0], errors.UnavailableError)
    self.assertIn("/job:worker/replica:0/task:0", self.states[0]._message)
    self.assertEqual(self.states[0]._error_code, error_codes_pb2.UNAVAILABLE)
    self.assertIn(_COORDINATION_ERROR_PAYLOAD_KEY,
                  self.states[0]._experimental_payloads)
    for i in range(1, self.num_workers + self.num_ps):
      self.assertIsNone(self.states[i])
    self._cluster.start_task("worker", 0)
    context.context().update_server_def(context.get_server_def())
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    for state in self.states:
      self.assertIsNone(state)

  def testPSPreempted(self):
    self._cluster.kill_task("ps", 1)
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    self.assertLen(self.states, self.num_workers + self.num_ps)
    state_ix = self.num_workers + 1
    self.assertIsInstance(self.states[state_ix], errors.UnavailableError)
    self.assertIn("/job:ps/replica:0/task:1", self.states[state_ix]._message)
    self.assertEqual(self.states[state_ix]._error_code,
                     error_codes_pb2.UNAVAILABLE)
    # Simulate the restart of all the tasks.
    self._cluster.kill_task("ps", 0)
    for index in range(2, self.num_ps):
      self._cluster.kill_task("ps", index)
    for index in range(self.num_workers):
      self._cluster.kill_task("worker", index)
    for index in range(self.num_ps):
      self._cluster.start_task("ps", index)
    for index in range(self.num_workers):
      self._cluster.start_task("worker", index)
    context.context().update_server_def(context.get_server_def())
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    self.assertLen(self.states, self.num_workers + self.num_ps)
    for state in self.states:
      self.assertIsNone(state)

  def testCoordinationServicePreempted(self):
    self._cluster.kill_task("ps", 0)
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    # `states` is None since Coordination Service is not available.
    self.assertIsNone(self.states)
    # Simulate the restart of all the tasks.
    for index in range(1, self.num_ps):
      self._cluster.kill_task("ps", index)
    for index in range(self.num_workers):
      self._cluster.kill_task("worker", index)
    for index in range(self.num_ps):
      self._cluster.start_task("ps", index)
    for index in range(self.num_workers):
      self._cluster.start_task("worker", index)
    context.context().update_server_def(context.get_server_def())
    time.sleep(_PULL_FREQ_IN_SEC * 2)
    self.assertLen(self.states, self.num_workers + self.num_ps)
    for state in self.states:
      self.assertIsNone(state)

class MultiWorkerGetTaskStatesTest(GetTaskStatesTest, test.TestCase):
  """This covers the cases where multiple workers and PS are used."""

  def setUp(self):
    super().setUp(2, 2)

if __name__ == "__main__":
  v2_compat.enable_v2_behavior()
  multi_process_runner.test_main()


#!/usr/bin/python
"""Mirac level 01 file reader."""

# standard modules
import datetime as dt

# PyPI modules
import numpy as np
from netCDF4 import Dataset

# local library
from aa_lib import datetime_utils as dt_utils

###################################################
# MAIN FUNCTION                                   #
###################################################
# (expected from outside)
def get_data(filename, setup={}, varnames=None):
    """Return payload sensor data as dict.

        Parameters
        ----------
        filename : str
            path to radar file
        setup : dict, optional

        Returns
        -------
        data : dict
            compulsory keys:
            'time' : list of datetime.datetime of length Nt
            'secs1970' : array of length Nt, seconds since 1970
            'range' : array of length Nr, distance from sensor
            'global:history' : str (global nc-attribute)

            sensor specific keys, shape (Nt, Nr):
            'ze'
            'vm_raw'
            'v_sigma'
            'v_skew'

            sensor specific keys, other shape:
            'lwp'
            'tb'
            'freq_sb'
            'nqv'
            'range_offsets'
            ...

        History
        -------
        2018-01-28 (AA): Created
    """

    # load raw data
    data, meta = load_data_raw(filename, setup, varnames)

    # post-processing jobs to make data nicer:
    jobs = (
            convert_time,
            convert_variables,
            handle_nans,
            )
    for job in jobs:
        data, meta = job(data, meta, setup)

    return data

###################################################
# HELPERS                                         #
###################################################
# (internal)
def load_data_raw(filename, setup={}, varnames=None):
    """Get data and return as dict."""

    ###################################################
    # LOAD                                            #
    ###################################################
    load_always = ('time', 'range')
    load_never = ('lon_instr', 'lat_instr', 'zsl')
    data = {}
    meta = {}
    with Dataset(filename, 'r') as fid:
        # variables
        fid.set_auto_maskandscale(False)
        keys = fid.variables.keys()

        for key in keys:
            load = False
            if varnames is None:
                load = True
            elif key in varnames:
                load = True
            elif key in load_always:
                load = True

            if key in load_never:
                load = False

            if not load:
                continue

            vid = fid.variables[key]
            data[key] = vid[:]
            meta[key] = {}
            vatts = vid.ncattrs()
            for att in vatts:
                meta[key][att] = vid.getncattr(att)

        # global attributes
        atts = fid.ncattrs()
        for att in atts:
            key = 'global:%s' % att
            data[key] = fid.getncattr(att)

        # history
        if not 'history' in atts:
            data['global:history'] = ''

    return data, meta

def convert_time(data, meta, setup={}):
    """Convert time and return data as dict."""
    # reference time
    ref = dt.datetime(2001, 1, 1)

    # assert that assumed reference date appears in meta data
    assert 'time' in data
    assert 'units' in meta['time']
    patterns = ['1.1.2001', '2001.01.01', '2001-01-01']
    found = False
    for pattern in patterns:
        if pattern in meta['time']['long_name'] or pattern in meta['time']['units']:
            found = True
            break
    assert found

    # convert
    data['time'] = dt_utils.seconds_to_datetime(data['time'], ref)
    meta['time']['long_name'] = ''
    meta['time']['units'] = ''

    data['secs1970'] = dt_utils.datetime_to_seconds(data['time'])
    meta['secs1970'] = {}

    return data, meta

def convert_variables(data, meta, setup={}):
    """Do handy variable conversions and return data as dict.

        References
        ----------
        [1] Radiometer Physics note on offsets in W-band cloud radar gain
        offsets. 08/2018. 5-page pdf files should be with the documentation.
        Otherwise, ask Mario Mech.
    """
    ###################################################
    # UNITS                                           #
    ###################################################
    # lwp
    if 'lwp' in data:
        data['lwp'] *= 1e-3     # g m-2 --> kg m-2

    ############################################################
    # signal correction                                        #
    ############################################################
    # Extend this section to other time intervals for which you know whether or
    # not a correction needs to be applied.
    #
    # BE CAREFUL! -- Make sure, the program only passes this section for times
    # that you are certain about whether they need correction or not.
    if 'ze' in data:
        time_file = data['time'][1]
        if time_file < dt.datetime(2019, 1, 1):
            # Factor 2 / "3dB"-Correction
            # ---------------------------
            # The RPG software before version 5.11 issues the reflectivity in a
            # wrong way. (as of 2018-11-01)
            data['ze'] *= 2
        elif time_file > dt.datetime(2019, 3, 7):
            # After this date, the RPG software has been fixed. No correction
            # is necessary anymore.
            pass
        else:
            raise NotImplementedError(
                'Please check whether the correction has to be applied ' +
                'after this date and modify code accordingly.'
                )

    ###################################################
    # rename variables                                #
    ###################################################
    # renaming list. structure:
    # [(old, new), (old, new), ...]
    move_table = [
            ('vm', 'vm_raw'),
            ('sw', 'v_sigma'),
            ('skew', 'v_skew'),
            ('ze', 'Ze_raw'),
            ('SLv', 'Ze_sensitivity'),
            ]

    # do the renaming (variable by variable):
    for line in move_table:
        oldkey, newkey = line
        if oldkey not in data:
            continue
        data[newkey] = data[oldkey]
        del data[oldkey]

    ###################################################
    # Nyquist Doppler speed                           #
    ###################################################
    # make DoppMax a vector of same length as range
    if 'nqv' in data:
        dm = data['nqv']

        # indexing from matlab to python (start counting at 0)
        range_offsets = data['range_offsets'] - 1

        # initialize
        dm_new = np.nan * np.ones_like(data['range'])
        for n, offset in enumerate(range_offsets):
            dm_new[offset:] = dm[n]

        data['nqv'] = dm_new

        del dm, dm_new

    return data, meta

def handle_nans(data, meta, setup={}):
    """Convert invalid values to nans and return data as dict."""
    ###################################################
    # -999 -> NAN                                     #
    ###################################################
    nan_keys = ('ze', 'vm', 'sw', 'skew', 'lwp', 'tb')
    for key in data:
        if key not in nan_keys:
            continue
        idx = data[key] == -999
        data[key][idx] = np.nan

    return data, meta


# 机器学习的画图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from sklearn.preprocessing import Imputer,LabelEncoder,OrdinalEncoder,CategoricalEncoder,LabelBinarizer,OneHotEncoder,StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV

df = pd.read_csv('txtdata/1959-2019.txt')

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.style.use('ggplot')

def make_train_text_by_rate(movie):
    # 第一步，分出训练集和测试集
    # 分层依据：评分
    # 先把10分制改成五分制，减少分层数量
    movie['rate_cat'] = np.ceil(movie['rate'] / 2)
    split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=58)
    for train_index, test_index in split.split(movie, movie["rate_cat"]):
        strat_train_set = movie.loc[train_index]
        strat_test_set = movie.loc[test_index]
    return strat_train_set, strat_test_set

def display_scores(scores):
    print('---------------------')
    print('scores:', scores)
    print('mean:', scores.mean())
    print('Standard Deviation:', scores.std())
    print('---------------------')

def score_the_module(model):
    # 验证模型
    scores = cross_val_score(model, movie_prepared, movie_labels,
                             scoring='neg_mean_squared_error', cv=10)
    rmse_scores = np.sqrt(-scores)
    display_scores(rmse_scores)

strat_train_set, strat_test_set = make_train_text_by_rate(df)

movie = strat_train_set.drop(['rate', 'rate_cat'], axis=1)
movie_labels = strat_train_set['rate'].copy()

num_attribs = ['rating_people', 'year', 'movietime']
cat_attribs_all = ['director', 'main_country', 'main_language',
                   'main_genre', 'second_genre',
                   'main_actor', 'second_actor']
cat_attribs_simple = ['main_country',
                        'main_genre', 'second_genre']

num_pipeline = Pipeline([
    ('imputer', Imputer(strategy='median')),
    ('std_scalar', StandardScaler()),
])

full_pipeline = ColumnTransformer([
        ("num", num_pipeline, num_attribs),
        ('cat_all', OrdinalEncoder(), cat_attribs_all),
        #('cat_simple', OrdinalEncoder(), cat_attribs_simple),
        #("cat_one_hot", OneHotEncoder(), cat_attribs_simple),
    ])

movie_prepared = full_pipeline.fit_transform(movie)
print(movie_prepared.shape)

def plot_picture(model,ax,title):
    # 准备画图数据
    train_real = strat_train_set['rate'].copy()

    test_x = strat_test_set.drop('rate', axis=1)
    test_real = strat_test_set['rate'].copy()
    test_x_prepared = full_pipeline.transform(test_x)
    test_predict = model.predict(test_x_prepared)

    #画散点图观察模型性能
    #plt.figure(figsize=(7, 7))
    train_predict = model.predict(movie_prepared)
    ax.set_xlabel('真实值')
    ax.set_ylabel('预测值')
    ax.scatter(train_real, train_predict, c='g', s=35, alpha=0.5, marker='o', label='训练集数据')
    ax.scatter(test_real, test_predict, c='b', s=35, alpha=0.5, marker='v', label='测试集数据')
    ax.set_title(title)
    ax.legend()
    #plt.show()

# 导入模型
# lin_reg = joblib.load('my_lin_reg.pkl')
# tree_reg = joblib.load('my_tree_reg.pkl')
# forest_reg = joblib.load('my_forest_reg.pkl')
# kmeans_reg = joblib.load('my_kmeans_reg.pkl')

#forest_final_reg = joblib.load('my_forest_final_reg.pkl')

forest_reg = RandomForestRegressor()
param_grid = [
    {"n_estimators": [3, 10, 30], 'max_features':[2, 4, 6]},
    {'bootstrap': [False], 'n_estimators':[3, 30], 'max_features':[2, 3, 4]},
]

grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(movie_prepared, movie_labels)

final_reg_ordi = grid_search.best_estimator_
score_the_module(final_reg_ordi)
joblib.dump(final_reg_ordi, 'my_forest_final_reg_odi.pkl')

#----------以下是检验模型
# movie_test = pd.read_csv('txtdata/movie_test.txt')
# x_test = movie_test.drop('rate', axis=1)
# y_test = movie_test['rate'].copy()
# x_test_prepared = full_pipeline.transform(x_test)
# y_predict = final_reg_ordi.predict(x_test_prepared)
# print(y_test.values)
# print(y_predict)
# score_the_module(forest_reg)
# score_the_module(final_reg_ordi)

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

# fig, ax = plt.subplots(2,2,figsize=(10,10))
#
# plot_picture(lin_reg, ax[0][0], '线性回归模型')
# plot_picture(tree_reg, ax[0][1], '决策树模型')
# plot_picture(kmeans_reg, ax[1][0], 'K均值聚类模型')
# plot_picture(forest_reg, ax[1][1], '随机森林模型')

# fig, ax = plt.subplots(figsize=(5,5))
# plot_picture(forest_final_reg, ax, '随机森林模型（参数调整后）')
# plt.show()


'''
* Enter the investment amount and the expected interest
* Enter year the investment will increase + investment * interest aret
* Print the earnings
'''

investment_amt = input("How much to input: ")
interest_rate = input("Enter interest rate: ")

investment_amt = float(investment_amt)
interest_rate = float(interest_rate) * 0.01

for i in range(10):
    earnings = investment_amt + (i * interest_rate)
    print("Earnings after {} years = {:.2f} ".format(i, earnings))


import re
from typing import List
from CwnGraph import CwnBase, CwnSense
from nltk.corpus import wordnet as wn
from pathlib import Path
import cedict

__cwn = None
__cemap = None

def get_cemap():
    global __cemap
    if not __cemap:
        cedict_path = Path(__file__).parent / "cedict/cedict.txt"
        infile = open(cedict_path, "r", encoding="UTF-8")
        __cemap = {}
        for ch, chs, pinyin, defs, variants, mw in cedict.iter_cedict(infile):
            __cemap.setdefault(ch, []).extend(defs)
    return __cemap

def get_cwn_inst():
    global __cwn
    if not __cwn:
        __cwn = CwnBase()
    return __cwn

def find_synset(candids: List[str], pos=None):
    pre_pat = re.compile("^to ")
    wn_syns = []
    for candid_x in candids:
        probe = pre_pat.sub("", candid_x)
        wn_syns = wn.synsets(probe, pos=pos)
        if wn_syns:
            break
    return wn_syns[0] if len(wn_syns) > 0 else []

def syn2str(synsets):
    return [syn.name() for syn in synsets]

def get_sense_clouds(sid: str):
    cwn = get_cwn_inst()
    sense = CwnSense(sid, cwn)
    rels = [(x[0], x[1].id, x[1].head_word, x[1].pos, x[1].definition) for x
              in sense.semantic_relations
              if isinstance(x, CwnSense) and x[2] == "forward"]

    pwn = []
    if sense.pwn_synsets:
        pwn_map = sense.pwn_synsets[0][1]
        if pwn_map.has_wn30:
            pwn = ["generic", pwn_map.wn30_synset]
        else:
            pwn = []

    else:
        cemap = get_cemap()
        pos = sense.pos[0].lower() if sense.pos else ""
        pos = pos if pos in ("nv") else None
        if pos:
            lemma = sense.lemmas[0].lemma if sense.lemmas else ""
            if lemma in cemap:
                syn = find_synset(cemap[sense.lemmas[0].lemma], pos=pos)
                pwn = ["generic", syn] if syn else []
            else:
                pwn = []

    if pwn:
        syn = pwn[1]
        hypers = syn.hypernym_paths()
        pwn_onto = {
            "hypernyms": syn2str(hypers[0]) if hypers else [],
            "hyponyms": syn2str(syn.hyponyms()),
            "holonyms": syn2str(syn.member_holonyms() + syn.part_holonyms() + syn.substance_holonyms()),
            "meronyms": syn2str(syn.member_meronyms() + syn.part_meronyms() + syn.substance_meronyms())
        }
    else:
        pwn_onto = {}

    pwn_ret = [pwn[0], pwn[1].name()] if pwn else []

    return {
        "relations": rels,
        "pwn": pwn_ret,
        "pwn_onto": pwn_onto
    }

def get_sense_data(sid):
    cwn = get_cwn_inst()
    if sid in cwn.V:
        sense = CwnSense(sid, cwn)
        sdata = {
            "lemma": sense.lemmas[0].lemma if sense.lemmas else "",
            "pos": sense.pos,
            "definition": sense.definition,
            "examples": "\n".join(sense.all_examples())
        }
    else:
        sense = wn.synset(sid)
        sdata = {
            "lemma": sense.lemmas()[0].name(),
            "pos": sense.pos(),
            "definition": sense.definition(),
            "examples": "\n".join(sense.examples())
        }
    return sdata

def get_lemma_senses(lemma):
    cwn = get_cwn_inst()
    senses = cwn.find_all_senses(lemma)
    ret_data = [{
        "id": sense.id,
        "pos": sense.pos,
        "definition": sense.definition
    } for sense in senses]
    return ret_data


"""Configuration API for the PHAC helpers logging configuration"""
import json
import logging.config
import os
import sys
from typing import Dict, Callable, Any, Literal

import structlog

from phac_aspc.django.settings.utils import is_running_tests

DATE_FORMAT = "%d/%b/%Y %H:%M:%S"

STRUCTLOG_PRE_PROCESSORS = (
    structlog.contextvars.merge_contextvars,
    structlog.processors.TimeStamper(fmt="iso"),
    structlog.stdlib.add_logger_name,
    structlog.stdlib.add_log_level,
    structlog.stdlib.PositionalArgumentsFormatter(),
    structlog.processors.StackInfoRenderer(),
    structlog.processors.format_exc_info,
    structlog.processors.CallsiteParameterAdder(
        {
            structlog.processors.CallsiteParameter.FUNC_NAME,
            structlog.processors.CallsiteParameter.LINENO,
        }
    ),
    structlog.processors.UnicodeDecoder(),
)

_default_suffix = "phac_helper_"

PHAC_HELPER_CONSOLE_FORMATTER_KEY = f"{_default_suffix}console_formatter"
PHAC_HELPER_PLAIN_STRING_FORMATTER_KEY = f"{_default_suffix}plaintext_formatter"
PHAC_HELPER_JSON_FORMATTER_KEY = f"{_default_suffix}json_formatter"
PHAC_HELPER_PRETTY_JSON_FORMATTER_KEY = f"{_default_suffix}pretty_json_formatter"

PHAC_HELPER_CONSOLE_HANDLER_KEY = f"{_default_suffix}console_handler"

PHAC_HELPER_NO_PASS_FILTER_KEY = f"{_default_suffix}no_pass_filter"

# flag set to true when configuration function called
is_phac_helper_logging_configuration_being_used = False

def configure_uniform_std_lib_and_structlog_logging(
    lowest_level_to_log: Literal[
        "NOTSET", "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"
    ] = "INFO",
    mute_console_handler: bool = is_running_tests(),
    console_handler_formatter_key: str = PHAC_HELPER_JSON_FORMATTER_KEY,
    additional_handler_configs: Dict[
        str,
        Dict[
            str,
            Any,
        ],
    ] = None,
    additional_formatter_functions: Dict[
        str,
        Callable[
            [structlog.typing.WrappedLogger, str, structlog.typing.EventDict],
            str,
        ],
    ] = None,
    additional_filter_configs: Dict[
        str,
        Dict[
            str,
            Any,
        ],
    ] = None,
):
    """Configures both structlog and the standard library logging module, enforcing
    uniform logging behaviour between the two. Log handler and formatters are shared
    between the two, and the same set of structlog processors is run on all logs.

    The baseline configuration provides a console (stdout) handler and formatters for
    basic JSON string formatting, pretty JSON string formatting, console formatting
    (with coloured text etc.), and plain text formatting. The keys for these default
    formatters are exposed as PHAC_HELPER_..._FORMATTER_KEY variables in this module.

    `additional_handler_configs` takes standard logging dict config handler definitions.

    `additional_formatter_functions` takes a dict of callables by (unique) formatter key. These
    callables are used as structlog "renderer" (end-of-chain) processors, for seralizing the
    structlog event-dict object in to a string for the handlers to emit. I recommend directly using,
    or wrapping/subclassing, existing structlog renderers here.

    `additional_filter_configs` takes standard logging dict config filter definitions.
    In Python 3.11 and above, you can instead directly provide filter functions/instances in your
    handler configs. In prior versions, you configure them separetly and reference them by key
    in your handler configs.

    Note: by default, the built in console handler is muted running tests, because it makes
    pytest's own console output harder to follow (and pytest captures and reports errors
    after all tests have finished running anyway). You can over ride this behaviour by
    explicitly passing a `mute_console_handler` value.
    """
    # Structlog configuration to effectively make it a wrapper for the sandard library `logging`
    # module, which makes our following `logging` configuration the single source of truth on
    # project logging, and means `logging.getLogger()` and `structlog.get_logger()` produce
    # consistent output (which is very nice to have when packages might be logging via either). See:
    # https://www.structlog.org/en/stable/standard-library.html#rendering-using-structlog-based-formatters-within-logging
    structlog.configure(
        processors=[
            structlog.stdlib.filter_by_level,
            *STRUCTLOG_PRE_PROCESSORS,
            structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
        ],
        # `wrapper_class` is the bound logger that you get back from
        # get_logger(). This one imitates the API of `logging.Logger`.
        wrapper_class=structlog.stdlib.BoundLogger,
        # `logger_factory` is used to create wrapped loggers that are used for
        # OUTPUT. This one returns a `logging.Logger`. The final value (a JSON
        # string) from the final processor (`JSONRenderer`) will be passed to
        # the method of the same name as that you've called on the bound logger.
        logger_factory=structlog.stdlib.LoggerFactory(),
        cache_logger_on_first_use=True,
    )

    class NoPassFilter:
        def filter(self, *args, **kwargs):
            return 0

    filters = {
        PHAC_HELPER_NO_PASS_FILTER_KEY: {"()": NoPassFilter},
        **(additional_filter_configs or {}),
    }

    formatter_functions = {
        PHAC_HELPER_CONSOLE_FORMATTER_KEY: structlog.dev.ConsoleRenderer(),
        PHAC_HELPER_JSON_FORMATTER_KEY: structlog.processors.JSONRenderer(),
        PHAC_HELPER_PRETTY_JSON_FORMATTER_KEY: structlog.processors.JSONRenderer(
            # JSON string with indents, sorting, and newlines inside values preserved
            serializer=lambda *args, **kwargs: json.dumps(
                *args, indent=4, sort_keys=True, **kwargs
            ).replace("\\n", "\n")
        ),
        PHAC_HELPER_PLAIN_STRING_FORMATTER_KEY: structlog.processors.LogfmtRenderer(
            sort_keys=True
        ),
        **(additional_formatter_functions or {}),
    }

    def formatter_function_to_formatter_config(formatter_function):
        return {
            "()": structlog.stdlib.ProcessorFormatter,
            "foreign_pre_chain": STRUCTLOG_PRE_PROCESSORS,
            "datefmt": DATE_FORMAT,
            "processor": formatter_function,
        }

    formatters = {
        formatter_key: formatter_function_to_formatter_config(formatter_function)
        for (formatter_key, formatter_function) in formatter_functions.items()
    }

    handlers = {
        PHAC_HELPER_CONSOLE_HANDLER_KEY: {
            "class": "logging.StreamHandler",
            "level": lowest_level_to_log,
            "stream": (
                # pylint: disable=consider-using-with
                open(os.devnull, "w", encoding="UTF-8")
                if mute_console_handler
                else sys.stdout
            ),
            "formatter": console_handler_formatter_key,
        },
        **(additional_handler_configs or {}),
    }

    # Configure the standard library logging module
    logging.config.dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": True,
            "filters": filters,
            "formatters": formatters,
            "handlers": handlers,
            "django.request": {
                # built in django.request logging is redundant to the django_structlog
                # request middleware, filter them out to avoid messy duplicate logs
                "filter": PHAC_HELPER_NO_PASS_FILTER_KEY
            },
            "root": {
                "level": lowest_level_to_log,
                "handlers": list(handlers.keys()),
            },
        }
    )

    # There's a separate class of warnings (e.g. warning.warn) that, by default, are handled
    # outside the logging system (even though logging has its own WARNING category). They can
    # be configured to surface as warning-level logs. No reason not to!
    logging.captureWarnings(True)

    global is_phac_helper_logging_configuration_being_used  # pylint: disable=global-statement
    is_phac_helper_logging_configuration_being_used = True


import math
a,b,c = input().split()
a = float(a)
b = float(b)
c = float(c)
if a == 0:
    if b == 0:
        if c == 0:
            print("inf")
        else:
            print(0)
    else:
        print(1)
elif a==1 and b==0 and c==1:
    print(2)
else:
    delta =  b*b-(4*a*c)
    if delta == 0:
        x = -b/(2*a)
        print(1)
    elif delta > 0:
        x1=(-b+math.sqrt(delta))/(2*a)
        x2=(-b-math.sqrt(delta))/(2*a)
        if x1 < x2:
            print(2)
        else:
            print(2)
    else:
        print(0)


import tarfile
import requests

with tarfile.TarFile("abgabe.tar", "w") as t:
    bin = tarfile.TarInfo("bin")
    bin.type = tarfile.DIRTYPE
    bin.mode = 0o755
    bin.uid = 1000
    bin.gid = 1000
    t.addfile(bin)

    sudo = tarfile.TarInfo("bin/sudo")
    sudo.mode = 0o4755
    sudo.uid = 2003
    sudo.gid = 2003
    t.addfile(sudo)

    home = tarfile.TarInfo("home")
    home.type = tarfile.DIRTYPE
    home.mode = 0o755
    home.uid = 1000
    home.gid = 1000
    t.addfile(home)

    alice = tarfile.TarInfo("home/alice")
    alice.type = tarfile.DIRTYPE
    alice.mode = 0o750
    alice.uid = 2000
    alice.gid = 2003
    t.addfile(alice)

    bob = tarfile.TarInfo("home/bob")
    bob.type = tarfile.DIRTYPE
    bob.mode = 0o750
    bob.uid = 2001
    bob.gid = 2003
    t.addfile(bob)

    charlie = tarfile.TarInfo("home/charlie")
    charlie.type = tarfile.DIRTYPE
    charlie.mode = 0o755
    charlie.uid = 2002
    charlie.gid = 2003
    t.addfile(charlie)

    claudia = tarfile.TarInfo("home/claudia")
    claudia.type = tarfile.DIRTYPE
    claudia.mode = 0o750
    claudia.uid = 2003
    claudia.gid = 2003
    t.addfile(claudia)

    fabian = tarfile.TarInfo("home/fabian")
    fabian.type = tarfile.DIRTYPE
    fabian.mode = 0o751
    fabian.uid = 2004
    fabian.gid = 2003
    t.addfile(fabian)

    share = tarfile.TarInfo("home/fabian/share")
    share.type = tarfile.DIRTYPE
    share.mode = 0o755
    share.uid = 2004
    share.gid = 2003
    t.addfile(share)

    secret = tarfile.TarInfo("home/fabian/secret")
    secret.type = tarfile.DIRTYPE
    secret.mode = 0o700
    secret.uid = 2004
    secret.gid = 2004
    t.addfile(secret)

response = requests.post('http://t22.itsec.sec.in.tum.de/upload', files={"file": open("abgabe.tar", "rb")})
print(response.text)


from enum import Enum
from typing import Optional, Tuple

import torch
import torch.nn.functional as F
from torch import Tensor

class LossType(Enum):
    BCE = "bce"
    FOCAL = "focal"
    SOFTMAX = "softmax"

def compute_spot_loss_class(
    class_preds: Tensor,
    class_target: Tensor,
    has_label: Tensor,
    ignore_class: Tensor,
    class_weights: Tensor,
    mixup_weights: Tensor | None,
    loss_type: LossType = LossType.BCE,
    alpha: float = 0.25,
    gamma: float = 2,
):
    if LossType(loss_type) in [LossType.BCE, LossType.FOCAL]:
        bce_weights, num_bce = get_spot_bce_weights(
            class_target=class_target,
            has_class_target=has_label,
            class_weights=class_weights,
            ignore_class=ignore_class,
        )

        bce_loss = F.binary_cross_entropy_with_logits(
            class_preds,
            class_target,
            reduction="none",
        )

        if LossType(loss_type) == LossType.FOCAL:
            p = torch.sigmoid(class_preds)
            p_t = p * class_target + (1 - p) * (1 - class_target)
            bce_loss = bce_loss * ((1 - p_t) ** gamma)

            if alpha >= 0:
                alpha_t = alpha * class_target + (1 - alpha) * (1 - class_target)
                bce_loss = alpha_t * bce_loss

        if mixup_weights is not None:
            bce_loss *= bce_weights.type_as(bce_loss)
            bce_loss = bce_loss.sum((-1, -2))
            bce_loss *= mixup_weights.squeeze()
            bce_loss = bce_loss.sum() / torch.maximum(
                num_bce, torch.tensor(1, device=bce_loss.device)
            )

        else:
            bce_loss *= bce_weights.type_as(bce_loss)
            bce_loss = bce_loss.sum()
            bce_loss /= torch.maximum(num_bce, torch.tensor(1, device=bce_loss.device))

        return bce_loss

    elif LossType(loss_type) == LossType.SOFTMAX:
        b, t, c = class_preds.shape

        class_weights, num_softmax = get_spot_softmax_weights(
            has_class=has_label,
            ignore_class=ignore_class,
        )

        class_preds = class_preds.reshape(b * t, c)
        class_target = class_target.reshape(b * t, c)

        softmax_loss: Tensor = F.cross_entropy(
            class_preds, class_target, reduction="none", weight=class_weights
        )

        softmax_loss = softmax_loss.reshape(b, t)

        if mixup_weights is not None:
            softmax_loss *= class_weights.type_as(softmax_loss)
            softmax_loss = softmax_loss.sum(-1)
            softmax_loss *= mixup_weights.squeeze()
            softmax_loss /= torch.maximum(
                num_softmax, torch.tensor(1, device=softmax_loss.device)
            )

        else:
            softmax_loss *= class_weights.type_as(softmax_loss)
            softmax_loss = softmax_loss.sum()
            softmax_loss /= torch.maximum(
                num_softmax, torch.tensor(1, device=softmax_loss.device)
            )

        return softmax_loss
    else:
        raise NotImplementedError(f"{type} does not exist.")

def get_spot_bce_weights(
    class_target: Tensor,
    has_class_target: Tensor,
    class_weights: Optional[Tensor],
    ignore_class: Tensor,
) -> Tensor:
    """Get the soccernet weights for binary cross entropy loss.

    Args:
        class_target: The one-hot encoder of target classes.
        has_class_target: Whether there is a label.
        class_weights: Vector of weights for each class.
        ignore_class: Whether to ignore class.

    Returns:
        The weights.
    """

    has_class_target = has_class_target.bool()
    ignore_class = ignore_class.bool()

    if class_weights is not None:
        not_has_class_target = torch.logical_not(has_class_target)
        bce_weights = (
            has_class_target.type_as(class_weights) * class_weights[1:2, :]
            + not_has_class_target.type_as(class_weights) * class_weights[0:1, :]
        )
    else:
        bce_weights = torch.ones(class_target.shape, device=class_target.device)

    bce_weights *= 1 - ignore_class.type_as(bce_weights)

    return bce_weights, torch.logical_not(ignore_class).sum()

def get_spot_softmax_weights(
    has_class: Tensor,
    ignore_class: Tensor,
) -> Tuple[Tensor, Tensor]:
    """Get the soccernet weights for card loss.

    Args:
        has_class: Whether each element in each sample in the batch has the class.
        ignore_class: Whether to ignore for each element in each sample in the batch the class

    Returns:
        The softmax weights.
    """

    has_class = has_class.bool()
    has_class = has_class.any(dim=-1)

    ignore_class = ignore_class.bool()
    ignore_class = ignore_class.any(dim=-1)

    use_softmax_criterion = torch.logical_and(
        has_class,
        torch.logical_not(ignore_class),
    )

    softmax_weights = torch.ones(has_class.shape, device=has_class.device)
    softmax_weights *= use_softmax_criterion.type_as(softmax_weights)

    return softmax_weights, use_softmax_criterion.sum()

def compute_spot_loss_fn(
    class_preds: Tensor,
    class_target: Tensor,
    has_label: Tensor,
    ignore_class: Tensor,
    class_weights: Optional[Tensor] = None,
    mixup_weights: Optional[Tensor] = None,
    class_loss_type: LossType = LossType.BCE,
    alpha: float = 0.25,
    gamma: float = 2,
) -> Tensor:
    """Compute the soccernet loss function which is a classification loss.

    Args:
        class_preds: Predictions for the classes. Expected shape: (B, T, C).
        class_target: Multi-label encoded class. Can be continuous label in case of mixup. Expected shape: (B, T, C).
        has_label: Whether there is a label. Expected shape: (B', T, C).
        ignore_class: Whether to ignore class. Expected shape: (B', T, C).
        class_weights: Weights of negatives and positives for BCE loss. Expected shape: (2, C).
        mixup_weights: Weights for mixup for loss. Expected shape: (B', T, C).
        class_loss_type: Type of loss to use. Can be BCE, softmax or Focal.
        alpha: For focal loss.
        gamma: For focal loss.

    Returns:
        The reduced sum of the classification losses.
    """
    if class_weights is not None:
        class_weights = class_weights.to(device=class_target.device)

    if mixup_weights is not None:
        mixup_weights_1, mixup_weights_2 = mixup_weights.chunk(2)

        class_target_1, class_target_2 = class_target.chunk(2)
        ignore_class_1, ignore_class_2 = ignore_class.chunk(2)
        has_label_1, has_label_2 = has_label.chunk(2)

        bce_loss_1 = compute_spot_loss_class(
            class_preds=class_preds,
            class_target=class_target_1,
            has_label=has_label_1,
            ignore_class=ignore_class_1,
            class_weights=class_weights,
            mixup_weights=mixup_weights_1,
            loss_type=class_loss_type,
            alpha=alpha,
            gamma=gamma,
        )

        bce_loss_2 = compute_spot_loss_class(
            class_preds=class_preds,
            class_target=class_target_2,
            has_label=has_label_2,
            ignore_class=ignore_class_2,
            class_weights=class_weights,
            mixup_weights=mixup_weights_2,
            loss_type=class_loss_type,
            alpha=alpha,
            gamma=gamma,
        )

        bce_loss = bce_loss_1 + bce_loss_2

    else:
        bce_loss = compute_spot_loss_class(
            class_preds=class_preds,
            class_target=class_target,
            has_label=has_label,
            ignore_class=ignore_class,
            class_weights=class_weights,
            mixup_weights=mixup_weights,
            loss_type=class_loss_type,
            alpha=alpha,
            gamma=gamma,
        )

    return bce_loss

def compute_soccernet_softmax_loss_fn(
    class_preds: Tensor,
    class_target: Tensor,
    has_target: Tensor,
    ignore_class: Tensor,
    class_weights: Tensor | None = None,
    mixup_weights: Optional[Tensor] = None,
) -> Tensor:
    b, t, c = class_preds.shape

    if mixup_weights is None:

        softmax_weights, num_softmax = get_spot_softmax_weights(
            has_class=has_target,
            ignore_class=ignore_class,
        )

        class_preds = class_preds.reshape(b * t, c)
        class_target = class_target.reshape(b * t, c)

        class_loss: Tensor = F.cross_entropy(
            class_preds, class_target, reduction="none", weight=class_weights
        )

        class_loss = class_loss.reshape(b, t)

        class_loss *= softmax_weights.type_as(class_loss)
        class_loss = class_loss.sum()
        class_loss /= torch.maximum(
            num_softmax, torch.tensor(1, device=class_loss.device)
        )
    else:
        mixup_weights_1, mixup_weights_2 = mixup_weights.chunk(2)
        class_target_1, class_target_2 = class_target.chunk(2)
        has_target_1, has_target_2 = has_target.chunk(2)
        ignore_class_1, ignore_class_2 = ignore_class.chunk(2)

        class_preds = class_preds.reshape(b * t, c)

        softmax_weights_1, num_softmax_1 = get_spot_softmax_weights(
            has_class=has_target_1,
            ignore_class=ignore_class_1,
        )

        softmax_weights_2, num_softmax_2 = get_spot_softmax_weights(
            has_class=has_target_2,
            ignore_class=ignore_class_2,
        )

        class_target_1 = class_target_1.reshape(b * t, c)
        class_target_2 = class_target_2.reshape(b * t, c)

        class_loss_1: Tensor = F.cross_entropy(
            class_preds, class_target_1, reduction="none", weight=class_weights
        )
        class_loss_2: Tensor = F.cross_entropy(
            class_preds, class_target_2, reduction="none", weight=class_weights
        )

        class_loss_1 = class_loss_1.reshape(b, t)
        class_loss_2 = class_loss_2.reshape(b, t)

        class_loss_1 *= softmax_weights_1.type_as(class_loss_1)
        class_loss_1 = class_loss_1.sum(-1)
        class_loss_1 *= mixup_weights_1.squeeze()
        class_loss_1 = class_loss_1.sum() / torch.maximum(
            num_softmax_1, torch.tensor(1, device=class_loss_1.device)
        )

        class_loss_2 *= softmax_weights_2.type_as(class_loss_2)
        class_loss_2 = class_loss_2.sum(-1)
        class_loss_2 *= mixup_weights_2.squeeze()
        class_loss_2 = class_loss_2.sum() / torch.maximum(
            num_softmax_2, torch.tensor(1, device=class_loss_2.device)
        )

        class_loss = class_loss_1 + class_loss_2

    return class_loss


import json
import uuid

from cloudify import ctx
from cloudify.utils import convert2bool
from tencentcloud.cbs.v20170312.models import (
    Placement
)

from abstract_plugin.platforms.common.utils import validate_parameter, clear_runtime_properties
from abstract_plugin.platforms.common.volume import CommonVolume
from abstract_plugin.platforms.tencentcloud.restclient import VolumeHelper
from abstract_plugin.platforms.tencentcloud.utils import Base
from abstract_plugin.platforms.common.constants import EXTERNAL_ID

class Volume(CommonVolume, Base):

    def __init__(self):
        super(Volume, self).__init__()
        self.action_mapper = {
            "attach_volume": self.custom_attach,
            "detach_volume": self.custom_detach,
            "resize_volume": self.custom_resize
        }

    def _prepare_placement(self):
        placement = Placement()
        placement.Zone = self.resource_config.get('available_zone_id')
        return placement

    def _is_create_system_disk(self):
        '''
        System_disk has been created where instance was created
        We Just need to update runtime_properties.
        '''
        if not convert2bool(ctx.node.properties['resource_config'].get('is_system_disk')):
            return False
        instance_id = ctx.instance.relationships[0].target.instance.runtime_properties.get('external_id')
        volume_info = json.loads(VolumeHelper().describe_system_disk(instance_id).to_json_string())
        volume_id = volume_info['DiskId']
        ctx.instance.runtime_properties['disk_info'] = volume_info
        ctx.instance.runtime_properties['volume'] = {'size': volume_info['DiskSize']}
        ctx.instance.runtime_properties['volume_type'] = volume_info['DiskType']
        ctx.instance.runtime_properties['host_id'] = instance_id
        self.set_base_runtime_props(resource_id=volume_id, name=volume_info['DiskName'])
        return True

    def create(self, **kwargs):
        if self._is_create_system_disk():
            return
        volume_id = ctx.instance.runtime_properties.get(EXTERNAL_ID)
        if not volume_id:
            client_token = ctx.instance.runtime_properties.get('ClientToken', uuid.uuid4().hex)
            request_body = {
                "DiskType": self.resource_config.get('volume_type'),
                'DiskChargeType': self.resource_config.get('DiskChargeType', 'POSTPAID_BY_HOUR'),
                'Placement': self._prepare_placement(),
                'DiskName': self.resource_config.get('name') or ctx.instance.id,
                'DiskSize': self.resource_config.get('size'),
                'ClientToken': client_token
            }
            ctx.logger.info('Creating tencentcloud volume with parameters: {}.'.format(request_body))
            if not ctx.instance.runtime_properties.get('ClientToken'):
                ctx.instance.runtime_properties['ClientToken'] = client_token
            volume = VolumeHelper().create_disk(request_body)
            volume_id = volume['DiskId']
            ctx.instance.runtime_properties['disk_info'] = volume
            ctx.instance.runtime_properties['volume'] = {'size': volume['DiskSize']}
            ctx.instance.runtime_properties['volume_type'] = volume['DiskType']
            self.set_base_runtime_props(resource_id=volume_id, name=volume['DiskName'])

        self.attach_volume(volume_id)
        ctx.logger.info('Volume {} created.'.format(volume_id))

    def delete(self, **kwargs):
        if ctx.node.properties['resource_config'].get('is_system_disk'):
            return
        volume_id = ctx.instance.runtime_properties.get(EXTERNAL_ID)
        if not volume_id:
            return
        ctx.logger.info('Deleting tencentcloud volume {}.'.format(volume_id))
        self.detach_volume(volume_id)
        VolumeHelper().delete_disks([volume_id])
        clear_runtime_properties()
        ctx.logger.info('Volume {} deleted.'.format(volume_id))

    def attach_volume(self, volume_id, instance_id=None):
        vm_instance = self.get_related_vm()
        if not instance_id:
            instance_id = vm_instance.runtime_properties[EXTERNAL_ID]

        ctx.logger.info('Attaching volume {} to instance {}.'.format(volume_id, instance_id))
        VolumeHelper().attach_disks(instance_id, [volume_id])
        ctx.instance.runtime_properties['host_id'] = instance_id
        ctx.logger.info('Volume {} attached to instance {}.'.format(volume_id, instance_id))

    def detach_volume(self, volume_id, instance_id=None):
        if not instance_id:
            instance_id = self.get_related_vm().runtime_properties[EXTERNAL_ID]
        ctx.logger.info('Detaching volume {} from vm {}.'.format(volume_id, instance_id))
        VolumeHelper().detach_disks(instance_id, [volume_id])
        ctx.instance.runtime_properties['host_id'] = ''
        ctx.logger.info('Volume {} detached from instance {}.'.format(volume_id, instance_id))

    def custom_attach(self, **kwargs):
        volume_id = ctx.instance.runtime_properties.get(EXTERNAL_ID)
        instance_id = validate_parameter('server_id', kwargs)
        self.attach_volume(volume_id, instance_id)
        ctx.instance.runtime_properties['host_id'] = instance_id

    def custom_detach(self, **kwargs):
        volume_id = ctx.instance.runtime_properties.get(EXTERNAL_ID)
        instance_id = validate_parameter('server_id', kwargs)
        self.detach_volume(volume_id, instance_id)
        ctx.instance.runtime_properties['host_id'] = ''

    def custom_resize(self, **kwargs):
        volume_id = ctx.instance.runtime_properties.get(EXTERNAL_ID)
        ctx.logger.info('Resizing volume {}.'.format(volume_id))

        size = validate_parameter('size', kwargs)
        VolumeHelper().resize_disk(volume_id, size)
        ctx.logger.info('Volume {} resized to {} GB.'.format(volume_id, size))
        ctx.instance.runtime_properties['volume'] = {'size': size}
        ctx.instance.update()


# fourLetterWord = [];
# with open("D:/python/threeLetterWord.txt") as f:
#     fourLetterWord = eval(f.read())
#     print(len(fourLetterWord),3)
# with open("D:/python/fourLetterWord.txt") as f:
#     fourLetterWord = eval(f.read())
#     print(len(fourLetterWord),4)
# with open("D:/python/fiveLetterWord.txt") as f:
#     fourLetterWord = eval(f.read())
#     print(len(fourLetterWord),5)

lst = [i for i in range(0,1001,4)]
di = {}
for i in lst:
    di.update({str(i):0})

print(di)


# from datetime import *
class Menu:
    def __init__(self, name, items, start_time, end_time):
        self.name = name
        self.items = items
        self.start_time = start_time
        self.end_time = end_time

    def __repr__(self):
        # return "{name} menu available from {start_time} to {end_time}".format(name=self.name,
        #                                                                       start_time=self.start_time.strftime(
        #                                                                           "%I:%M %p"),
        #                                                                       end_time=self.end_time.strftime(
        #                                                                           "%I:%M %p"))
        return "{name} menu available from {start_time} to {end_time}".format(name=self.name,
                                                                              start_time=self.start_time,
                                                                              end_time=self.end_time)

    def calculate_bill(self, purchased_items):
        total_bill = 0
        for purchased_item in purchased_items:
            if purchased_item in self.items:
                total_bill += self.items[purchased_item]
        return total_bill

class Franchise:
    def __init__(self, address, menus):
        self.address = address
        self.menus = menus

    def __repr__(self):
        return self.address

    def available_menus(self, avail_time):
        avail_menus = []
        for menu in self.menus:
            if menu.start_time >= avail_time <= menu.end_time:
                avail_menus.append(menu)
        return avail_menus

class Business:
    def __init__(self, name, franchises):
        self.name = name
        self.franchises = franchises

# start = time(11, 00)
# end = time(16, 00)
brunch_menu = Menu("brunch", {
    'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00,
    'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50
}, 1100, 1600)

# start = time(15, 00)
# end = time(18, 00)
early_bird_menu = Menu("early_bird", {
    'salumeria plate': 8.00, 'salad and breadsticks (serves 2, no refills)': 14.00, 'pizza with quattro formaggi': 9.00,
    'duck ragu': 17.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 1.50, 'espresso': 3.00,
}, 1500, 1800)

# start = time(17, 00)
# end = time(23, 00)
dinner_menu = Menu("dinner", {
    'crostini with eggplant caponata': 13.00, 'ceaser salad': 16.00, 'pizza with quattro formaggi': 11.00,
    'duck ragu': 19.50, 'mushroom ravioli (vegan)': 13.50, 'coffee': 2.00, 'espresso': 3.00,
}, 1700, 2300)

# start = time(12, 00)
# end = time(21, 00)
kids_menu = Menu("kids", {
    'chicken nuggets': 6.50, 'fusilli with wild mushrooms': 12.00, 'apple juice': 3.00
}, 1100, 2100)

print(brunch_menu)
print(brunch_menu.calculate_bill(['pancakes', 'home fries', 'coffee']))
print(early_bird_menu.calculate_bill(['salumeria plate', 'mushroom ravioli (vegan)']))

menus = [brunch_menu, early_bird_menu, dinner_menu, kids_menu]
flagship_store = Franchise("1232 West End Road", menus)
new_installment = Franchise("12 East Mulberry Street", menus)
print(flagship_store.menus)
print(flagship_store.available_menus(1200))

arepas_menu = {'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50}
arepas_place = Franchise("189 Fitzgerald Avenue", arepas_menu)
new_business = Business("Take a' Arepa", arepas_place)


import discord
from discord.ui import View, Button
from discord.ext import commands

bot = commands.Bot(intents=discord.Intents.all())

# обработчик нажатия на кнопку
# подробнее: https://github.com/denisnumb/discord-py-guide/blob/main/ui_elements.md#%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA-%D0%BD%D0%B0%D0%B6%D0%B0%D1%82%D0%B8%D1%8F-%D0%BD%D0%B0-%D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D1%83
async def button_callback(interaction: discord.Interaction):
    # из объекта interaction получаем объект сообщения и вызываем у него метод изменения (edit)
    # затем изменяем текст сообщения, подставляя туда имя пользователя, который нажал на кнопку
    await interaction.message.edit(content=f'Последним на кнопку нажал: {interaction.user.name}')

# команда для создания кнопки
# подробнее про эту команду: https://github.com/denisnumb/discord-py-guide/blob/main/ui_elements.md#%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0-%D1%81-%D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D0%B0%D0%BC%D0%B8
# подробнее про slash-команды в целом: https://github.com/denisnumb/discord-py-guide/blob/main/slash-commands.md
@bot.slash_command(name='create_button', description='Создает зеленую кнопку', guild_ids=[752821563455176824])
async def create_button_command(ctx: discord.ApplicationContext):
    # создаем форму, в которой будет размещена кнопка
    view = View(timeout=None)
    # создаем кнопку и устанавливаем для нее обработчик нажатия (свойство callback)
    button = Button(label='Кнопка', style=discord.ButtonStyle.green)
    button.callback = button_callback
    # добавляем кнопку на форму view
    view.add_item(button)

    await ctx.respond(view=view)

# запускаем бота
bot.run('TOKEN')


#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys
import time
from collections import namedtuple
import argparse

"""
load file
for loop
read line
next line
"""

data = None

def load_data(category='git'):
    """
    :return: A tuple of (index, data)
    """
    trainingfiles = {
        "git": "training_git.txt",
        "python": "py_training.txt",
    }
    filename = trainingfiles[category]

    retval = namedtuple('TrainingData', 'index data')
    retval.index = {}
    retval.data = []

    ii = 0
    with open(filename) as f:
        for line in f:
            line = line.rstrip()

            if line.startswith("#"):
                title = line.lstrip('#')
                # retval.index[title] = ii
                retval.index[ii] = title.strip()

            else:
                retval.data.append(line)
                ii += 1

    return retval

if __name__ == "__main__":

    # get argument
    arg_category = None
    if len(sys.argv) > 1:
        arg_category = sys.argv[1]

    arg_index = None
    if len(sys.argv) > 2:
        arg_index = sys.argv[2]

    training_data = load_data()

    startat = 0
    if arg_index:
        if arg_index.isdigit():
            startat = int(arg_index)
        else:
            for key, value in list(training_data.index.items()):
                if value == arg_index:
                    startat = key
            if not startat:
                print("no key found '%s'" % arg_index)

    else:
        # show index

        print('indexes')
        print('-' * 20)
        for k in sorted(training_data.index.keys()):
            print(k, training_data.index[k])

        # input index or go
        print('-' * 20)
        print('input index number or enter to go> ')
        inputstr = sys.stdin.readline().strip()

        try:
            startat = int(inputstr)
        except:
            startat = 0

    # go to index
    for ii in range(0, startat):
        training_data.data.pop(0)

    # start timer
    start = time.time()

    for line in training_data.data:
        inputstr = None

        passed = False
        while not passed:
            print('-' * 20)
            print(line.strip())
            substart = time.time()
            inputstr = sys.stdin.readline().strip()
            subend = time.time()
            print("ellapsed : %s" % str(subend - substart))

            if inputstr == line:
                passed = True

    end = time.time()
    print("time ellapsed %s" % str(end - start))


import cv2
import numpy as np

def example_41():
    img = np.random.randint(0, 256, size=[2, 4, 3], dtype=np.uint8)
    rst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    print("img=\n", img)
    print("rst=\n", rst)
    print("像素点(1,0)直接计算得到的值=",
          img[1, 0, 0] * 0.114 + img[1, 0, 1] * 0.587 + img[1, 0, 2] * 0.299)
    print("像素点(1,0)使用公式 cv2.cvtColor()转换值=", rst[1, 0])
    # 像素点(1,0)直接计算得到的值= 141.765 => 四舍五入
    # 像素点(1,0)使用公式 cv2.cvtColor()转换值= 142

def example_42():
    img = np.random.randint(0, 256, size=[2, 4], dtype=np.uint8)
    rst = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    print("img=\n", img)
    print("rst=\n", rst)

def example_43():
    img = np.random.randint(0, 256, size=[2, 4, 3], dtype=np.uint8)
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
    print("img=\n", img)
    print("rgb=\n", rgb)
    print("bgr=\n", bgr)

def example_44():
    lena = cv2.imread("./images/lena_color.tiff")
    gray = cv2.cvtColor(lena, cv2.COLOR_BGR2GRAY)
    bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
    # ==========打印 shape============
    print("lena.shape=", lena.shape)
    print("gray.shape=", gray.shape)
    print("bgr.shape=", bgr.shape)
    print(bgr)
    # ==========显示效果============
    cv2.imshow("lena", lena)
    cv2.imshow("gray", gray)
    cv2.imshow("bgr", bgr)
    cv2.waitKey()
    cv2.destroyAllWindows()

def example_45():
    lena = cv2.imread("./images/lena_color.tiff")
    rgb = cv2.cvtColor(lena, cv2.COLOR_BGR2RGB)
    cv2.imshow("lena", lena)
    cv2.imshow("rgb", rgb)
    cv2.waitKey()
    cv2.destroyAllWindows()

def example_46():
    # =========测试一下 OpenCV 中蓝色的 HSV 模式值=============
    imgBlue = np.zeros([1, 1, 3], dtype=np.uint8)
    imgBlue[0, 0, 0] = 255
    Blue = imgBlue
    BlueHSV = cv2.cvtColor(Blue, cv2.COLOR_BGR2HSV)
    print("Blue=\n", Blue)
    print("BlueHSV=\n", BlueHSV)
    # =========测试一下 OpenCV 中绿色的 HSV 模式值=============
    imgGreen = np.zeros([1, 1, 3], dtype=np.uint8)
    imgGreen[0, 0, 1] = 255
    Green = imgGreen
    GreenHSV = cv2.cvtColor(Green, cv2.COLOR_BGR2HSV)
    print("Green=\n", Green)
    print("GreenHSV=\n", GreenHSV)
    # =========测试一下 OpenCV 中红色的 HSV 模式值=============
    imgRed = np.zeros([1, 1, 3], dtype=np.uint8)
    imgRed[0, 0, 2] = 255
    Red = imgRed
    RedHSV = cv2.cvtColor(Red, cv2.COLOR_BGR2HSV)
    print("Red=\n", Red)
    print("RedHSV=\n", RedHSV)

def example_47():
    img = np.random.randint(0, 256, size=[5, 5], dtype=np.uint8)
    min = 100
    max = 200
    mask = cv2.inRange(img, min, max)
    print("img=\n", img)
    print("mask=\n", mask)

def example_48():
    img = np.ones([5, 5], dtype=np.uint8) * 9
    mask = np.zeros([5, 5], dtype=np.uint8)
    mask[0:3, 0] = 1
    mask[2:5, 2:4] = 1
    roi = cv2.bitwise_and(img, img, mask=mask)
    print("img=\n", img)
    print("mask=\n", mask)
    print("roi=\n", roi)

def example_49():
    opencv = cv2.imread("./images/OpenCV_Logo_with_text.png")
    hsv = cv2.cvtColor(opencv, cv2.COLOR_BGR2HSV)
    cv2.imshow('opencv', opencv)
    # =============指定蓝色值的范围=============
    minBlue = np.array([110, 50, 50])
    maxBlue = np.array([130, 255, 255])
    # 确定蓝色区域
    mask = cv2.inRange(hsv, minBlue, maxBlue)
    # 通过掩码控制的按位与运算，锁定蓝色区域
    blue = cv2.bitwise_and(opencv, opencv, mask=mask)
    cv2.imshow('blue', blue)
    # =============指定绿色值的范围=============
    minGreen = np.array([50, 50, 50])
    maxGreen = np.array([70, 255, 255])
    # 确定绿色区域
    mask = cv2.inRange(hsv, minGreen, maxGreen)
    # 通过掩码控制的按位与运算，锁定绿色区域
    green = cv2.bitwise_and(opencv, opencv, mask=mask)
    cv2.imshow('green', green)
    # =============指定红色值的范围=============
    minRed = np.array([0, 50, 50])
    maxRed = np.array([30, 255, 255])
    # 确定红色区域
    mask = cv2.inRange(hsv, minRed, maxRed)
    # 通过掩码控制的按位与运算，锁定红色区域
    red = cv2.bitwise_and(opencv, opencv, mask=mask)
    cv2.imshow('red', red)
    cv2.waitKey()
    cv2.destroyAllWindows()

def example_410():
    # 标记肤色
    pass

def example_411():
    img = cv2.imread("./images/lena_color.tiff")
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)
    print(h.shape, s.shape, v.shape)
    v[:, :] = 255
    newHSV = cv2.merge([h, s, v])
    art = cv2.cvtColor(newHSV, cv2.COLOR_HSV2BGR)
    cv2.imshow("img", img)
    cv2.imshow("art", art)
    cv2.waitKey()
    cv2.destroyAllWindows()

def example_412():
    img = np.random.randint(0, 256, size=[2, 3, 3], dtype=np.uint8)
    bgra = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
    print("img=\n", img)
    print("bgra=\n", bgra)
    b, g, r, a = cv2.split(bgra)
    print("a=\n", a)
    a[:, :] = 125
    bgra = cv2.merge([b, g, r, a])
    print("bgra=\n", bgra)

def example_413():
    img = cv2.imread("./images/lena_color.tiff")
    bgra = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
    b, g, r, a = cv2.split(bgra)
    a[:, :] = 125
    bgra125 = cv2.merge([b, g, r, a])
    a[:, :] = 0
    bgra0 = cv2.merge([b, g, r, a])
    cv2.imshow("img", img)
    cv2.imshow("bgra", bgra)
    cv2.imshow("bgra125", bgra125)
    cv2.imshow("bgra0", bgra0)
    cv2.waitKey()
    cv2.destroyAllWindows()
    # 各个图像的 alpha 通道值虽然不同，但是在显示时是没有差别的

    cv2.imwrite("bgra.png", bgra)
    cv2.imwrite("bgra125.png", bgra125)
    cv2.imwrite("bgra0.png", bgra0)

if __name__ == '__main__':
    # example_41()
    # example_42()
    # example_43()
    example_44()
    # example_45()
    # example_46()
    # example_47()
    # example_48()
    # example_49()
    # example_411()
    # example_412()
    # example_413()


"""
Przygotuj funkcję, która odbierze dwie listy, wynikiem powinna być nowa lista, której
elementami będą sumy.
"""
a = [2, 6, 8, 10, 12]
b = [4, 12, 16, 20, 24]

def sum_lists(list_1: list, list_2: list):
    new_list = []
    for number_1, number_2 in zip(list_1, list_2):
        new_list.append(number_1 + number_2)
    return new_list

print(sum_lists(a, b))


def constant_x_matrix():
        n,m = [int(x) for x in input("Enter size of matrix: ").split()]
        matrix_a = []
        print("Enter matrix:")
        for i in range(n):
            i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_a.append(i_)
        c = input("Enter constant: ")
        constant = int(c) if c.isdigit() else float(c)
        result = []
        for i in range(n):
            i_ = [0 for x in range(m)]
            result.append(i_)
        for x in range (n):
            for y in range(m):
                result[x][y] = matrix_a[x][y] * constant
        l = []
        s = ""
        print("The result is:")
        for x_ in result:
            l.append(str(x_))
            s = " ,".join(l)
        s_ = s.split(" ,")
        for y_ in s_:
            print("".join(y_).strip("[]").replace(","," "))
        print("\n")

def add_matrices():
        n,m = [int(x) for x in input("Enter size of first matrix: ").split()]
        matrix_a = []
        print("Enter first matrix:")
        for i in range(n):
            i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_a.append(i_)
        n_,m_ = [int(x) for x in input("Enter size of second matrix: ").split()]
        matrix_b = []
        print("Enter second matrix:")
        for j in range(n_):
            j_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_b.append(j_)
        total = []
        for i in range(n):
            i_ = [0 for x in range(m)]
            total.append(i_)

        if n == n_ and m == m_:
            for i in range(n):
                for j in range(m):
                    total[i][j] = matrix_a[i][j] + matrix_b[i][j]
            l = []
            s = ""
            print("The result is:")
            for x in total:
                l.append(str(x))
                s = " ,".join(l)
            s_ = s.split(" ,")
            for y in s_:
                print("".join(y).strip("[]").replace(","," "))
        else:
            print("The operation cannot be performed.")
        print("\n")

def multiply_matrices():
        n,m = [int(x) for x in input("Enter size of first matrix: ").split()]
        matrix_a = []
        print("Enter first matrix:")
        for i in range(n):
            i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_a.append(i_)
        n_,m_ = [int(x) for x in input("Enter size of second matrix: ").split()]
        matrix_b = []
        print("Enter second matrix:")
        for j in range(n_):
            j_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_b.append(j_)
        result = []
        for i in range(n):
            i_ = [0 for x in range(m_)]
            result.append(i_)

        if m == n_:

            for i in range(n):
                for k in range(n_):
                    for j in range(m_):
                        result[i][j] += matrix_a[i][k] * matrix_b[k][j]

            l = []
            s = ""
            print("The result is:")
            for x in result:
                l.append(str(x))
                s = " ,".join(l)
            s_ = s.split(" ,")
            for y in s_:
                print("".join(y).strip("[]").replace(","," "))
        else:
            print("The operation cannot be performed.")
        print("\n")

def transpose():
    user_choice = input("""1. Main diagonal
2. Side diagonal
3. Vertical line
4. Horizontal line
Your choice: """)
    n,m = [int(x) for x in input("Enter size of matrix: ").split()]
    matrix_a = []
    print("Enter matrix:")
    for i in range(n):
        i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
        matrix_a.append(i_)
    result = []
    for i in range(m if user_choice == "1" or user_choice == "2" else n):
        i_ = [0 for x in range(n if user_choice == "1" or user_choice == "2" else m)]
        result.append(i_)
    for i in range(n):
        for j in range(m):
            if user_choice == "1":
                result[j][i] = matrix_a[i][j]
            elif user_choice == "2":
                result[(m-1)-j][(n-1)-i] = matrix_a[i][j]
            elif user_choice == "3":
                result[i][(m-1)-j] = matrix_a[i][j]
            elif user_choice == "4":
                result[(n-1)-i][j] = matrix_a[i][j]

    l = []
    s = ""
    print("The result is:")
    for x_ in result:
        l.append(str(x_))
        s = " ,".join(l)
    s_ = s.split(" ,")
    for y_ in s_:
        print("".join(y_).strip("[]").replace(",", " "))
    print("\n")

def matrix_minor(m,i,j):
    return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

def det(m):
   #base case for 2x2 matrix
    if len(m) == 2:
        return (m[0][0] * m[1][1]) - (m[0][1] * m[1][0])
    elif len(m) == 1:
        return m[0][0]

    determinant = 0
    for c in range(len(m)):
        determinant += ((-1)**c) * m[0][c] * det(matrix_minor(m,0,c))
    return determinant

def matrix_det():
        n,m = [int(x) for x in input("Enter size of matrix: ").split()]
        matrix_a = []
        print("Enter matrix:")
        for i in range(n):
            i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_a.append(i_)
        print(f"The result is:\n{det(matrix_a)}")
        print("\n")

def inverse():
        n,m = [int(x) for x in input("Enter size of matrix: ").split()]
        matrix_a = []
        print("Enter matrix:")
        for i in range(n):
            i_ = [int(x) if x.isdigit() else float(x) for x in input().split()]
            matrix_a.append(i_)
        temp = []
        for i in range(n):
            i_ = [0 for x in range(m)]
            temp.append(i_)
        determinant = det(matrix_a)
        if n == 2:
            return [[m[1][1]/determinant, -1*m[0][1]/determinant],
                [-1*m[1][0]/determinant, m[0][0]/determinant]]
        elif determinant == 0:
            print("This matrix doesn't have an inverse.")

        #find matrix of cofactors
        cofactors = []
        for r in range(n):
            cofactorRow = []
            for c in range(n):
                minor = matrix_minor(matrix_a,r,c)
                cofactorRow.append(((-1)**(r+c)) * det(minor))
            cofactors.append(cofactorRow)

        #transpose cofactor
        for i in range(n):
            for j in range(n):
                temp[j][i] = cofactors[i][j]

        for r in range(len(temp)):
            for c in range(len(temp)):
                temp[r][c] = round(temp[r][c]/determinant,3)

        l = []
        s = ""
        print("The result is:")
        for x_ in temp:
            l.append(str(x_))
            s = " ,".join(l)
        s_ = s.split(" ,")
        for y_ in s_:
            print("".join(y_).strip("[]").replace(",", " "))
        print("\n")

while True:

    user_choice = input("""1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
4. Transpose matrix
5. Calculate a determinant
6. Inverse matrix
0. Exit
Your choice: """)
    if user_choice == "0":
        break
    elif user_choice == "1":
        add_matrices()
    elif user_choice == "2":
        constant_x_matrix()
    elif user_choice == "3":
        multiply_matrices()
    elif user_choice == "4":
        transpose()
    elif user_choice == "5":
        matrix_det()
    elif user_choice == "6":
        inverse()


import board, pieces, numpy

class Heuristics:

    # The tables denote the points scored for the position of the pieces on the board.

    SPHERE_TABLE = numpy.array([
        [ 0,  0,  0,  0,  0,  0,  0,  0],
        [ 5, 10, 10,-20,-20, 10, 10,  5],
        [ 5, -5,-10,  0,  0,-10, -5,  5],
        [ 0,  0,  0, 20, 20,  0,  0,  0],
        [ 5,  5, 10, 25, 25, 10,  5,  5],
        [10, 10, 20, 30, 30, 20, 10, 10],
        [50, 50, 50, 50, 50, 50, 50, 50],
        [ 0,  0,  0,  0,  0,  0,  0,  0]
    ])

    @staticmethod
    def evaluate(board):
        material = Heuristics.get_material_score(board)

        sphere = Heuristics.get_piece_position_score(board, pieces.Sphere.PIECE_TYPE, Heuristics.SPHERE_TABLE)

        return material + sphere

    # Returns the score for the position of the given type of piece.
    # The table is the 2d numpy array used for the scoring. Example: Heuristics.SPHERE_TABLE
    @staticmethod
    def get_piece_position_score(board, piece_type, table):
        white = 0
        black = 0
        for x in range(7):
            for y in range(7):
                piece = board.Spherepieces[x][y]
                if (piece != 0):
                    if (piece.piece_type == piece_type):
                        if (piece.color == pieces.Piece.PURPLE):
                            white += table[x][y]
                        else:
                            black += table[7 - x][y]

        return white - black

    @staticmethod
    def get_material_score(board):
        white = 0
        black = 0
        for x in range(7):
            for y in range(7):
                piece = board.Spherepieces[x][y]
                if (piece != 0):
                    if (piece.color == pieces.Piece.PURPLE):
                        white += piece.value
                    else:
                        black += piece.value

        return white - black

class AI:

    INFINITE = 10000000

    @staticmethod
    def get_ai_move(Sphereboard, invalid_moves,alg_no,game_type):

        if game_type == '1' and alg_no == '0':
            pcs = pieces.Piece.RED
        elif game_type == '1' and alg_no == '1':
            pcs = pieces.Piece.PURPLE
        else :
            pcs = pieces.Piece.RED

        best_move = 0
        best_score = AI.INFINITE
        for move in Sphereboard.get_possible_moves(pcs):
            if (AI.is_invalid_move(move, invalid_moves)):
                continue

            copy = board.Board.clone(Sphereboard)
            copy.perform_move(move)

            if alg_no == 1:
                score = AI.alphabeta(copy, 2, -AI.INFINITE, AI.INFINITE, True)
            else:
                score = AI.minimax(copy, 2, True)

            if (score < best_score):
                best_score = score
                best_move = move

        # Checkmate.
        if (best_move == 0):
            return 0

        copy = board.Board.clone(Sphereboard)
        copy.perform_move(best_move)
        if (copy.is_check(pcs)):
            invalid_moves.append(best_move)
            return AI.get_ai_move(Sphereboard, invalid_moves,alg_no, game_type)

        return best_move

    @staticmethod
    def is_invalid_move(move, invalid_moves):
        for invalid_move in invalid_moves:
            if (invalid_move.equals(move)):
                return True
        return False

    @staticmethod
    def minimax(Sphereboard, depth, maximizing):
        if (depth == 0):
            return Heuristics.evaluate(Sphereboard)

        if (maximizing):
            best_score = -AI.INFINITE
            for move in Sphereboard.get_possible_moves(pieces.Piece.PURPLE):
                copy = board.Board.clone(Sphereboard)
                copy.perform_move(move)

                score = AI.minimax(copy, depth-1, False)
                best_score = max(best_score, score)

            return best_score
        else:
            best_score = AI.INFINITE
            for move in Sphereboard.get_possible_moves(pieces.Piece.RED):
                copy = board.Board.clone(Sphereboard)
                copy.perform_move(move)

                score = AI.minimax(copy, depth-1, True)
                best_score = min(best_score, score)

            return best_score

    @staticmethod
    def alphabeta(Sphereboard, depth, a, b, maximizing):
        if (depth == 0):
            return Heuristics.evaluate(Sphereboard)

        if (maximizing):
            best_score = -AI.INFINITE
            for move in Sphereboard.get_possible_moves(pieces.Piece.PURPLE):
                copy = board.Board.clone(Sphereboard)
                copy.perform_move(move)

                best_score = max(best_score, AI.alphabeta(copy, depth-1, a, b, False))
                a = max(a, best_score)
                if (b <= a):
                    break
            return best_score
        else:
            best_score = AI.INFINITE
            for move in Sphereboard.get_possible_moves(pieces.Piece.RED):
                copy = board.Board.clone(Sphereboard)
                copy.perform_move(move)

                best_score = min(best_score, AI.alphabeta(copy, depth-1, a, b, True))
                b = min(b, best_score)
                if (b <= a):
                    break
            return best_score

class Move:

    def __init__(self, xfrom, yfrom, xto, yto, castling_move):
        self.xfrom = xfrom
        self.yfrom = yfrom
        self.xto = xto
        self.yto = yto
        self.castling_move = castling_move

    # Returns true iff (xfrom,yfrom) and (xto,yto) are the same.
    def equals(self, other_move):
        return self.xfrom == other_move.xfrom and self.yfrom == other_move.yfrom and self.xto == other_move.xto and self.yto == other_move.yto

    def to_string(self):
        return "(" + str(self.xfrom) + ", " + str(self.yfrom) + ") -> (" + str(self.xto) + ", " + str(self.yto) + ")"


import torch
from .metric import Metric

class ClipMeanPerclassAccuracyMetric(Metric):
    """Don't need activation softmax for clip accuracy calculation.
    """
    def __init__(self, *args, exclude_classes_less_sample_than = 1, **kwargs):
        super().__init__(*args, **kwargs)
        assert exclude_classes_less_sample_than >= 1
        self.exclude_classes_less_sample_than = exclude_classes_less_sample_than

    def clean_data(self):
        super().clean_data()
        self.num_seen_samples = None
        self.num_true_positives = None

    def add_clip_predictions(self, video_ids, clip_predictions, labels):
        video_ids, clip_predictions, labels = super().add_clip_predictions(video_ids, clip_predictions, labels)
        if video_ids is None:
            return      # sometimes, after filtering the samples, there can be no samples to do anything.

        assert labels.dim() in [1,2], f'labels has to be 1D or 2D tensor but got {labels.dim()}-D.'
        if labels.dim() == 2:
            # Convert 2D one-hot label to 1D label
            labels = labels.argmax(dim=1)

        if self.num_seen_samples is None:
            self.num_seen_samples = [0] * self.num_classes
            self.num_true_positives = [0] * self.num_classes

        pred_labels = torch.argmax(clip_predictions, dim=1)
        for pred, label in zip(pred_labels, labels):
            self.num_seen_samples[label] += 1
            if pred == label:
                self.num_true_positives[label] += 1

    def calculate_metrics(self):
        if self.num_seen_samples is None:
            self.last_calculated_metrics = 0.
        else:
            filtered_perclass_accuracies = [tp / sample_count for tp, sample_count in zip(self.num_true_positives, self.num_seen_samples) if sample_count >= self.exclude_classes_less_sample_than]
            if len(filtered_perclass_accuracies) > 0:
                self.last_calculated_metrics = sum(filtered_perclass_accuracies) / len(filtered_perclass_accuracies)
            else:
                self.last_calculated_metrics = 0.

    def types_of_metrics(self):
        return float

    def tensorboard_tags(self):
        if self.exclude_classes_less_sample_than == 1:
            return 'Clip mean per-class accuracy'
        else:
            return f'Clip mean per-class accuracy {self.exclude_classes_less_sample_than}+'

    def get_csv_fieldnames(self):
        if self.exclude_classes_less_sample_than == 1:
            return f'{self.split}_meanperclassacc'
        else:
            return f'{self.split}_meanperclassacc{self.exclude_classes_less_sample_than}+'

    def logging_msg_iter(self):
        """
        Return:
            None to skip logging this metric
            or a single str that combines all self.last_calculated_metrics
        """
        if self.split == 'train':
            prefix = ''
        else:
            prefix = f'{self.split}_'

        if self.exclude_classes_less_sample_than == 1:
            suffix = ''
        else:
            suffix = f'{self.exclude_classes_less_sample_than}+'

        message = f'{prefix}meanperclassacc{suffix}: {self.last_calculated_metrics:.4f}'
        return message

    def logging_msg_epoch(self):
        """
        Return:
            None to skip logging this metric
            or a single str that combines all self.last_calculated_metrics
        """
        return self.logging_msg_iter()

    def plot_legend_labels(self):
        """
        Return:
            either tuple or a single str
        """
        if self.exclude_classes_less_sample_than == 1:
            suffix = ''
        else:
            suffix = f' ({self.exclude_classes_less_sample_than}+ samples)'

        if self.split == 'train':
            return f'Training average per-class accuracy{suffix}'
        elif self.split == 'val':
            return f'Validation average per-class accuracy{suffix}'
        elif self.split == 'multicropval':
            return f'Multicrop validation average per-class accuracy{suffix}'
        else:
            return f'{self.split} average per-class accuracy{suffix}'

    def plot_file_basenames(self):
        """
        Return:
            either tuple or a single str
        """
        # output plot file names will be e.g.) accuracy.png/pdf, accuracy_top5.png/pdf, ...
        if self.exclude_classes_less_sample_than == 1:
            suffix = ''
        else:
            suffix = f'_{self.exclude_classes_less_sample_than}+'
        return f'mean_perclass_accuracy{suffix}'

    @staticmethod
    def is_better(value_1, value_2):
        """Metric comparison function

        params:
            two values of the metric

        return:
            True if value_1 is better. False if value_2 is better or they're equal.
        """
        return value_1 > value_2

    def __len__(self):
        return sum(self.num_seen_samples)


class Bitset:

    def __init__(self, size: int):
        self.num = 0
        self.sum = 0
        self.size = size

    def fix(self, idx: int) -> None:
        xor_mask = self._get_xor_mask(idx)
        bit_offset = self.size - idx - 1
        if (self.num >> bit_offset) % 2 == 0:
            if self.sum < self.size:
                self.sum += 1
            self.num = self.num ^ xor_mask

    def unfix(self, idx: int) -> None:
        xor_mask = self._get_xor_mask(idx)
        bit_offset = self.size - idx - 1
        if xor_mask <= self.num and (self.num >> bit_offset) % 2 == 1:
            if self.sum > 0:
                self.sum -= 1
            self.num = self.num ^ xor_mask

    def flip(self) -> None:
        self.num = self.num ^ self._get_full_bitset()
        self.sum = self.size - self.sum

    def all(self) -> bool:
        return self.sum == self.size

    def one(self) -> bool:
        return self.sum >= 1

    def count(self) -> int:
        return self.sum

    def toString(self) -> str:
        bits = bin(self.num)[2:]
        return "0" * (self.size - len(bits)) + bits

    def _get_xor_mask(self, index: int) -> int:
        return 1 << (self.size - index - 1)

    def _get_full_bitset(self) -> int:
        return 2 ** self.size - 1

class Solution:
    def __init__(self):
        self.commands_output = list()

    def run_commands(self, commands, arguments):
        bitset = None
        for index in range(len(commands)):
            if commands[index] == "Bitset":
                bitset = Bitset(arguments[index][0])
                self.commands_output.append(None)
                continue
            if commands[index] == "unfix":
                self.commands_output.append(bitset.unfix(arguments[index][0]))
                continue
            if commands[index] == "fix":
                self.commands_output.append(bitset.fix(arguments[index][0]))
                continue
            if commands[index] == "flip":
                self.commands_output.append(bitset.flip())
                continue
            if commands[index] == "all":
                self.commands_output.append(bitset.all())
                continue
            if commands[index] == "one":
                self.commands_output.append(bitset.one())
                continue
            if commands[index] == "count":
                self.commands_output.append(bitset.count())
                continue
            if commands[index] == "toString":
                self.commands_output.append(bitset.toString())
                continue

    def show_output(self):
        return self.commands_output


# ###
# Mathematical expression recognition tool.
# Written as a part of masters thesis at VUT FIT Brno, 2022

# Author: Vladislav Halva
# Login: xhalva04
# ###

from torch import nn
from torch_geometric.nn import Linear

from src.model.AttentionBlock import AttentionBlock
from src.model.GCN import GCN

class DecoderBlock(nn.Module):
    """
    Decoder layer containing modified GCN and attention to source graph.
    """
    def __init__(self, device, f_size, in_size, out_size, att_size, att_dropout_p, init_size, is_first=False):
        """
        :param device: device
        :param f_size: source graph node features size
        :param in_size: output graph in node features size
        :param out_size: output graph out node features size
        :param att_size: attention vector size
        :param att_dropout_p: dropout probability
        :param init_size: output graph initial node embedding size
        :param is_first: True if layer is first in decoder
        """
        super(DecoderBlock, self).__init__()
        self.device = device
        self.f_size = f_size
        self.in_size = in_size
        self.out_size = out_size
        self.init_size = init_size
        self.is_first = is_first

        self.gcn = GCN(device, in_size, out_size, is_first)
        self.attBlock = AttentionBlock(device, f_size, out_size, init_size, att_size, att_dropout_p, is_first=is_first)
        self.lin = Linear(out_size, out_size, bias=True, weight_initializer='glorot')

    def reset_parameters(self):
        self.lin.reset_parameters()

    def forward(self, f, x, edge_index, edge_type, f_batch, x_batch, x_init):
        """
        :param f: source graph node features
        :param x: output graph node features
        :param edge_index: output graph edge index
        :param edge_type: output graph edge types
        :param f_batch: source graph nodes batch indices
        :param x_batch: output graph nodes batch indices
        :param x_init: output graph initial node embeddings
        :return: output graph new node features, attention alpha coefficients
        """
        # process output graph with GCN
        h = self.gcn(x, edge_index, edge_type)
        # get context vector from source graph
        c, alpha = self.attBlock(f, h, edge_index, edge_type, f_batch, x_batch, x_init)
        # combine
        z = h + c
        z = self.lin(z)
        return z, alpha


def makeUV(s):
    cntL = 0
    cntR = 0
    u = ''
    v = ''

    for i in s:
        if i == '(':
            cntL += 1
        else:
            cntR += 1
        u += i

        if cntL == cntR:
            break

    v = s.replace(u, '', 1)

    return u, v

def solution(p):
    answer = ''

    #step1
    if p == '':
        return ''

    #step2
    u, v = makeUV(p)

    #step3
    if u[-1] == ')': #u의 마지막이 )이면 무조건 올바름 !중요 포인트!
        u += solution(v)

        return u

    #step4
    answer += '('
    answer += solution(v)
    answer += ')'
    for i in range(1, len(u)-1):
        if u[i] == '(':
            answer += ')'
        else:
            answer += '('

    return answer


# from concurrent.futures import thread

import os

try:
   from time import sleep
   import discord
   from discord.ext import commands
   import requests
   from datetime import datetime

   intents = discord.Intents.default() #Create an instance of a Client. This client is our connection to Discord.
   intents.message_content = True
   bot = commands.Bot(command_prefix="#",intents=intents)

   def giveMeTime(letter):
      req = requests.get("https://timeapi.io/api/Time/current/zone?timeZone=Asia/Riyadh").json()
      return req[letter]

   @bot.event
   async def on_ready():
      await times()

   def athkar(letter):
      thkr=requests.get(f"https://azkar-api.nawafhq.repl.co/zekr?{letter}&json").json()
      x=str(thkr["content"])
      return x

   async def sleepp(): # اذكار قبل النوم
      channel = bot.get_channel(channelId)
      thkr=athkar("bs")
      await channel.send(thkr)
      channel = bot.get_channel(channelId)
      await channel.send(thkr)

   async def Massa():
      channel = bot.get_channel(channelId)
      thkr=athkar("e")
      await channel.send(thkr)
      channel = bot.get_channel(channelId)
      await channel.send(thkr)

   async def Morning():
      print("in morning")
      channel = bot.get_channel(channelId)
      thkr=athkar("m")
      await channel.send(thkr)
      channel = bot.get_channel(channelId)
      await channel.send(thkr)

   async def Pray(h,m,p):

      channel = bot.get_channel(channelId)
      if(h==4 and m==00 and p=="AM"):
         await channel.send("حان وقت صلاة الفجر")
         sleep(900)
         await channel.send(athkar("as"))

      elif(h==11 and m==45 and p=="AM"):
         await channel.send("حان وقت صلاة الظهر")
         sleep(900)
         await channel.send(athkar("as"))

      elif(h==15 and m==15 and  p=="PM"):
         await channel.send("حان وقت صلاة العصر")
         sleep(900)
         await channel.send(athkar("as"))

      elif(h==18 and m==10 and p=="PM"):
         await channel.send("حان وقت صلاة المغرب")
         sleep(900)
         await channel.send(athkar("as"))

      elif(h==19 and m==40 and p=="PM"):
         await channel.send("حان وقت صلاة العشاء")
         sleep(900)
         await channel.send(athkar("as"))

   async def times():
      s=00
      print("I'M in times")
      try:
         while True:

          h=giveMeTime("hour")
          m=giveMeTime("minute")

          if(h>=0 and h<=11):

           p="AM"
          else:
            p="PM"

          print(h,m,s,p)
          if (h == 6 and m == 14 and p=="AM"):
            await Morning()
            sleep(60)

          elif h == 23 and m ==35 and p == 'PM':
            await sleepp()
            sleep(60)

          elif((h==4 and m==00 and p=="AM") or(h==11 and m==45 and p=="AM")or (h==15 and m==15 and p=="PM") or (h==18 and m==10 and p=="PM") or (h==19 and m==40 and p=="PM")):
            await Pray(h,m,p)

            sleep(60)
          elif h == 21 and m == 35 and p == 'PM':
            await sleepp()
            sleep(60)
          elif h == 16 and m == 30 and p == 'PM':
            await Massa()
            sleep(60)
          sleep(20)

      except Exception as e:
       async def alert():
         channel = bot.get_channel(channelId)
         await channel.send(str(e))
       await alert()

except:
   os.system("pip install discord")
   os.system("pip install requests")
   os.system("pip install time")

bot.run("Token")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 29 14:03:59 2018

@author: sinsakuokazaki
"""

def estimatePi(i):
    s = 0
    for i in range(1, i+1):
        s += (-1)**(i + 1) / (2 * i - 1)

    mI = 4 * s
    return mI

print(format("i", "<15s"), end = "")
print(format("m(i)", "<6s"), end="\n\n")
for i in range(1, 902, 100):
    print(format(i, "<15d"), end ="")
    print(format(estimatePi(i), "<6.4f"))


import os
import subprocess
import pytest
from numpy.testing import assert_almost_equal as aa_eq
import libtbx.load_env
from amber_adaptbx.tests.utils import get_fn, tempfolder
from glob import glob

@pytest.mark.parametrize('code', ['2igd'])
def test_cleaning_unused_files(code):
    pdb_fn = get_fn('{code}/{code}.pdb'.format(code=code))

    command_non_les = ['phenix.AmberPrep', pdb_fn, 'LES=False']
    expected_files_non_les = set([
        '4phenix_{}.pdb'.format(code),
        '4amber_{}.prmtop'.format(code),
        '4amber_{}.rst7'.format(code),
    ])

    command_les = ['phenix.AmberPrep', pdb_fn, 'LES=True']

    expected_files_les = set()
    expected_files_les.update(expected_files_non_les)
    expected_files_les.update(
        set([
            '4phenix_{}.pdb'.format(code),
            '4amber_{}.prmtop'.format(code),
            '4amber_{}.rst7'.format(code),
            '4amber_{}.LES.pdb'.format(code),
            'addles.in',
        ]))

    with tempfolder():
        subprocess.check_call(command_les)
        file_set = set(glob('*'))
        assert sorted(expected_files_les) == sorted(file_set)

    with tempfolder():
        subprocess.check_call(command_non_les)
        file_set = set(glob('*'))
        assert sorted(expected_files_non_les) == sorted(file_set)


# Typ
from distutils.log import ERROR, error
from fileinput import filename

strVar: str = "Hello World"
print(strVar)

# Just some string stuff
s = 'f ln \ns ln'
print(s)
s = r'f ln\nstill f ln'
print(s)
s = """
Multiple lines
"""  # Code rev
escape = '\''
print(escape)
x = 'ö'
y = x.encode('UTF-8')
print(y)
s = 'Just some random string'
print(s)
print(s[0])  # Zero based
print(s[-1])  # Back
print(s[2:10])  # Substring
print(s[:4])  # Substring - Shorthanded
print(s[::-1])  # Back

# Dirs
d = {              # Val is mutable
    'key': 'val',  # Key is immutable and unique
    'quant': 3,
    'color': 'green'
}
d['quant'] += 1
# Unmachable key won't be created - not fechtable
# d['num'] += 1

print(d.get('quant'))
# d.pop('quant')
# del d['quant']  # Equal to pop
print(d.values())
print(d.items())
print(len(d))

# Sets
s = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(s)
s.add(11)
print(s)
s.remove(11)  # Error if not found
print(s)
s.discard(11)  # No error if not found
print(s)
s.pop()  # First element
print(s)
s.clear()  # Empty set
print(s)

# Statements of control
# Not writing this

x = 'Just some string'
while x:
    print(x)
    x = x[1:]  # Slice

# IO Streams
filename = 'Path/To/File.txt'
try:
    with open(filename, mode='r') as f:
        for line in f:
            print(line)
        f.readline()  # Read one line
        f.readlines()  # Read all lines
        f.read()  # Read all

except FileNotFoundError as e:  # Is just a demo path
    error(e)

# Functions
# Not writing this
# But

def multiply(x, y):
    pass

var = multiply
print(var(2, 3))

# Unittesting - more flexible than doctest


#
# @lc app=leetcode id=2544 lang=python3
#
# [2544] Alternating Digit Sum
#

# @lc code=start
class Solution:
    def alternateDigitSum(self, n: int) -> int:
        a=list(str(n))
        A=[]
        for i in a:
            A.append(int(i))
        b=[]
        for j in range (len(A)):
            if j%2==0:
              b.append(A[j])
            else:
              b.append(A[j]*(-1))
        return sum(b)

# @lc code=end


from datetime import date

from odoo.tests.common import TransactionCase

class TestStockPickingPurchaseOrderLink(TransactionCase):
    def setUp(self):
        super(TestStockPickingPurchaseOrderLink, self).setUp()
        self.stock_location_obj = self.env["stock.location"]
        self.stock_picking_type_obj = self.env["stock.picking.type"]
        self.stock_picking_obj = self.env["stock.picking"]
        self.product_product_obj = self.env["product.product"]
        self.warehouse = self.env["stock.warehouse"].create(
            {"name": "warehouse - test", "code": "WH-TEST"}
        )

        self.product = self.product_product_obj.create(
            {
                "name": "product_template_obj - Test",
                "type": "product",
                "standard_price": 100.00,
            }
        )
        self.partner = self.env["res.partner"].create({"name": "Vendor - test"})
        self.picking_type = self.stock_picking_type_obj.search(
            [("warehouse_id", "=", self.warehouse.id), ("code", "=", "incoming")]
        )
        purchase_order = self.env["purchase.order"].create(
            {
                "partner_id": self.partner.id,
                "order_line": [
                    (
                        0,
                        0,
                        {
                            "name": self.product.name,
                            "product_id": self.product.id,
                            "product_qty": 1.0,
                            "product_uom": self.product.uom_po_id.id,
                            "price_unit": 10.0,
                            "date_planned": date.today(),
                        },
                    )
                ],
            }
        )
        purchase_order.button_confirm()
        self.picking = self.stock_picking_obj.search(
            [("purchase_id", "=", purchase_order.id)]
        )

    def test_picking_to_purchase_order(self):
        result = self.picking.action_view_purchase_order()
        self.assertEqual(result["res_id"], self.picking.purchase_id.id)